text:
"""Tests for UnicodeEncode op from ragged_string_ops."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl.testing import parameterized
import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors_impl as errors
from tensorflow.python.framework import test_util
from tensorflow.python.ops.ragged import ragged_factory_ops
from tensorflow.python.ops.ragged import ragged_string_ops
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.ops.ragged import ragged_tensor_value
from tensorflow.python.platform import test

class UnicodeEncodeOpTest(test.TestCase, parameterized.TestCase):

  def assertRaggedEqual(self, rt, expected):
    with self.cached_session() as sess:
      value = sess.run(rt)
      if isinstance(value, np.ndarray):
        value = value.tolist()
      elif isinstance(value, ragged_tensor_value.RaggedTensorValue):
        value = value.to_list()
      self.assertEqual(value, expected)

  def testScalar(self):
    with self.cached_session():
      with self.assertRaises(ValueError):
        ragged_string_ops.unicode_encode(72, "UTF-8")
    with self.cached_session():
      with self.assertRaises(ValueError):
        ragged_string_ops.unicode_encode(constant_op.constant(72), "UTF-8")

  def testRequireParams(self):
    with self.cached_session():
      with self.assertRaises(TypeError):
        ragged_string_ops.unicode_encode()
    with self.cached_session():
      with self.assertRaises(TypeError):
        ragged_string_ops.unicode_encode(72)
    with self.cached_session():
      with self.assertRaises(TypeError):
        ragged_string_ops.unicode_encode(encoding="UTF-8")

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  def testStrictErrors(self, encoding):
    test_value = np.array([72, 101, 2147483647, -1, 111], np.int32)
    with self.cached_session() as session:
      with self.assertRaises(errors.InvalidArgumentError):
        session.run(
            ragged_string_ops.unicode_encode(test_value, encoding, "strict"))

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def testIgnoreErrors(self, encoding):
    test_value = np.array([72, 101, 2147483647, -1, 111], np.int32)
    expected_value = u"Heo".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding,
                                                         "ignore")
    with self.cached_session() as session:
      result = session.run(unicode_encode_op)
      self.assertIsInstance(result, bytes)
      self.assertAllEqual(result, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def testReplaceErrors(self, encoding):
    test_value = np.array([72, 101, 2147483647, -1, 111], np.int32)
    expected_value = u"He\U0000fffd\U0000fffdo".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding,
                                                         "replace")
    self.assertRaggedEqual(unicode_encode_op, expected_value)

    # Test custom replacement character
    test_value = np.array([72, 101, 2147483647, -1, 111], np.int32)
    expected_value = u"Heooo".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding,
                                                         "replace", 111)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

    # Verify "replace" is default
    test_value = np.array([72, 101, 2147483647, -1, 111], np.int32)
    expected_value = u"He\U0000fffd\U0000fffdo".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

    # Replacement_char must be within range
    test_value = np.array([72, 101, 2147483647, -1, 111], np.int32)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding,
                                                         "replace", 1114112)
    with self.assertRaises(errors.InvalidArgumentError):
      self.evaluate(unicode_encode_op)

  # -- regular Tensor tests -- #

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def testVector(self, encoding):
    test_value = np.array([72, 101, 108, 108, 111], np.int32)
    expected_value = u"Hello".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

    test_value = np.array([72, 101, 195, 195, 128516], np.int32)
    expected_value = u"He\xc3\xc3\U0001f604".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

    # Single character string
    test_value = np.array([72], np.int32)
    expected_value = u"H".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

    test_value = np.array([128516], np.int32)
    expected_value = u"\U0001f604".encode(encoding)
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def testMatrix(self, encoding):
    test_value = np.array(
        [[72, 128516, 108, 108, 111], [87, 128516, 114, 108, 100]], np.int32)
    expected_value = [
        u"H\U0001f604llo".encode(encoding), u"W\U0001f604rld".encode(encoding)
    ]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertAllEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def test3DimMatrix(self, encoding):
    test_value = constant_op.constant(
        [[[72, 101, 108, 108, 111], [87, 111, 114, 108, 100]],
         [[102, 105, 120, 101, 100], [119, 111, 114, 100, 115]],
         [[72, 121, 112, 101, 114], [99, 117, 98, 101, 46]]], np.int32)
    expected_value = [[u"Hello".encode(encoding), u"World".encode(encoding)],
                      [u"fixed".encode(encoding), u"words".encode(encoding)],
                      [u"Hyper".encode(encoding), u"cube.".encode(encoding)]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def test4DimMatrix(self, encoding):
    test_value = constant_op.constant(
        [[[[72, 101, 108, 108, 111]], [[87, 111, 114, 108, 100]]],
         [[[102, 105, 120, 101, 100]], [[119, 111, 114, 100, 115]]],
         [[[72, 121, 112, 101, 114]], [[99, 117, 98, 101, 46]]]], np.int32)
    expected_value = [[[u"Hello".encode(encoding)],
                       [u"World".encode(encoding)]],
                      [[u"fixed".encode(encoding)],
                       [u"words".encode(encoding)]],
                      [[u"Hyper".encode(encoding)],
                       [u"cube.".encode(encoding)]]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  # -- Ragged Tensor tests -- #

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def testRaggedMatrix(self, encoding):
    test_value = ragged_factory_ops.constant(
        [[72, 195, 108, 108, 111], [87, 128516, 114, 108, 100, 46]], np.int32)
    expected_value = [
        u"H\xc3llo".encode(encoding), u"W\U0001f604rld.".encode(encoding)
    ]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def test3DimMatrixWithRagged2ndDim(self, encoding):
    test_value = ragged_factory_ops.constant(
        [[[72, 101, 108, 108, 111], [87, 111, 114, 108, 100]],
         [[102, 105, 120, 101, 100]],
         [[72, 121, 112, 101, 114], [119, 111, 114, 100, 115],
          [99, 117, 98, 101, 46]]], np.int32)
    expected_value = [[u"Hello".encode(encoding), u"World".encode(encoding)],
                      [u"fixed".encode(encoding)],
                      [
                          u"Hyper".encode(encoding), u"words".encode(encoding),
                          u"cube.".encode(encoding)
                      ]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def test3DimMatrixWithRagged3rdDim(self, encoding):
    test_value = ragged_factory_ops.constant(
        [[[72, 101, 108, 108, 111], [87, 111, 114, 108, 100, 46]],
         [[68, 111, 110, 39, 116], [119, 195, 114, 114, 121, 44, 32, 98, 101]],
         [[128516], []]], np.int32)
    expected_value = [[u"Hello".encode(encoding), u"World.".encode(encoding)],
                      [
                          u"Don't".encode(encoding),
                          u"w\xc3rry, be".encode(encoding)
                      ], [u"\U0001f604".encode(encoding), u"".encode(encoding)]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def test3DimMatrixWithRagged2ndAnd3rdDim(self, encoding):
    test_value = ragged_factory_ops.constant(
        [[[72, 101, 108, 108, 111], [87, 111, 114, 108, 100, 46]], [],
         [[128516]]], np.int32)
    expected_value = [[u"Hello".encode(encoding), u"World.".encode(encoding)],
                      [], [u"\U0001f604".encode(encoding)]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def test4DimRaggedMatrix(self, encoding):
    test_value = ragged_factory_ops.constant(
        [[[[72, 101, 108, 108, 111], [87, 111, 114, 108, 100]]],
         [[[]], [[72, 121, 112, 101]]]], np.int32)
    expected_value = [[[u"Hello".encode(encoding), u"World".encode(encoding)]],
                      [[u"".encode(encoding)], [u"Hype".encode(encoding)]]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

  @parameterized.parameters("UTF-8", "UTF-16-BE", "UTF-32-BE")
  @test_util.run_v1_only("b/120545219")
  def testRaggedMatrixWithMultiDimensionInnerValues(self, encoding):
    test_flat_values = constant_op.constant([[[72, 101, 108, 108, 111],
                                              [87, 111, 114, 108, 100]],
                                             [[102, 105, 120, 101, 100],
                                              [119, 111, 114, 100, 115]],
                                             [[72, 121, 112, 101, 114],
                                              [99, 117, 98, 101, 46]]])
    test_row_splits = [
        constant_op.constant([0, 2, 3], dtype=np.int64),
        constant_op.constant([0, 1, 1, 3], dtype=np.int64)
    ]
    test_value = ragged_tensor.RaggedTensor.from_nested_row_splits(
        test_flat_values, test_row_splits)
    expected_value = [[[[u"Hello".encode(encoding), u"World".encode(encoding)]],
                       []],
                      [[[u"fixed".encode(encoding), u"words".encode(encoding)],
                        [u"Hyper".encode(encoding),
                         u"cube.".encode(encoding)]]]]
    unicode_encode_op = ragged_string_ops.unicode_encode(test_value, encoding)
    self.assertRaggedEqual(unicode_encode_op, expected_value)

if __name__ == "__main__":
  test.main()


text:
package org.mortbay.jetty.servlet;

import junit.framework.TestCase;

public abstract class AbstractSessionTest extends TestCase
{
    public static final String __host1 = "localhost";
    public static final String __host2 = __host1;
    public static final String __port1 = "8010";
    public static final String __port2 = "8011";
    SessionTestServer _server1;
    SessionTestServer _server2;

    public abstract SessionTestServer newServer1 ();

    public abstract SessionTestServer newServer2();

    public void setUp () throws Exception
    {
        _server1 = newServer1();
        _server2 = newServer2();
        _server1.start();
        _server2.start();
    }

    public void tearDown () throws Exception
    {
        if (_server1 != null)
            _server1.stop();
        if (_server2 != null)
            _server2.stop();

        _server1=null;
        _server2=null;
    }

    public void testSessions () throws Exception
    {
        SessionTestClient client1 = new SessionTestClient("http://"+__host1+":"+__port1);
        SessionTestClient client2 = new SessionTestClient("http://"+__host2+":"+__port2);
        // confirm that user has no session
        assertFalse(client1.send("/contextA", null));
        String cookie1 = client1.newSession("/contextA");
        assertNotNull(cookie1);
        System.err.println("cookie1: " + cookie1);

        // confirm that client2 has the same session attributes as client1
        assertTrue(client1.setAttribute("/contextA", cookie1, "foo", "bar"));
        assertTrue(client2.hasAttribute("/contextA", cookie1, "foo", "bar"));

        // confirm that /contextA would share same sessionId as /contextB
        assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie1));
        assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie1));
        assertTrue(client1.send("/contextB", cookie1));

        // verify that session attributes on /contextA is different from /contextB
        assertFalse(client1.hasAttribute("/contextB/action", cookie1, "foo", "bar"));

        // add new session attributes on /contextB
        client1.setAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy");
        assertTrue(client1.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy"));

        // verify that client2 has same sessionAttributes on /contextB
        // client1's newly added attribute "zzzzz" needs to be flushed to the database first
        // saveInterval is configured at 10s... to test, uncomment the 2 lines below.
        //Thread.sleep(10000);
        //assertTrue(client2.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy"));

        String cookie2 = client2.newSession("/contextA");
        assertNotNull(cookie2);
        System.err.println("cookie2: " + cookie2);

        // confirm that client1 has same session attributes as client2
        assertTrue(client2.setAttribute("/contextA", cookie2, "hello", "world"));
        assertTrue(client1.hasAttribute("/contextA", cookie2, "hello", "world"));

        // confirm that /contextA would share same sessionId as /contextB
        assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie2));
        assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie2));
        assertTrue(client1.send("/contextB", cookie2));

        // Session invalidate on contextA
        assertTrue(client1.invalidate("/contextA", cookie1));

        // confirm that session on contextB has not been invalidated after contextA has been invalidated
        assertTrue(client1.send("/contextB", cookie1));

        // confirm that session on contextA has been deleted
        assertFalse(client1.send("/contextA", cookie1));

        // Session invalidate on contextB
        assertTrue(client1.invalidate("/contextB/action", cookie1));

        // confirm that session on contextB has been deleted
        assertFalse(client1.send("/contextB/action", cookie1));

        // wait for saveInterval and check if the session invalidation has been reflected to the other node
        // to test, uncomment 3 lines below
        //Thread.sleep(10000);
        //assertFalse(client2.send("/contextA", cookie1));
        //assertFalse(client2.send("/contextB/action", cookie1));
    }

    public void testSessionManagerStop() throws Exception
    {
        SessionTestClient client1 = new SessionTestClient("http://"+__host1+":"+__port1);
        SessionTestClient client2 = new SessionTestClient("http://"+__host2+":"+__port2);
        // confirm that user has no session
        assertFalse(client1.send("/contextA", null));
        String cookie1 = client1.newSession("/contextA");
        assertNotNull(cookie1);
        System.err.println("cookie1: " + cookie1);

        // creates a session for contextB
        assertTrue(client1.send("/contextB", cookie1));

        // confirm that /contextA and /contextB sessions are available
        assertTrue(client1.send("/contextA", cookie1));
        assertTrue(client1.send("/contextB/action", cookie1));
        assertTrue(client1.setAttribute("/contextA", cookie1, "a", "b"));
        assertTrue(client1.setAttribute("/contextB/action", cookie1, "c", "d"));

        // confirm that /contextA and /contextB sessions from client2 are available
        assertTrue(client2.send("/contextA", cookie1));
        assertTrue(client2.send("/contextB/action", cookie1));
        assertTrue(client2.hasAttribute("/contextA", cookie1, "a", "b"));
        assertTrue(client2.hasAttribute("/contextB/action", cookie1, "c", "d"));

        // stop sessionManager from node1
        _server1._sessionMgr1.stop();

        // verify session still exists for contextB
        assertTrue(client1.send("/contextB/action", cookie1));
        assertTrue(client1.hasAttribute("/contextB/action", cookie1, "c", "d"));

        // stop sessionManager from node2
        _server2._sessionMgr2.stop();

        // verfiy session still exists for contextA
        assertTrue(client2.send("/contextA", cookie1));
        assertTrue(client2.hasAttribute("/contextA", cookie1, "a", "b"));
    }

    public void testFailover() throws Exception
    {
        SessionTestClient client1 = new SessionTestClient("http://"+__host1+":"+__port1);
        SessionTestClient client2 = new SessionTestClient("http://"+__host2+":"+__port2);
        // confirm that user has no session
        assertFalse(client1.send("/contextA", null));
        String cookie1 = client1.newSession("/contextA");

        assertNotNull(cookie1);
        System.err.println("cookie1: " + cookie1);

        assertTrue(client1.setAttribute("/contextA", cookie1, "a", "b"));

        assertTrue(client2.hasAttribute("/contextA", cookie1, "a", "b"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia athallina H. Magn.

### Remarks
null


text:
import * as React from 'react'
import {StylesCrossPlatform} from '../../styles'
import {IconType} from '../icon.constants-gen'
export type Action = {
  custom?: React.ReactNode
  label?: string // TODO: make this required after updates are fully integrated,
  color?: string // TODO: narrow this type
  icon?: IconType
  iconColor?: string
  onPress?: (() => void) | null
}
export type Props = {
  // TODO: remove these after updates are fully integrated
  onBack?: (() => void) | null
  onCancel?: (() => void) | null
  customCancelText?: string
  rightActionLabel?: string
  onRightAction?: (() => void) | null
  // keep these
  badgeNumber?: number
  borderless?: boolean
  titleComponent?: React.ReactNode
  title?: string
  leftAction?: 'back' | 'cancel' // defaults to 'back',
  onLeftAction?: (() => void) | null
  leftActionText?: string // defaults to 'cancel' when leftAction is 'cancel',
  hideBackLabel?: boolean
  customComponent?: React.ReactNode | null
  customSafeAreaBottomStyle?: StylesCrossPlatform // mobile only,
  customSafeAreaTopStyle?: StylesCrossPlatform // mobile only; use with `underNotch` route tag,
  headerStyle?: StylesCrossPlatform
  theme?: 'light' | 'dark' // defaults to 'light',
  rightActions?: Array<Action | null>
  // for nav2. if you use the actual header, its already safe so you can opt out of another safe
  underNotch?: boolean
}
export type LeftActionProps = {
  badgeNumber?: number
  disabled?: boolean
  customCancelText?: string
  hasTextTitle?: boolean
  hideBackLabel?: boolean
  leftAction?: 'back' | 'cancel' | null
  leftActionText?: string
  theme?: 'light' | 'dark' // defaults to 'light',
  onLeftAction: (() => void) | null
  customIconColor?: string
  style?: StylesCrossPlatform
}

type HeaderHocProps = Props

/**
 * Short term use this instead of the hoc as a regular component
 */
export declare class HeaderHocWrapper extends React.Component<
  Props & {children: React.ReactNode; skipHeader?: boolean}
> {}
export declare class HeaderHocHeader extends React.Component<HeaderHocProps> {}
export declare class LeftAction extends React.Component<LeftActionProps> {}
// HeaderHoc is deprecated. navigationOptions should be used instead.

// used in navigationOptions
export declare class HeaderLeftArrow extends React.Component<any> {}
export declare class HeaderLeftBlank extends React.Component<any> {}
export declare class HeaderLeftCancel extends React.Component<any> {}


text:
BSLS_IDENT("$Id$ $CSID$")

// ============================================================================
// IMPLEMENTATION NOTES
//
// Note that we declare all the possible 'customSwap*' functions in the
// namespace 'struct', but only at most half of them (and possibly none of
// them) will actually be defined.  All the ones that will be defined will be
// defined inline in the .h file.  Never will a 'p' version (a function that
// takes 'x' as a ptr) and a 'non-p' (a function that takes 'x' by value') be
// defined for the same word width at the same time.  It was felt that to add
// the myriad and byzantine #ifdef's needed to only declare the functions that
// will later be defined in the .h file would unacceptably obscure the
// readability of the declarations.
// ============================================================================

namespace BloombergLP {

#if defined(BSLS_PLATFORM_CPU_SPARC) && !defined(BSLS_PLATFORM_CMP_GNU)
void bsls_byteOrderUtil_Impl_common()
    // This function is never called, it is just a common area in which the
    // following assembler is to reside.
{
// Commented out since the generic implementation is probably faster than the
// function call for 16 and 32 bits.
//..
//  asm(".global bsls_byteOrderUtil_Impl_sparc_CC_swap_p16\n"
//      ".type   bsls_byteOrderUtil_Impl_sparc_CC_swap_p16,#function\n"
//      "bsls_byteOrderUtil_Impl_sparc_CC_swap_p16:\n"
//      "retl\n"
//      "lduha [%o0] 0x88, %o0\n");
//
//  asm(".global bsls_byteOrderUtil_Impl_sparc_CC_swap_p32\n"
//      ".type   bsls_byteOrderUtil_Impl_sparc_CC_swap_p32,#function\n"
//      "bsls_byteOrderUtil_Impl_sparc_CC_swap_p32:\n"
//      "retl\n"
//      "lduwa [%o0] 0x88, %o0\n");
//..

#ifdef BSLS_PLATFORM_CPU_32_BIT
    asm(".global bsls_byteOrderUtil_Impl_sparc_CC_swap_p64\n"
        ".type   bsls_byteOrderUtil_Impl_sparc_CC_swap_p64,#function\n"
        "bsls_byteOrderUtil_Impl_sparc_CC_swap_p64:\n"
        "ldxa [%o0] 0x88, %o2\n" // load into %o2
        "srl %o2, 0, %o1\n"      // %o1 = %o2 & UINT_MAX
        "retl\n"
        "srlx %o2, 32, %o0\n");  // %o0 = %o2 >> 32;

#else  // BSLS_PLATFORM_CPU_32_BIT else

    asm(".global bsls_byteOrderUtil_Impl_sparc_CC_swap_p64\n"
        ".type   bsls_byteOrderUtil_Impl_sparc_CC_swap_p64,#function\n"
        "bsls_byteOrderUtil_Impl_sparc_CC_swap_p64:\n"
        "retl\n"
        "ldxa [%o0] 0x88, %o0\n");

#endif  // BSLS_PLATFORM_CPU_32_BIT else
}

#endif  // BSLS_PLATFORM_CPU_SPARC

}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import static org.chromium.android_webview.test.AwActivityTestRule.WAIT_TIMEOUT_MS;

import android.os.Build;
import android.support.test.InstrumentationRegistry;
import android.webkit.JavascriptInterface;

import androidx.test.filters.SmallTest;

import com.google.common.util.concurrent.SettableFuture;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.android_webview.AwContents;
import org.chromium.android_webview.AwContentsClient.AwWebResourceRequest;
import org.chromium.android_webview.AwSettings;
import org.chromium.android_webview.test.TestAwContentsClient.OnReceivedSslErrorHelper;
import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.net.test.EmbeddedTestServer;
import org.chromium.net.test.ServerCertificate;
import org.chromium.url.GURL;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * A test suite for WebView's network-related configuration. This tests WebView's default settings,
 * which are configured by either AwURLRequestContextGetter or NetworkContext.
 */
@RunWith(AwJUnit4ClassRunner.class)
@Batch(Batch.PER_CLASS)
public class AwNetworkConfigurationTest {
    @Rule
    public AwActivityTestRule mActivityTestRule = new AwActivityTestRule();

    private AwTestContainerView mTestContainerView;
    private TestAwContentsClient mContentsClient;
    private AwContents mAwContents;

    private EmbeddedTestServer mTestServer;

    @Before
    public void setUp() {
        mContentsClient = new TestAwContentsClient();
        mTestContainerView = mActivityTestRule.createAwTestContainerViewOnMainSync(mContentsClient);
        mAwContents = mTestContainerView.getAwContents();
    }

    @After
    public void tearDown() throws Exception {
        // Clean up any X-Requested-With allow-lists that test may have set.
        AwSettings awSettings = mActivityTestRule.getAwSettingsOnUiThread(mAwContents);
        awSettings.setRequestedWithHeaderOriginAllowList(Collections.emptySet());
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @DisabledTest(message = "crbug.com/1148388")
    // clang-format off+
    public void testSHA1LocalAnchorsAllowed() throws Throwable {
        // clang-format on
        mTestServer = EmbeddedTestServer.createAndStartHTTPSServer(
                InstrumentationRegistry.getInstrumentation().getContext(),
                ServerCertificate.CERT_SHA1_LEAF);
        try {
            OnReceivedSslErrorHelper onReceivedSslErrorHelper =
                    mContentsClient.getOnReceivedSslErrorHelper();
            int count = onReceivedSslErrorHelper.getCallCount();
            String url = mTestServer.getURL("/android_webview/test/data/hello_world.html");
            mActivityTestRule.loadUrlSync(
                    mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                Assert.assertEquals("We should generate an SSL error on >= Q", count + 1,
                        onReceivedSslErrorHelper.getCallCount());
            } else {
                if (count != onReceivedSslErrorHelper.getCallCount()) {
                    Assert.fail("We should not have received any SSL errors on < Q but we received"
                            + " error " + onReceivedSslErrorHelper.getError());
                }
            }
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    private static String getPackageName() {
        return InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageName();
    }

    private String getXRequestedWithFromResultBody() throws Exception {
        AwActivityTestRule.enableJavaScriptOnUiThread(mAwContents);
        return mActivityTestRule.getJavaScriptResultBodyTextContent(mAwContents, mContentsClient);
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"disable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderMainFrameLegacy() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            mActivityTestRule.loadUrlSync(
                    mAwContents, mContentsClient.getOnPageFinishedHelper(), echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be the app package name",
                    getPackageName(), getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    private void allowRequestOrigin(String echoHeaderUrl) throws Exception {
        AwSettings awSettings = mActivityTestRule.getAwSettingsOnUiThread(mAwContents);
        GURL gurl = new GURL(echoHeaderUrl);
        String origin = gurl.getScheme() + "://" + gurl.getHost() + ":" + gurl.getPort();
        awSettings.setRequestedWithHeaderOriginAllowList(Set.of(origin));
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderMainFrame() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            mActivityTestRule.loadUrlSync(
                    mAwContents, mContentsClient.getOnPageFinishedHelper(), echoHeaderUrl);

            Assert.assertEquals("No X-Requested-With header should be set", "None",
                    getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderMainFrameOriginAllowed() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            allowRequestOrigin(echoHeaderUrl);
            mActivityTestRule.loadUrlSync(
                    mAwContents, mContentsClient.getOnPageFinishedHelper(), echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be the app package name",
                    getPackageName(), getXRequestedWithFromResultBody());

        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderMainFrameUnrelatedOriginAllowed() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            AwSettings awSettings = mActivityTestRule.getAwSettingsOnUiThread(mAwContents);
            awSettings.setRequestedWithHeaderOriginAllowList(Set.of("https://google.com"));
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            mActivityTestRule.loadUrlSync(
                    mAwContents, mContentsClient.getOnPageFinishedHelper(), echoHeaderUrl);

            Assert.assertEquals("No X-Requested-With header should be set", "None",
                    getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderMainFrameInvalidOriginPattern() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            AwSettings awSettings = mActivityTestRule.getAwSettingsOnUiThread(mAwContents);
            try {
                // An origin pattern must have a scheme, so this is expected to fail
                awSettings.setRequestedWithHeaderOriginAllowList(Set.of("google.com"));
                Assert.fail("An IllegalArgumentException was expected");
            } catch (IllegalArgumentException expected) {
                // Expected
            }
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    private String getXRequestedWithFromIframe() throws Exception {
        AwActivityTestRule.enableJavaScriptOnUiThread(mAwContents);
        final String xRequestedWith =
                getJavaScriptResultIframeTextContent(mAwContents, mContentsClient);
        return xRequestedWith;
    }

    private void loadPageInIframe(String echoHeaderUrl) throws Throwable {
        // Use the test server's root path as the baseUrl to satisfy same-origin restrictions.
        final String baseUrl = mTestServer.getURL("/");
        final String pageWithIframeHtml =
                "
Main frame
";
        // We use loadDataWithBaseUrlSync because we need to dynamically control the HTML
        // content, which EmbeddedTestServer doesn't support. We don't need to encode content
        // because loadDataWithBaseUrl() encodes content itself.
        mActivityTestRule.loadDataWithBaseUrlSync(mAwContents,
                mContentsClient.getOnPageFinishedHelper(), pageWithIframeHtml,
                /* mimeType */ null, /* isBase64Encoded */ false, baseUrl, /* historyUrl */
                null);
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"disable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderSubResourceLegacy() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            loadPageInIframe(echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be the app package name",
                    getPackageName(), getXRequestedWithFromIframe());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderSubResource() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            loadPageInIframe(echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should not be set", "None",
                    getXRequestedWithFromIframe());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderSubResourceOriginAllowed() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            allowRequestOrigin(echoHeaderUrl);
            loadPageInIframe(echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be the app package name",
                    getPackageName(), getXRequestedWithFromIframe());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    private void requestRedirectToUrl(String echoHeaderUrl) throws Exception {
        final String encodedEchoHeaderUrl = URLEncoder.encode(echoHeaderUrl, "UTF-8");
        // Returns a server-redirect (301) to echoHeaderUrl.
        final String redirectToEchoHeaderUrl =
                mTestServer.getURL("/server-redirect?" + encodedEchoHeaderUrl);
        mActivityTestRule.loadUrlSync(
                mAwContents, mContentsClient.getOnPageFinishedHelper(), redirectToEchoHeaderUrl);
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"disable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderHttpRedirectLegacy() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            requestRedirectToUrl(echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be the app package name",
                    getPackageName(), getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderHttpRedirect() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            requestRedirectToUrl(echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be None", "None",
                    getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithHeaderHttpRedirectAllowOrigin() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            allowRequestOrigin(echoHeaderUrl);

            requestRedirectToUrl(echoHeaderUrl);

            Assert.assertEquals("X-Requested-With header should be the app package name",
                    getPackageName(), getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    private void testRequestedWithApplicationValuePreferredBase() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String echoHeaderUrl = mTestServer.getURL("/echoheader?X-Requested-With");
            final String applicationRequestedWithValue = "foo";
            final Map<String, String> extraHeaders = new HashMap<>();
            extraHeaders.put("X-Requested-With", applicationRequestedWithValue);
            mActivityTestRule.loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(),
                    echoHeaderUrl, extraHeaders);

            Assert.assertEquals("Should prefer app's provided X-Requested-With header",
                    applicationRequestedWithValue, getXRequestedWithFromResultBody());
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"disable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithApplicationValuePreferredLegacy() throws Throwable {
        // Application preference should override the header and allow it to be set whether the
        // feature is enabled or not.
        testRequestedWithApplicationValuePreferredBase();
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    @CommandLineFlags.Add({"enable-features=WebViewXRequestedWithHeaderControl"})
    public void testRequestedWithApplicationValuePreferred() throws Throwable {
        // Application preference should override the header and allow it to be set whether the
        // feature is enabled or not.
        testRequestedWithApplicationValuePreferredBase();
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    public void testRequestedWithHeaderShouldInterceptRequest() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            final String url = mTestServer.getURL("/android_webview/test/data/hello_world.html");
            mActivityTestRule.loadUrlSync(
                    mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
            AwWebResourceRequest request =
                    mContentsClient.getShouldInterceptRequestHelper().getRequestsForUrl(url);
            Assert.assertFalse("X-Requested-With should be invisible to shouldInterceptRequest",
                    request.requestHeaders.containsKey("X-Requested-With"));
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    @Test
    @SmallTest
    @Feature({"AndroidWebView", "Network"})
    public void testAccessControlAllowOriginHeader() throws Throwable {
        mTestServer = EmbeddedTestServer.createAndStartServer(
                InstrumentationRegistry.getInstrumentation().getContext());
        try {
            AwActivityTestRule.enableJavaScriptOnUiThread(mAwContents);

            final SettableFuture<Boolean> fetchResultFuture = SettableFuture.create();
            Object injectedObject = new Object() {
                @JavascriptInterface
                public void success() {
                    fetchResultFuture.set(true);
                }
                @JavascriptInterface
                public void error() {
                    fetchResultFuture.set(false);
                }
            };
            AwActivityTestRule.addJavascriptInterfaceOnUiThread(
                    mAwContents, injectedObject, "injectedObject");

            // The test server will add the Access-Control-Allow-Origin header to the HTTP response
            // for this resource. We should check WebView correctly respects this.
            final String fetchWithAllowOrigin =
                    mTestServer.getURL("/set-header?Access-Control-Allow-Origin:%20*");
            String html = ""
                    + "  "
                    + "  "
                    + "  "
                    + "    HTML content does not matter."
                    + "  "
                    + "";
            final String baseUrl = "http://some.origin.test/index.html";
            mActivityTestRule.loadDataWithBaseUrlSync(mAwContents,
                    mContentsClient.getOnPageFinishedHelper(), html,
                    /* mimeType */ null, /* isBase64Encoded */ false, baseUrl,
                    /* historyUrl */ null);

            String script = "fetch('" + fetchWithAllowOrigin + "')"
                    + "  .then(() => { injectedObject.success(); })"
                    + "  .catch(() => { injectedObject.failure(); });";
            mActivityTestRule.executeJavaScriptAndWaitForResult(
                    mAwContents, mContentsClient, script);
            Assert.assertTrue("fetch() should succeed, due to Access-Control-Allow-Origin header",
                    fetchResultFuture.get(WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS));
            // If we timeout, this indicates the fetch() was erroneously blocked by CORS (as was the
            // root cause of https://crbug.com/960165).
        } finally {
            mTestServer.stopAndDestroyServer();
        }
    }

    /**
     * Like {@link AwActivityTestRule#getJavaScriptResultBodyTextContent}, but it gets the text
     * content of the iframe instead. This assumes the main frame has only a single iframe.
     */
    private String getJavaScriptResultIframeTextContent(
            final AwContents awContents, final TestAwContentsClient viewClient) throws Exception {
        final String script =
                "document.getElementsByTagName('iframe')[0].contentDocument.body.textContent";
        String raw =
                mActivityTestRule.executeJavaScriptAndWaitForResult(awContents, viewClient, script);
        return mActivityTestRule.maybeStripDoubleQuotes(raw);
    }
}


text: Rails.application.config.session_store :cookie_store, key: '_VoterApp_session'


text:
/* Copyright 2014-2017 Dr.O.Hagendorf, HS Wismar  */
/* MAX11300 Modifications by Axel Utech 2014, HS Wismar */
/* Copyright 2015 M. Marquardt, HS Wismar */

/*
 * Must specify the S_FUNCTION_NAME as the name of the S-function.
 */
#define S_FUNCTION_NAME                max11300_Config
#define S_FUNCTION_LEVEL               2

/*
 * Need to include simstruc.h for the definition of the SimStruct and
 * its associated macro definitions.
 */
#include "simstruc.h"

#define EDIT_OK(S, P_IDX) \
 (!((ssGetSimMode(S)==SS_SIMMODE_SIZES_CALL_ONLY) && mxIsEmpty(ssGetSFcnParam(S, P_IDX))))
#define MDL_CHECK_PARAMETERS
#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)

/* Function: mdlCheckParameters ===========================================
 * Abstract:
 *    mdlCheckParameters verifies new parameter settings whenever parameter
 *    change or are re-evaluated during a simulation. When a simulation is
 *    running, changes to S-function parameters can occur at any time during
 *    the simulation loop.
 */
static void mdlCheckParameters(SimStruct *S)
{
  /*
   * Check the parameter 1 (SpiPort)
   */
  if EDIT_OK(S, 0) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 0, "P1", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 2 (CsPort
   */
  if EDIT_OK(S, 1) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 1, "P2", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 3 (CsPin)
   */
  if EDIT_OK(S, 2) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 2, "P3", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 4 (AdcRate)
   */
  if EDIT_OK(S, 3) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 3, "P4", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 5 (DacRef)
   */
  if EDIT_OK(S, 4) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 4, "P5", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 6 (TempCh0)
   */
  if EDIT_OK(S, 5) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 5, "P6", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 7 (TempCh1)
   */
  if EDIT_OK(S, 6) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 6, "P7", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
  /*
   * Check the parameter 8 (TempCh2)
   */
  if EDIT_OK(S, 7) {
    int_T dimsArray[2] = { 1, 1 };

    /* Check the parameter attributes */
    ssCheckSFcnParamValueAttribs(S, 7, "P8", DYNAMICALLY_TYPED, 2, dimsArray, 0);
  }
}

#endif

/* Function: mdlInitializeSizes ===========================================
 * Abstract:
 *    The sizes information is used by Simulink to determine the S-function
 *    block's characteristics (number of inputs, outputs, states, etc.).
 */
static void mdlInitializeSizes(SimStruct *S)
{
  /* Number of expected parameters */
  ssSetNumSFcnParams(S, 8);

#if defined(MATLAB_MEX_FILE)

  if (ssGetNumSFcnParams(S) == ssGetSFcnParamsCount(S)) {
    /*
     * If the number of expected input parameters is not equal
     * to the number of parameters entered in the dialog box return.
     * Simulink will generate an error indicating that there is a
     * parameter mismatch.
     */
    mdlCheckParameters(S);
    if (ssGetErrorStatus(S) != NULL) {
      return;
    }
  } else {
    /* Return if number of expected != number of actual parameters */
    return;
  }

#endif

  /* Set the parameter's tunable status */
  ssSetSFcnParamTunable(S, 0, 0);    // SpiPort
  ssSetSFcnParamTunable(S, 1, 0);   // CsPort
  ssSetSFcnParamTunable(S, 2, 0);   // CsPin
  ssSetSFcnParamTunable(S, 3, 0);   // AdcRate
  ssSetSFcnParamTunable(S, 4, 0);   // DacRef
  ssSetSFcnParamTunable(S, 5, 0);   // TempCh0
  ssSetSFcnParamTunable(S, 6, 0);   // TempCh1
  ssSetSFcnParamTunable(S, 7, 0);   // TempCh2

  ssSetNumPWork(S, 0);

  if (!ssSetNumDWork(S, 0))
    return;

  /*
   * Set the number of input ports.
   */
  if (!ssSetNumInputPorts(S, 0))
    return;

  /*
   * Set the number of output ports.
   */
  if (!ssSetNumOutputPorts(S, 0))
    return;

  /*
   * This S-function can be used in referenced model simulating in normal mode.
   */
  ssSetModelReferenceNormalModeSupport(S, MDL_START_AND_MDL_PROCESS_PARAMS_OK);

  /*
   * Set the number of sample time.
   */
  ssSetNumSampleTimes(S, 1);

  /*
   * All options have the form SS_OPTION_<name> and are documented in
   * matlabroot/simulink/include/simstruc.h. The options should be
   * combined with bitwise OR as in
   *   ssSetOptions(S, (SS_OPTION_name1 | SS_OPTION_name2))
   */
  ssSetOptions(S,
               SS_OPTION_USE_TLC_WITH_ACCELERATOR |
               SS_OPTION_CAN_BE_CALLED_CONDITIONALLY |
               SS_OPTION_EXCEPTION_FREE_CODE |
               SS_OPTION_WORKS_WITH_CODE_REUSE |
               SS_OPTION_SFUNCTION_INLINED_FOR_RTW |
               SS_OPTION_DISALLOW_CONSTANT_SAMPLE_TIME);
}

/* Function: mdlInitializeSampleTimes =====================================
 * Abstract:
 *    This function is used to specify the sample time(s) for your
 *    S-function. You must register the same number of sample times as
 *    specified in ssSetNumSampleTimes.
 */
static void mdlInitializeSampleTimes(SimStruct *S)
{
  ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
  ssSetOffsetTime(S, 0, FIXED_IN_MINOR_STEP_OFFSET);

#if defined(ssSetModelReferenceSampleTimeDefaultInheritance)

  ssSetModelReferenceSampleTimeDefaultInheritance(S);

#endif

}

#define MDL_SET_WORK_WIDTHS
#if defined(MDL_SET_WORK_WIDTHS) && defined(MATLAB_MEX_FILE)

/* Function: mdlSetWorkWidths =============================================
 * Abstract:
 *      The optional method, mdlSetWorkWidths is called after input port
 *      width, output port width, and sample times of the S-function have
 *      been determined to set any state and work vector sizes which are
 *      a function of the input, output, and/or sample times.
 *
 *      Run-time parameters are registered in this method using methods
 *      ssSetNumRunTimeParams, ssSetRunTimeParamInfo, and related methods.
 */
static void mdlSetWorkWidths(SimStruct *S)
{
  /* Set number of run-time parameters */
  if (!ssSetNumRunTimeParams(S, 8))
    return;

  ssRegDlgParamAsRunTimeParam(S, 0, 0, "SpiPort", ssGetDataTypeId(S, "uint8"));
  ssRegDlgParamAsRunTimeParam(S, 1, 1, "CsPort", ssGetDataTypeId(S, "uint8"));
  ssRegDlgParamAsRunTimeParam(S, 2, 2, "CsPin", ssGetDataTypeId(S, "uint8"));
  ssRegDlgParamAsRunTimeParam(S, 3, 3, "AdcRate", ssGetDataTypeId(S, "uint8"));
  ssRegDlgParamAsRunTimeParam(S, 4, 4, "DacRef", SS_UINT8);
  ssRegDlgParamAsRunTimeParam(S, 5, 5, "TempCh0", SS_UINT8);
  ssRegDlgParamAsRunTimeParam(S, 6, 6, "TempCh1", SS_UINT8);
  ssRegDlgParamAsRunTimeParam(S, 7, 7, "TempCh2", SS_UINT8);
}

#endif

#define MDL_START
#if defined(MDL_START)

/* Function: mdlStart =====================================================
 * Abstract:
 *    This function is called once at start of model execution. If you
 *    have states that should be initialized once, this is the place
 *    to do it.
 */
static void mdlStart(SimStruct *S)
{
    UNUSED_PARAMETER(S);
}

#endif

/* Function: mdlOutputs ===================================================
 * Abstract:
 *    In this function, you compute the outputs of your S-function
 *    block. Generally outputs are placed in the output vector(s),
 *    ssGetOutputPortSignal.
 */
static void mdlOutputs(SimStruct *S, int_T tid)
{
    UNUSED_PARAMETER(S);
    UNUSED_PARAMETER(tid);
}

/* Function: mdlTerminate =================================================
 * Abstract:
 *    In this function, you should perform any actions that are necessary
 *    at the termination of a simulation.
 */
static void mdlTerminate(SimStruct *S)
{
    UNUSED_PARAMETER(S);
}

/*
 * Required S-function trailer
 */
#ifdef MATLAB_MEX_FILE
# include "simulink.c"
#else
# include "cg_sfun.h"
#endif


text:
@echo off

REM ************Compact Framework. RELEASE to Bin\Release\CF\Excel.dll************
REM **********************************************************************
SET CSC=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe /nologo

SET SC_PATH=%cd%

REM **CLEAN

RD /S /Q %SC_PATH%\Bin\Release\CF\
MKDIR %SC_PATH%\Bin\Release\CF\

set NETCF_PATH=C:\Program Files\Microsoft.NET\SDK\CompactFramework\v2.0\WindowsCE

if DEFINED REF ( set REF= )

set REF=%REF% "/r:%NETCF_PATH%\MsCorlib.dll"
set REF=%REF% "/r:%NETCF_PATH%\System.dll"
set REF=%REF% "/r:%NETCF_PATH%\System.Data.dll"
set REF=%REF% "/r:%NETCF_PATH%\System.Xml.dll"
set REF=%REF% /r:"%SC_PATH%\..\Lib\cf\ICSharpCode.SharpZipLib.dll"

@echo on
%CSC% /define:CF_RELEASE /nologo -nostdlib -noconfig /o /out:"%SC_PATH%\Bin\Release\CF\Excel.dll" /target:library %REF% /recurse:*.cs


text:
<?php
namespace Collections;

interface DictionaryInterface extends \IteratorAggregate, \Countable
{
    /**
     * Returns the type of the dictionary's keys.
     *
     * @return string
     */
    public function getKeyType();

    /**
     * Returns the type of the dictionary's values.
     *
     * @return string
     */
    public function getValueType();

    /**
     * Returns true if $key is in the dictionary, returns false if it is not.
     *
     * @param $key
     * @return bool
     */
    public function exists($key);

    /**
     * Returns true if the callable returns true. The callable should accept a
     * key and value as arguments and return a boolean.
     *
     * @param callable $callable
     * @param bool
     */
    public function contains(callable $callable);

    /**
     * Returns the value associated with $key.
     *
     * @param $key
     * @return mixed
     */
    public function get($key);

    /**
     * Removes the key-value pair represented by $key from the dictionary.
     *
     * @param $key
     * @return static
     */
    public function delete($key);

    /**
     * Returns true if $value is in the dictionary, returns false if not.
     *
     * @param $value
     * @return bool
     */
    public function valueExists($value);

    /**
     * Returns the number of key-value pairs in the dictionary.
     *
     * @return int
     */
    public function count();

    /**
     * Removes every key-value pair from the dictionary.
     *
     * @return static
     */
    public function clear();

    /**
     * Returns the key-value pairs in the dictionary as an associative array.
     *
     * @return array
     */
    public function toArray();

    /**
     * Returns a dictionary that only contains the key-value pairs which satisfy
     * $condition.
     *
     * @param callable $condition
     * @return static
     */
    public function filter(callable $condition);

    /**
     * Removes all key-value pairs from the Dictionary that do not satisfy
     * $condition.
     *
     * @param callable $condition
     * @return static
     */
    public function without(callable $condition);

    /**
     * Adds the key-value pair containing $key and $value to the dictionary.
     *
     * @param $key
     * @param $value
     * @return static
     * @throws Exceptions\InvalidArgumentException
     */
    public function add($key, $value);

    /**
     * Applies the callback function $callable to each key-value pair in the
     * dictionary.
     *
     * @param callable $callable
     */
    public function each(callable $callable);

    /**
     * Returns the value associated with $key in the dictionary, returns
     * $default if it does not.
     *
     * @param $key
     * @param $default
     * @return mixed
     */
    public function getOrElse($key, $default);

    /**
     * Returns an array of all keys in the dictionary.
     *
     * @return array
     */
    public function keys();

    /**
     * Returns an array of all values in the dictionary.
     *
     * @return array
     */
    public function values();

    /**
     * Returns a new dictionary with the callback function $callable applied to
     * every key-value pair in the dictionary.
     *
     * @param callable $callable
     * @return static
     */
    public function map(callable $callable);

    /**
     * Adds every key-value pair in $newItems to the dictionary.
     *
     * @param $newItems
     * @return static
     */
    public function merge($newItems);

    /**
     * Reduce the dictionary to a single value. The callable should contain args: carry, key, value
     *
     * @param callable $callable
     * @param mixed $initial
     * @return mixed
     */
    public function reduce(callable $callable, $initial);
}


text:
[![CI Status](http://img.shields.io/travis/c3mb0/AppAnalytics.svg?style=flat)](https://travis-ci.org/c3mb0/AppAnalytics)
[![Version](https://img.shields.io/cocoapods/v/AppAnalytics.svg?style=flat)](http://cocoapods.org/pods/AppAnalytics)
[![License](https://img.shields.io/cocoapods/l/AppAnalytics.svg?style=flat)](http://cocoapods.org/pods/AppAnalytics)
[![Platform](https://img.shields.io/cocoapods/p/AppAnalytics.svg?style=flat)](http://cocoapods.org/pods/AppAnalytics)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

AppAnalytics is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "AppAnalytics"
```

## Author

c3mb0, c3mb0@users.noreply.github.com

## License

AppAnalytics is available under the MIT license. See the LICENSE file for more info.


text:
import marconi.openstack.common.log as logging
from marconi.queues import storage
#from marconi.queues.storage import errors

LOG = logging.getLogger(__name__)

class MessageController(storage.Message):

    def list(self, queue, project=None, marker=None,
             limit=10, echo=False, client_uuid=None,
             include_claimed=False):
        """Base method for listing messages.

        :param queue: Name of the queue to get the
            message from.
        :param project: Project id
        :param marker: Tail identifier
        :param limit: (Default 10) Max number of messages to return.
        :type limit: Maybe int
        :param echo: (Default False) Boolean expressing whether
            or not this client should receive its own messages.
        :param client_uuid: A UUID object. Required when echo=False.
        :param include_claimed: omit claimed messages from listing?
        :type include_claimed: bool

        :returns: An iterator giving a sequence of messages and
            the marker of the next page.
        """
        raise NotImplementedError

    def first(self, queue, project=None, sort=1):
        """Get first message in the queue (including claimed).

        :param queue: Name of the queue to list
        :param sort: (Default 1) Sort order for the listing. Pass 1 for
            ascending (oldest message first), or -1 for descending (newest
            message first).

        :returns: First message in the queue, or None if the queue is
            empty
        """
        raise NotImplementedError

    def get(self, queue, message_id, project=None):
        """Base method for getting a message.

        :param queue: Name of the queue to get the
            message from.
        :param project: Project id
        :param message_id: Message ID

        :returns: Dictionary containing message data
        :raises: DoesNotExist
        """
        raise NotImplementedError

    def bulk_get(self, queue, message_ids, project=None):
        """Base method for getting multiple messages.

        :param queue: Name of the queue to get the
            message from.
        :param project: Project id
        :param message_ids: A sequence of message IDs.

        :returns: An iterable, yielding dicts containing
            message details
        """
        raise NotImplementedError

    def post(self, queue, messages, client_uuid, project=None):
        """Base method for posting one or more messages.

        Implementations of this method should guarantee
        and preserve the order, in the returned list, of
        incoming messages.

        :param queue: Name of the queue to post message to.
        :param messages: Messages to post to queue, an iterable
            yielding 1 or more elements. An empty iterable
            results in undefined behavior.
        :param client_uuid: A UUID object.
        :param project: Project id

        :returns: List of message ids
        """
        raise NotImplementedError

    def delete(self, queue, message_id, project=None, claim=None):
        """Base method for deleting a single message.

        :param queue: Name of the queue to post
            message to.
        :param message_id: Message to be deleted
        :param project: Project id
        :param claim: Claim this message
            belongs to. When specified, claim must
            be valid and message_id must belong to
            it.
        """
        raise NotImplementedError

    def bulk_delete(self, queue, message_ids, project=None):
        """Base method for deleting multiple messages.

        :param queue: Name of the queue to post
            message to.
        :param message_ids: A sequence of message IDs
            to be deleted.
        :param project: Project id
        """
        raise NotImplementedError


text:
'use strict';

// Create a new 'render' controller method
exports.render = function(req, res) {
	// Use the 'response' object to render the 'index' view with a 'title' and a stringified 'user' properties
	res.render('index', {
		title: 'Welcome to the Cloud'
	});
};


text:
namespace TraktApiSharp.Objects.Get.Users.Statistics
{
    using System.Collections.Generic;

    /// A collection of Trakt user statistics for ratings.
    public class TraktUserRatingsStatistics : ITraktUserRatingsStatistics
    {
        /// Gets or sets the total number of items an user has rated.
        public int? Total { get; set; }

        ///
        /// Gets or sets the rating distribution of an user's ratings.
        /// <para>Nullable</para>
        ///
        public IDictionary<string, int> Distribution { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- These are the attributes for the SupportRecyclerView. -->
    <declare-styleable name="SupportRecyclerView">
        <!-- The choice behavior for the list. -->
        <attr name="choiceMode">
            <!-- The list does not indicate choices. -->
            <enum name="none" value="0" />
            <!-- The list allows up to one choice. -->
            <enum name="singleChoice" value="1" />
            <!-- The list allows multiple choices. -->
            <enum name="multipleChoice" value="2" />
            <!-- The list allows multiple choices in a custom selection mode. -->
            <enum name="multipleChoiceModal" value="3" />
        </attr>
    </declare-styleable>

</resources>


text:
java-quick-Log4j2Slf4j
======================

Sample config and code to make a slf4j with log4j2 includes runtime jars

Dependancies with log4j

	<dependencies>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.1</version>
		</dependency>
	</dependencies>

Code declare sample:

	private static final Logger logger = LoggerFactory.getLogger(App.class);

log4j2.xml in classpath

	<?xml version="1.0" encoding="UTF-8"?>
	<configuration status="WARN">
	<appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>

		<RollingFile append="false" name="Rolling-1" fileName="/apps/eset/logs/a.log"
			filePattern="yyyy_MMM_%i.log">
			<PatternLayout>
				<pattern>%d %p %C [%t] %m%n</pattern> <!-- %d %p %C{1.} [%t] %m%n -->
			</PatternLayout>

			<!--   <OnStartupTriggeringPolicy />
			<SizeBasedTriggeringPolicy size="20 MB" />
			<TimeBasedTriggeringPolicy /> -->
			<SizeBasedTriggeringPolicy size="5mb" />
			<OnStartupTriggeringPolicy />
		</RollingFile>

	</appenders>
	<loggers>
		<root level="debug">
			<appender-ref ref="Console" />
			<appender-ref ref="Rolling-1" />
		</root>
	</loggers>
	</configuration>

	---


text:
<TITLE>Review for eXistenZ (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

eXistenZ (1999)

reviewed by
James Sanford

eXistenZ (Dimension Films)
Directed by David Cronenberg

 With violent video games currently under scrutiny in light of the
tragedy in Colorado, writer-director David Cronenberg's "eXistenZ" has
probably taken on a timeliness its author could never have anticipated.
But teetering on the cutting edge is hardly an unfamiliar position for
Cronenberg, whose 1982 shocker "Videodrome" prophetically warned about
the desensitization of viewers fed a steady diet of violent or
pornographic films, and whose 1986 remake of "The Fly" is often read as
an allegory about the AIDS crisis.
 "eXistenZ," which is almost lightweight in comparison to other
Cronenberg creations, spins a genuinely jolting yarn about world-famous
game designer Allegra Geller (Jennifer Jason Leigh), whose latest
breakthrough is a kill-or-be-killed program that's downloaded directly
into the body through a port in the base of the player's spine. Even the
controllers look like flattened-out, misshapen breasts. The problem with
the new technology is that it's too realistic, too convincing. Allegra
and her partner (Jude Law) finally get so swept up in what's going on
they can't tell if they're in the real world or the virtual world.
Through some clever twists, Cronenberg eventually succeeds in making the
audience feel as disoriented as Allegra, uncertain of what to believe at
any given time.
 Leigh, who couldn't underplay a part if she tried, envisions Allegra as
a kind of electronic junkie who shivers and writhes in ecstacy as she
plugs into the electronic drug she's created; to further underscore the
connection, the wires that link her to the source look uncannily like
umbilical cords. The rallying cry of Cronenberg's characters in
"Videodrome" was "Long live the new flesh!", but almost two decades
later the taut and tricky "eXistenZ" argues that sometimes progress can
take us to places we might have been better off avoiding altogether.
James Sanford

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/signal"
	"path/filepath"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	. "github.com/google/syzkaller/pkg/log"
	"github.com/google/syzkaller/prog"
	"github.com/google/syzkaller/syz-manager/mgrconfig"
	"github.com/google/syzkaller/vm"
)

var (
	flagConfig = flag.String("config", "", "configuration file")
)

func main() {
	flag.Parse()
	cfg, err := mgrconfig.LoadFile(*flagConfig)
	if err != nil {
		Fatalf("%v", err)
	}
	if len(flag.Args()) != 1 {
		Fatalf("usage: syz-crush -config=config.file execution.log")
	}
	if _, err := prog.GetTarget(cfg.TargetOS, cfg.TargetArch); err != nil {
		Fatalf("%v", err)
	}
	env := mgrconfig.CreateVMEnv(cfg, false)
	vmPool, err := vm.Create(cfg.Type, env)
	if err != nil {
		Fatalf("%v", err)
	}

	Logf(0, "booting test machines...")
	var shutdown uint32
	var wg sync.WaitGroup
	wg.Add(vmPool.Count() + 1)
	for i := 0; i < vmPool.Count(); i++ {
		i := i
		go func() {
			defer wg.Done()
			for {
				runInstance(cfg, vmPool, i)
				if atomic.LoadUint32(&shutdown) != 0 {
					break
				}
			}
		}()
	}

	go func() {
		c := make(chan os.Signal, 2)
		signal.Notify(c, syscall.SIGINT)
		<-c
		wg.Done()
		atomic.StoreUint32(&shutdown, 1)
		close(vm.Shutdown)
		Logf(-1, "shutting down...")
		atomic.StoreUint32(&shutdown, 1)
		<-c
		Fatalf("terminating")
	}()
	wg.Wait()
}

func runInstance(cfg *mgrconfig.Config, vmPool *vm.Pool, index int) {
	inst, err := vmPool.Create(index)
	if err != nil {
		Logf(0, "failed to create instance: %v", err)
		return
	}
	defer inst.Close()

	execprogBin, err := inst.Copy(filepath.Join(cfg.Syzkaller, "bin", "syz-execprog"))
	if err != nil {
		Logf(0, "failed to copy execprog: %v", err)
		return
	}
	executorBin, err := inst.Copy(filepath.Join(cfg.Syzkaller, "bin", "syz-executor"))
	if err != nil {
		Logf(0, "failed to copy executor: %v", err)
		return
	}
	logFile, err := inst.Copy(flag.Args()[0])
	if err != nil {
		Logf(0, "failed to copy log: %v", err)
		return
	}

	cmd := fmt.Sprintf("%v -executor=%v -repeat=0 -procs=%v -cover=0 -sandbox=%v %v",
		execprogBin, executorBin, cfg.Procs, cfg.Sandbox, logFile)
	outc, errc, err := inst.Run(time.Hour, nil, cmd)
	if err != nil {
		Logf(0, "failed to run execprog: %v", err)
		return
	}

	Logf(0, "vm-%v: crushing...", index)
	desc, _, output, crashed, timedout := vm.MonitorExecution(outc, errc, true, cfg.ParsedIgnores)
	if timedout {
		// This is the only "OK" outcome.
		Logf(0, "vm-%v: running long enough, restarting", index)
	} else {
		if !crashed {
			// syz-execprog exited, but it should not.
			desc = "lost connection to test machine"
		}
		f, err := ioutil.TempFile(".", "syz-crush")
		if err != nil {
			Logf(0, "failed to create temp file: %v", err)
			return
		}
		defer f.Close()
		Logf(0, "vm-%v: crashed: %v, saving to %v", index, desc, f.Name())
		f.Write(output)
	}
	return
}


text:
//
//  DataSetDetailsViewController.m
//  mainapp
//
//  Created by Eric Roland on 12/22/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "DataSetDetailsViewController.h"
#import "NSString+HTML.h"
#import "DataItemDetailViewController.h"
#import "ModelHelper.h"
#import "FilterResultsViewController.h"
#import "DataSetViewController.h"
#import "DataSetDetailsMapViewController.h"
#import "DataSetDetailsInfoViewController.h"
#import "AppDelegate.h"
#import "AdWebViewController.h"
#import "HudView.h"
#define appDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate]

@implementation DataSetDetailsViewController
@synthesize locationManager, isMovingToDataset;
@synthesize items = _items;
@synthesize tableView = _tableView;
@synthesize iconItems = _iconItems;
@synthesize markerType = _markerType;
@synthesize dataSetId = _dataSetId;
@synthesize adUrl = _adUrl;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

-(IBAction)saveDataset:(id)sender {
    [ModelHelper getAndSaveUserDatasetByExternalIdItem:self.dataSetId:nil];

    NSString *dialogMessage = @"Your search was saved";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Search saved" message:dialogMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];

    /*
	UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Filter Results", @"Show Results on Map",
                                 @"Full Dataset Details", @"Email a Link", nil];
	popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
	[popupQuery showFromTabBar:self.tabBarController.tabBar];
    */
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    [self becomeFirstResponder];
    [self dismissModalViewControllerAnimated:YES];
}

- (void)getItems {
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    self.items = [settings objectForKey:[NSString stringWithFormat:@"%@DataSetItems", self.dataSetId]];
    if (self.items == nil) {
        [self.items removeAllObjects];
        [self.tableView reloadData];
        [_hudView startActivityIndicator:self.view];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-M-dd"];
        double lastLatitude = [settings doubleForKey:@"lastLatitude"];
        double lastLongitude = [settings doubleForKey:@"lastLongitude"];
        NSMutableString *url = [[[appDelegate defaults] objectForKey:@"DataSetDetailUrl"] mutableCopy];
        NSMutableString *yourMapperAPIKey = [[[appDelegate defaults] objectForKey:@"YourMapperAPIKey"] mutableCopy];

        [url replaceOccurrencesOfString:@"KEY" withString:[[NSString alloc] initWithFormat:@"%@", yourMapperAPIKey]
                                options:NSLiteralSearch range:(NSRange){0,[url length]}];

        [url replaceOccurrencesOfString:@"LATITUDE" withString:[[NSString alloc] initWithFormat:@"%f", lastLatitude]
                                options:NSLiteralSearch range:(NSRange){0,[url length]}];

        [url replaceOccurrencesOfString:@"LONGITUDE" withString:[[NSString alloc] initWithFormat:@"%f", lastLongitude]
                                options:NSLiteralSearch range:(NSRange){0,[url length]}];

        [url replaceOccurrencesOfString:@"ID" withString:[[NSString alloc] initWithFormat:@"%@", self.dataSetId]
                                options:NSLiteralSearch range:(NSRange){0,[url length]}];

        NSString *savedCategories = [settings stringForKey:[NSString stringWithFormat:@"%@SavedCategories", self.dataSetId]];
        if (savedCategories != nil && savedCategories.length > 0) {
            [url appendString:[NSString stringWithFormat:@"&c=%@", savedCategories]];
        }

        NSDate *startDate = [settings objectForKey:[NSString stringWithFormat:@"%@SavedStartDate", self.dataSetId]];
        if (startDate != nil) {
            NSString *formattedDate = [NSString stringWithFormat:@"%@", [dateFormat stringFromDate:startDate]];
            [url appendString:[NSString stringWithFormat:@"&start=%@", formattedDate]];
        }

        NSDate *endDate = [settings objectForKey:[NSString stringWithFormat:@"%@SavedEndDate", self.dataSetId]];
        if (endDate != nil) {
            NSString *formattedDate = [NSString stringWithFormat:@"%@", [dateFormat stringFromDate:endDate]];
            [url appendString:[NSString stringWithFormat:@"&end=%@", formattedDate]];
        }

        NSString *searchText = [settings stringForKey:[NSString stringWithFormat:@"%@SavedSearchText", self.dataSetId]];
        if (searchText != nil && searchText.length > 0) {
            [url appendString:[NSString stringWithFormat:@"&search=%@", searchText]];
        }

        NSURL *finalUrl = [NSURL URLWithString:[NSString stringWithString:url]];
        dispatch_async(kBgQueue, ^{
            NSData* data = [NSData dataWithContentsOfURL:finalUrl];
            if (data == nil) {
                [_hudView stopActivityIndicator];
                [AppDelegate showConnectionError];
            } else {
                [self performSelectorOnMainThread:@selector(fetchedData:)
                                       withObject:data waitUntilDone:YES];
            }
        });
    } else {
        [self.tableView reloadData];
    }
}

- (void)filterButtonPressed:(id)sender {
    FilterResultsViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"FilterResultsStoryboard"];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    [self presentModalViewController:navigationController animated:YES];
}

- (void)mapButtonPressed:(id)sender {
    DataSetDetailsMapViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DataSetDetailsMapStoryboard"];
    controller.items = self.items;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    [self presentModalViewController:navigationController animated:YES];
}

- (void)infoButtonPressed:(id)sender {
    DataSetDetailsInfoViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DataSetDetailsInfoStoryboard"];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    [self presentModalViewController:navigationController animated:YES];
}

- (void)emailButtonPressed:(id)sender {
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    Dataset *dataSet = [ModelHelper getAndSaveDatasetByExternalId:self.dataSetId];
    NSMutableString *url = [[[appDelegate defaults] objectForKey:@"DataSetLinkUrl"] mutableCopy];

    NSString *categories = [settings stringForKey:[NSString stringWithFormat:@"%@Categories", self.dataSetId]];
    NSString *searchText = [settings stringForKey:[NSString stringWithFormat:@"%@SearchText", self.dataSetId]];
    NSString *startDate = [settings stringForKey:[NSString stringWithFormat:@"%@SavedStartDate", self.dataSetId]];
    NSString *endDate = [settings stringForKey:[NSString stringWithFormat:@"%@SavedEndDate", self.dataSetId]];
    double latitude = [settings doubleForKey:@"lastLatitude"];
    double longitude = [settings doubleForKey:@"lastLongitude"];
    NSString *dataSetName = [dataSet.name lowercaseString];
    dataSetName = [[dataSetName componentsSeparatedByString: @" "] componentsJoinedByString: @"-"];

    [url replaceOccurrencesOfString:@"DATASETID" withString:[NSString stringWithFormat:@"%@", dataSet.datasetId] options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"DATASETNAME" withString:dataSetName options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"DATASETPERMALINK" withString:dataSet.linkPath options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"CATEGORIES" withString:(categories == nil) ? @"" : categories options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"SEARCHTEXT" withString:(searchText == nil) ? @"" : searchText options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"STARTDATE" withString:(startDate == nil) ? @"" : startDate options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"ENDDATE" withString:(endDate == nil) ? @"" : endDate options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"LATITUDE" withString:[NSString stringWithFormat:@"%f",latitude] options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"LONGITUDE" withString:[NSString stringWithFormat:@"%f",longitude] options:NSLiteralSearch range:(NSRange){0,[url length]}];

    MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
    controller.mailComposeDelegate = self;
    [controller setSubject:[NSString stringWithFormat:@"Your Mapper: %@", dataSet.name]];
    [controller setMessageBody:url isHTML:NO];
    [self presentModalViewController:controller animated:YES];
}
- (void)locationButtonPressed:(id)sender {
    [_hudView startActivityIndicator:self.view];
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    [settings setDouble:newLocation.coordinate.latitude forKey:@"lastLatitude"];
    [settings setDouble:newLocation.coordinate.longitude forKey:@"lastLongitude"];
    [settings synchronize];
    //[ModelHelper getAndSaveUserLocationByLatLng:newLocation.coordinate.latitude :newLocation.coordinate.longitude:@"geocodedLocation"];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([settings doubleForKey:@"lastLatitude"], [settings doubleForKey:@"lastLongitude"]);
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error != nil){
            [_hudView stopActivityIndicator];
            return;
        }
        [_hudView stopActivityIndicator];
        [locationManager stopUpdatingLocation];
        if (!self.isMovingToDataset && placemarks.count > 0) {
            CLPlacemark *placeMark = [placemarks objectAtIndex:0];
            [ModelHelper getAndSaveUserLocationByPlaceMarker:placeMark.addressDictionary:@"geocodedLocation":coordinate.latitude:coordinate.longitude];
            NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
            [settings setObject:nil forKey:[NSString stringWithFormat:@"%@DataSetItems", self.dataSetId]];
            [settings synchronize];
            self.isMovingToDataset = YES;
            [self loadData];
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError*)error{
    [_hudView stopActivityIndicator];
    [AppDelegate showConnectionError];
    [locationManager stopUpdatingLocation];
}

#pragma mark - View lifecycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.051 green:0.345 blue:0.6 alpha:1];

    [self loadData];

    UIBarButtonItem* saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveDataset:)];
    self.navigationItem.rightBarButtonItem = saveButton;

    if (!self.tableView &&
        [self.view isKindOfClass:[UITableView class]]) {
        self.tableView = (UITableView *)self.view;
    }

    self.view = [[UIView alloc] initWithFrame:
                  [UIScreen mainScreen].applicationFrame];
    self.tableView.frame = self.view.bounds;
    self.tableView.contentInset = UIEdgeInsetsMake(44.0, 0.0, 0.0, 0.0);
    [self.view addSubview:self.tableView];

    UIToolbar *toolbar = [[UIToolbar alloc] init];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [toolbar sizeToFit];
    CGFloat toolbarHeight = [toolbar frame].size.height;
    CGRect viewBounds = self.navigationController.navigationBar.frame;
    CGFloat rootViewWidth = CGRectGetWidth(viewBounds);
    CGRect rectArea = CGRectMake(0, 0, rootViewWidth, toolbarHeight);
    [toolbar setFrame:rectArea];

    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    BOOL hasFilter = [settings boolForKey:[NSString stringWithFormat:@"%@HasFilter", self.dataSetId]];

    UIImage *filterImage = [UIImage imageNamed:(hasFilter) ? @"Toolbar-Filter-On" : @"Toolbar-Filter.png"];
    UIButton *filterButton = [UIButton buttonWithType:UIButtonTypeCustom];
    filterButton.bounds = CGRectMake( 0, 0, filterImage.size.width, filterImage.size.height );
    [filterButton setImage:filterImage forState:UIControlStateNormal];
    [filterButton addTarget:self action:@selector(filterButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *filterButtonItem = [[UIBarButtonItem alloc] initWithCustomView:filterButton];

    UIBarButtonItem *mapButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Toolbar-Map.png"] style:UIBarButtonItemStylePlain target:self action:@selector(mapButtonPressed:)];
    UIBarButtonItem *infoButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Toolbar-Info.png"] style:UIBarButtonItemStylePlain target:self action:@selector(infoButtonPressed:)];
    UIBarButtonItem *emailButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(emailButtonPressed:)];
    UIBarButtonItem *locationButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Toolbar-Location.png"] style:UIBarButtonItemStylePlain target:self action:@selector(locationButtonPressed:)];

    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, mapButton, flexibleSpace, filterButtonItem, flexibleSpace, locationButton, flexibleSpace, infoButton, flexibleSpace, emailButton, flexibleSpace, nil]];

    [self.view addSubview:toolbar];
}

- (void)loadData {
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    self.dataSetId = [settings stringForKey:@"dataSetId"];
    Dataset *dataSet = [ModelHelper getAndSaveDatasetByExternalId:self.dataSetId];

    double latitude = [settings doubleForKey:@"lastLatitude"];
    double longitude = [settings doubleForKey:@"lastLongitude"];

    self.markerType = [dataSet.markerType intValue];
    self.title = [settings stringForKey:@"dataSetName"];

    NSMutableString *url = [[[appDelegate defaults] objectForKey:@"AdUrl"] mutableCopy];
    [url replaceOccurrencesOfString:@"DATASETID" withString:[NSString stringWithFormat:@"%@", dataSet.datasetId] options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"LATITUDE" withString:[NSString stringWithFormat:@"%f",latitude] options:NSLiteralSearch range:(NSRange){0,[url length]}];
    [url replaceOccurrencesOfString:@"LONGITUDE" withString:[NSString stringWithFormat:@"%f",longitude] options:NSLiteralSearch range:(NSRange){0,[url length]}];
    NSURL *finalUrl = [NSURL URLWithString:[NSString stringWithString:url]];
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:finalUrl];
        if (data != nil) {
            [self performSelectorOnMainThread:@selector(fetchedAd:)
                                   withObject:data waitUntilDone:YES];
        }
    });

    [self getItems];
}

- (void)showAd:(id)sender {
    NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
    [settings setObject:self.adUrl forKey:@"AdUrl"];
    [settings synchronize];
    AdWebViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"AdWebStoryboard"];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)fetchedAd:(NSData *)responseData {
    NSError* error;
    id json = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          options:kNilOptions
                          error:&error];
    BOOL isValid = [NSJSONSerialization isValidJSONObject:json];
    if (isValid) {
        self.tableView.contentInset = UIEdgeInsetsMake(44.0, 0.0, 50.0, 0.0);
        NSMutableString *adUrl = [[json objectForKey:@"ImagePath"] mutableCopy];
        if ([AppDelegate isRetina]) {
            [adUrl replaceOccurrencesOfString:@".png" withString:@"@2x.png" options:NSLiteralSearch range:(NSRange){0,[adUrl length]}];
        }
        self.adUrl = [json objectForKey:@"LinkPath"];
        NSURL *url = [NSURL URLWithString:adUrl];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 318, 320, 50)];
        [button addTarget:self action:@selector(showAd:) forControlEvents:UIControlEventTouchUpInside];
        [button setBackgroundImage:image forState:UIControlStateNormal];
        [self.view addSubview:button];
    }
}

- (void)fetchedData:(NSData *)responseData {
    [_hudView stopActivityIndicator];
    NSError* error;
    id json = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          options:kNilOptions
                          error:&error];
    BOOL isValid = [NSJSONSerialization isValidJSONObject:json];
    if (isValid) {
        self.items = [[NSMutableArray alloc] initWithArray:[json objectForKey:@"items"]];
        [self.items removeObjectAtIndex:0];
        NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
        [settings setObject:self.items forKey:[NSString stringWithFormat:@"%@DataSetItems", self.dataSetId]];
        [settings synchronize];
        for (NSDictionary *item in self.items) {
            [ModelHelper getAndSaveMarkerById:[item objectForKey:@"id"]:item:self.dataSetId];
        }
        [self.tableView reloadData];
    } else {
        [AppDelegate showConnectionError];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _hudView = [[HudView alloc] init];
    _hudView.hasSecondHeaderBar = YES;
    [_hudView loadActivityIndicator];
    //[_hudView_hasSecondHeaderBar = YES;
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = (NSDictionary*)[self.items objectAtIndex:indexPath.row];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setMaximumFractionDigits:2];
    [formatter setRoundingMode: NSNumberFormatterRoundDown];
    Marker *marker = [ModelHelper getMarkerById:[item objectForKey:@"id"]];
    float distance = [marker.distance floatValue];
    NSString *roundedDistance = [formatter stringFromNumber:[NSNumber numberWithFloat:distance]];

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        UIImageView *categoryImage = nil;
        if (self.markerType == 1) {
            categoryImage = [[UIImageView alloc] initWithFrame:CGRectMake(13,7,13,20)];
        } else {
            categoryImage = [[UIImageView alloc] initWithFrame:CGRectMake(13,7,13,13)];
        }
        categoryImage.tag = 5;
        [cell.contentView addSubview:categoryImage];

        UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 25, 50, 35)];
        distanceLabel.tag = 1;
        distanceLabel.lineBreakMode = UILineBreakModeWordWrap;
        distanceLabel.numberOfLines = 0;
        distanceLabel.textColor = [UIColor grayColor];
        distanceLabel.font = [UIFont fontWithName:@"ArialMT" size:10];

        [cell.contentView addSubview:distanceLabel];

        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 1, 230, 20)];
        titleLabel.tag = 2;
        titleLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:12];
        [cell.contentView addSubview:titleLabel];

        UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 18, 230, 20)];
        addressLabel.tag = 3;
        addressLabel.font = [UIFont fontWithName:@"ArialMT" size:12];
        [cell.contentView addSubview:addressLabel];

        UILabel *categoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 36, 230, 20)];
        categoryLabel.font = [UIFont fontWithName:@"Arial-ItalicMT" size:12];
        categoryLabel.textColor = [UIColor grayColor];
        categoryLabel.tag = 4;
        [cell.contentView addSubview:categoryLabel];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    UIImageView *categoryImage = (UIImageView*)[cell viewWithTag:5];
    NSString *imageName =  [marker.categoryImage stringByAppendingString:@".png"];
    categoryImage.image = [UIImage imageNamed:imageName];

    UILabel *distanceLabel = (UILabel*)[cell viewWithTag:1];
    distanceLabel.text = [NSString stringWithFormat:@"%@\nmiles", roundedDistance];

    UILabel *titleLabel = (UILabel*)[cell viewWithTag:2];
    titleLabel.text = [NSString stringWithFormat:@"%@", [marker.name stringByConvertingHTMLToPlainText]];

    UILabel *addressLabel = (UILabel*)[cell viewWithTag:3];
    addressLabel.text = [NSString stringWithFormat:@"%@, %@, %@", marker.address, marker.city, marker.state];

    UILabel *categoryLabel = (UILabel*)[cell viewWithTag:4];
    categoryLabel.text = [NSString stringWithFormat:@"%@", marker.category];

    cell.selectionStyle = UITableViewCellSelectionStyleBlue;

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_hudView startActivityIndicator:self.view];
    NSDictionary *item = (NSDictionary*)[self.items objectAtIndex:indexPath.row];
    NSString *externalId = [item objectForKey:@"id"];
    Marker *marker = [ModelHelper getMarkerById:externalId];
    DataItemDetailViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DataItemDetailStoryboard"];
    controller.marker = marker;
    [self.navigationController pushViewController:controller animated:YES];
    [_hudView stopActivityIndicator];
}

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

@end


text:
"""b3j0f.sync.accessor package."""

from .core import Accessor
from .registry import AccessorRegistry