text:
import six
import mock

from pyfakefs import fake_filesystem_unittest
from py_utils import cloud_storage

import dependency_manager
from dependency_manager import exceptions

class DependencyManagerTest(fake_filesystem_unittest.TestCase):

  def setUp(self):
    self.lp_info012 = dependency_manager.LocalPathInfo(
        ['path0', 'path1', 'path2'])
    self.cloud_storage_info = dependency_manager.CloudStorageInfo(
        'cs_bucket', 'cs_hash', 'download_path', 'cs_remote_path')

    self.dep_info = dependency_manager.DependencyInfo(
        'dep', 'platform', 'config_file', local_path_info=self.lp_info012,
        cloud_storage_info=self.cloud_storage_info)
    self.setUpPyfakefs()

  def tearDown(self):
    self.tearDownPyfakefs()

  # TODO(crbug.com/1111556): add a test that construct
  # dependency_manager.DependencyManager from a list of DependencyInfo.
  def testErrorInit(self):
    with self.assertRaises(ValueError):
      dependency_manager.DependencyManager(None)
    with self.assertRaises(ValueError):
      dependency_manager.DependencyManager('config_file?')

  def testInitialUpdateDependencies(self):
    dep_manager = dependency_manager.DependencyManager([])

    # Empty BaseConfig.
    dep_manager._lookup_dict = {}
    base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
    base_config_mock.IterDependencyInfo.return_value = iter([])
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertFalse(dep_manager._lookup_dict)

    # One dependency/platform in a BaseConfig.
    dep_manager._lookup_dict = {}
    base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
    dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep = 'dependency'
    plat = 'platform'
    dep_info.dependency = dep
    dep_info.platform = plat
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
    expected_lookup_dict = {dep: {plat: dep_info}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info.Update.called)

    # One dependency multiple platforms in a BaseConfig.
    dep_manager._lookup_dict = {}
    base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
    dep = 'dependency'
    plat1 = 'platform1'
    plat2 = 'platform2'
    dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info1.dependency = dep
    dep_info1.platform = plat1
    dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info2.dependency = dep
    dep_info2.platform = plat2
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info1,
                                                             dep_info2])
    expected_lookup_dict = {dep: {plat1: dep_info1,
                                  plat2: dep_info2}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info1.Update.called)
    self.assertFalse(dep_info2.Update.called)

    # Multiple dependencies, multiple platforms in a BaseConfig.
    dep_manager._lookup_dict = {}
    base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)
    dep1 = 'dependency1'
    dep2 = 'dependency2'
    plat1 = 'platform1'
    plat2 = 'platform2'
    dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info1.dependency = dep1
    dep_info1.platform = plat1
    dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info2.dependency = dep1
    dep_info2.platform = plat2
    dep_info3 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info3.dependency = dep2
    dep_info3.platform = plat2
    base_config_mock.IterDependencyInfo.return_value = iter(
        [dep_info1, dep_info2, dep_info3])
    expected_lookup_dict = {dep1: {plat1: dep_info1,
                                   plat2: dep_info2},
                            dep2: {plat2: dep_info3}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info1.Update.called)
    self.assertFalse(dep_info2.Update.called)
    self.assertFalse(dep_info3.Update.called)

  def testFollowupUpdateDependenciesNoOverlap(self):
    dep_manager = dependency_manager.DependencyManager([])
    dep = 'dependency'
    dep1 = 'dependency1'
    dep2 = 'dependency2'
    dep3 = 'dependency3'
    plat1 = 'platform1'
    plat2 = 'platform2'
    plat3 = 'platform3'
    dep_info_a = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info_a.dependency = dep1
    dep_info_a.platform = plat1
    dep_info_b = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info_b.dependency = dep1
    dep_info_b.platform = plat2
    dep_info_c = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info_c.dependency = dep
    dep_info_c.platform = plat1

    start_lookup_dict = {dep: {plat1: dep_info_a,
                               plat2: dep_info_b},
                         dep1: {plat1: dep_info_c}}
    base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)

    # Empty BaseConfig.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    base_config_mock.IterDependencyInfo.return_value = iter([])
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(start_lookup_dict, dep_manager._lookup_dict)

    # One dependency/platform in a BaseConfig.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info.dependency = dep3
    dep_info.platform = plat1
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
    expected_lookup_dict = {dep: {plat1: dep_info_a,
                                  plat2: dep_info_b},
                            dep1: {plat1: dep_info_c},
                            dep3: {plat3: dep_info}}

    dep_manager._UpdateDependencies(base_config_mock)
    six.assertCountEqual(self, expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info.Update.called)
    self.assertFalse(dep_info_a.Update.called)
    self.assertFalse(dep_info_b.Update.called)
    self.assertFalse(dep_info_c.Update.called)

    # One dependency multiple platforms in a BaseConfig.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info1.dependency = dep2
    dep_info1.platform = plat1
    dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info2.dependency = dep2
    dep_info2.platform = plat2
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info1,
                                                             dep_info2])
    expected_lookup_dict = {dep: {plat1: dep_info_a,
                                  plat2: dep_info_b},
                            dep1: {plat1: dep_info_c},
                            dep2: {plat1: dep_info1,
                                   plat2: dep_info2}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info1.Update.called)
    self.assertFalse(dep_info2.Update.called)
    self.assertFalse(dep_info_a.Update.called)
    self.assertFalse(dep_info_b.Update.called)
    self.assertFalse(dep_info_c.Update.called)

    # Multiple dependencies, multiple platforms in a BaseConfig.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep1 = 'dependency1'
    plat1 = 'platform1'
    plat2 = 'platform2'
    dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info1.dependency = dep2
    dep_info1.platform = plat1
    dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info2.dependency = dep2
    dep_info2.platform = plat2
    dep_info3 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info3.dependency = dep3
    dep_info3.platform = plat2
    base_config_mock.IterDependencyInfo.return_value = iter(
        [dep_info1, dep_info2, dep_info3])
    expected_lookup_dict = {dep: {plat1: dep_info_a,
                                  plat2: dep_info_b},
                            dep1: {plat1: dep_info_c},
                            dep2: {plat1: dep_info1,
                                   plat2: dep_info2},
                            dep3: {plat2: dep_info3}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info1.Update.called)
    self.assertFalse(dep_info2.Update.called)
    self.assertFalse(dep_info3.Update.called)
    self.assertFalse(dep_info_a.Update.called)
    self.assertFalse(dep_info_b.Update.called)
    self.assertFalse(dep_info_c.Update.called)

    # Ensure the testing data wasn't corrupted.
    self.assertEqual(start_lookup_dict,
                     {dep: {plat1: dep_info_a,
                            plat2: dep_info_b},
                      dep1: {plat1: dep_info_c}})

  def testFollowupUpdateDependenciesWithCollisions(self):
    dep_manager = dependency_manager.DependencyManager([])
    dep = 'dependency'
    dep1 = 'dependency1'
    dep2 = 'dependency2'
    plat1 = 'platform1'
    plat2 = 'platform2'
    dep_info_a = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info_a.dependency = dep1
    dep_info_a.platform = plat1
    dep_info_b = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info_b.dependency = dep1
    dep_info_b.platform = plat2
    dep_info_c = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info_c.dependency = dep
    dep_info_c.platform = plat1

    start_lookup_dict = {dep: {plat1: dep_info_a,
                               plat2: dep_info_b},
                         dep1: {plat1: dep_info_c}}
    base_config_mock = mock.MagicMock(spec=dependency_manager.BaseConfig)

    # One dependency/platform.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info.dependency = dep
    dep_info.platform = plat1
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
    expected_lookup_dict = {dep: {plat1: dep_info_a,
                                  plat2: dep_info_b},
                            dep1: {plat1: dep_info_c}}

    dep_manager._UpdateDependencies(base_config_mock)
    six.assertCountEqual(self, expected_lookup_dict, dep_manager._lookup_dict)
    dep_info_a.Update.assert_called_once_with(dep_info)
    self.assertFalse(dep_info.Update.called)
    self.assertFalse(dep_info_b.Update.called)
    self.assertFalse(dep_info_c.Update.called)
    dep_info_a.reset_mock()
    dep_info_b.reset_mock()
    dep_info_c.reset_mock()

    # One dependency multiple platforms in a BaseConfig.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info1.dependency = dep1
    dep_info1.platform = plat1
    dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info2.dependency = dep2
    dep_info2.platform = plat2
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info1,
                                                             dep_info2])
    expected_lookup_dict = {dep: {plat1: dep_info_a,
                                  plat2: dep_info_b},
                            dep1: {plat1: dep_info_c},
                            dep2: {plat2: dep_info2}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info1.Update.called)
    self.assertFalse(dep_info2.Update.called)
    self.assertFalse(dep_info_a.Update.called)
    self.assertFalse(dep_info_b.Update.called)
    dep_info_c.Update.assert_called_once_with(dep_info1)
    dep_info_a.reset_mock()
    dep_info_b.reset_mock()
    dep_info_c.reset_mock()

    # Multiple dependencies, multiple platforms in a BaseConfig.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep1 = 'dependency1'
    plat1 = 'platform1'
    plat2 = 'platform2'
    dep_info1 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info1.dependency = dep
    dep_info1.platform = plat1
    dep_info2 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info2.dependency = dep1
    dep_info2.platform = plat1
    dep_info3 = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info3.dependency = dep2
    dep_info3.platform = plat2
    base_config_mock.IterDependencyInfo.return_value = iter(
        [dep_info1, dep_info2, dep_info3])
    expected_lookup_dict = {dep: {plat1: dep_info_a,
                                  plat2: dep_info_b},
                            dep1: {plat1: dep_info_c},
                            dep2: {plat2: dep_info3}}
    dep_manager._UpdateDependencies(base_config_mock)
    self.assertEqual(expected_lookup_dict, dep_manager._lookup_dict)
    self.assertFalse(dep_info1.Update.called)
    self.assertFalse(dep_info2.Update.called)
    self.assertFalse(dep_info3.Update.called)
    self.assertFalse(dep_info_b.Update.called)
    dep_info_a.Update.assert_called_once_with(dep_info1)
    dep_info_c.Update.assert_called_once_with(dep_info2)

    # Collision error.
    dep_manager._lookup_dict = start_lookup_dict.copy()
    dep_info = mock.MagicMock(spec=dependency_manager.DependencyInfo)
    dep_info.dependency = dep
    dep_info.platform = plat1
    base_config_mock.IterDependencyInfo.return_value = iter([dep_info])
    dep_info_a.Update.side_effect = ValueError
    self.assertRaises(ValueError,
                      dep_manager._UpdateDependencies, base_config_mock)

    # Ensure the testing data wasn't corrupted.
    self.assertEqual(start_lookup_dict,
                     {dep: {plat1: dep_info_a,
                            plat2: dep_info_b},
                      dep1: {plat1: dep_info_c}})

  def testGetDependencyInfo(self):
    dep_manager = dependency_manager.DependencyManager([])
    self.assertFalse(dep_manager._lookup_dict)

    # No dependencies in the dependency manager.
    self.assertEqual(None, dep_manager._GetDependencyInfo('missing_dep',
                                                          'missing_plat'))

    dep_manager._lookup_dict = {'dep1': {'plat1': 'dep_info11',
                                         'plat2': 'dep_info12',
                                         'plat3': 'dep_info13'},
                                'dep2': {'plat1': 'dep_info11',
                                         'plat2': 'dep_info21',
                                         'plat3': 'dep_info23',
                                         'default': 'dep_info2d'},
                                'dep3': {'plat1': 'dep_info31',
                                         'plat2': 'dep_info32',
                                         'default': 'dep_info3d'}}
    # Dependency not in the dependency manager.
    self.assertEqual(None, dep_manager._GetDependencyInfo(
        'missing_dep', 'missing_plat'))
    # Dependency in the dependency manager, but not the platform. No default.
    self.assertEqual(None, dep_manager._GetDependencyInfo(
        'dep1', 'missing_plat'))
    # Dependency in the dependency manager, but not the platform, but a default
    # exists.
    self.assertEqual('dep_info2d', dep_manager._GetDependencyInfo(
        'dep2', 'missing_plat'))
    # Dependency and platform in the dependency manager. A default exists.
    self.assertEqual('dep_info23', dep_manager._GetDependencyInfo(
        'dep2', 'plat3'))
    # Dependency and platform in the dependency manager. No default exists.
    self.assertEqual('dep_info12', dep_manager._GetDependencyInfo(
        'dep1', 'plat2'))

  @mock.patch(
      'dependency_manager.dependency_info.DependencyInfo.GetRemotePath')  # pylint: disable=line-too-long
  def testFetchPathUnititializedDependency(
      self, cs_path_mock):
    dep_manager = dependency_manager.DependencyManager([])
    self.assertFalse(cs_path_mock.call_args)
    cs_path = 'cs_path'
    cs_path_mock.return_value = cs_path

    # Empty lookup_dict
    with self.assertRaises(exceptions.NoPathFoundError):
      dep_manager.FetchPath('dep', 'plat_arch_x86')

    # Non-empty lookup dict that doesn't contain the dependency we're looking
    # for.
    dep_manager._lookup_dict = {'dep1': mock.MagicMock(),
                                'dep2': mock.MagicMock()}
    with self.assertRaises(exceptions.NoPathFoundError):
      dep_manager.FetchPath('dep', 'plat_arch_x86')

  @mock.patch('os.path')
  @mock.patch(
      'dependency_manager.DependencyManager._GetDependencyInfo')
  @mock.patch(
      'dependency_manager.dependency_info.DependencyInfo.GetRemotePath')  # pylint: disable=line-too-long
  def testFetchPathLocalFile(self, cs_path_mock, dep_info_mock, path_mock):
    dep_manager = dependency_manager.DependencyManager([])
    self.assertFalse(cs_path_mock.call_args)
    cs_path = 'cs_path'
    dep_info = self.dep_info
    cs_path_mock.return_value = cs_path
    # The DependencyInfo returned should be passed through to LocalPath.
    dep_info_mock.return_value = dep_info

    # Non-empty lookup dict that contains the dependency we're looking for.
    # Local path exists.
    dep_manager._lookup_dict = {'dep': {'platform' : self.dep_info},
                                'dep2': mock.MagicMock()}
    self.fs.CreateFile('path1')
    found_path = dep_manager.FetchPath('dep', 'platform')

    self.assertEqual('path1', found_path)
    self.assertFalse(cs_path_mock.call_args)

  @mock.patch(
      'dependency_manager.dependency_info.DependencyInfo.GetRemotePath')  # pylint: disable=line-too-long
  def testFetchPathRemoteFile(
      self, cs_path_mock):
    dep_manager = dependency_manager.DependencyManager([])
    self.assertFalse(cs_path_mock.call_args)
    cs_path = 'cs_path'
    def FakeCSPath():
      self.fs.CreateFile(cs_path)
      return cs_path
    cs_path_mock.side_effect = FakeCSPath

    # Non-empty lookup dict that contains the dependency we're looking for.
    # Local path doesn't exist, but cloud_storage_path is downloaded.
    dep_manager._lookup_dict = {'dep': {'platform' : self.dep_info,
                                        'plat1': mock.MagicMock()},
                                'dep2': {'plat2': mock.MagicMock()}}
    found_path = dep_manager.FetchPath('dep', 'platform')
    self.assertEqual(cs_path, found_path)

  @mock.patch(
      'dependency_manager.dependency_info.DependencyInfo.GetRemotePath')  # pylint: disable=line-too-long
  def testFetchPathError(
      self, cs_path_mock):
    dep_manager = dependency_manager.DependencyManager([])
    self.assertFalse(cs_path_mock.call_args)
    cs_path_mock.return_value = None
    dep_manager._lookup_dict = {'dep': {'platform' : self.dep_info,
                                        'plat1': mock.MagicMock()},
                                'dep2': {'plat2': mock.MagicMock()}}
    # Non-empty lookup dict that contains the dependency we're looking for.
    # Local path doesn't exist, and cloud_storage path wasn't successfully
    # found.
    self.assertRaises(exceptions.NoPathFoundError,
                      dep_manager.FetchPath, 'dep', 'platform')

    cs_path_mock.side_effect = cloud_storage.CredentialsError
    self.assertRaises(cloud_storage.CredentialsError,
                      dep_manager.FetchPath, 'dep', 'platform')

    cs_path_mock.side_effect = cloud_storage.CloudStorageError
    self.assertRaises(cloud_storage.CloudStorageError,
                      dep_manager.FetchPath, 'dep', 'platform')

    cs_path_mock.side_effect = cloud_storage.PermissionError
    self.assertRaises(cloud_storage.PermissionError,
                      dep_manager.FetchPath, 'dep', 'platform')

  def testLocalPath(self):
    dep_manager = dependency_manager.DependencyManager([])
    # Empty lookup_dict
    with self.assertRaises(exceptions.NoPathFoundError):
      dep_manager.LocalPath('dep', 'plat')

  def testLocalPathNoDependency(self):
    # Non-empty lookup dict that doesn't contain the dependency we're looking
    # for.
    dep_manager = dependency_manager.DependencyManager([])
    dep_manager._lookup_dict = {'dep1': mock.MagicMock(),
                                'dep2': mock.MagicMock()}
    with self.assertRaises(exceptions.NoPathFoundError):
      dep_manager.LocalPath('dep', 'plat')

  def testLocalPathExists(self):
    # Non-empty lookup dict that contains the dependency we're looking for.
    # Local path exists.
    dep_manager = dependency_manager.DependencyManager([])
    dep_manager._lookup_dict = {'dependency' : {'platform': self.dep_info},
                                'dep1': mock.MagicMock(),
                                'dep2': mock.MagicMock()}
    self.fs.CreateFile('path1')
    found_path = dep_manager.LocalPath('dependency', 'platform')

    self.assertEqual('path1', found_path)

  def testLocalPathMissingPaths(self):
    # Non-empty lookup dict that contains the dependency we're looking for.
    # Local path is found but doesn't exist.
    dep_manager = dependency_manager.DependencyManager([])
    dep_manager._lookup_dict = {'dependency' : {'platform': self.dep_info},
                                'dep1': mock.MagicMock(),
                                'dep2': mock.MagicMock()}
    self.assertRaises(exceptions.NoPathFoundError,
                      dep_manager.LocalPath, 'dependency', 'platform')

  def testLocalPathNoPaths(self):
    # Non-empty lookup dict that contains the dependency we're looking for.
    # Local path isn't found.
    dep_manager = dependency_manager.DependencyManager([])
    dep_info = dependency_manager.DependencyInfo(
        'dep', 'platform', 'config_file',
        cloud_storage_info=self.cloud_storage_info)
    dep_manager._lookup_dict = {'dependency' : {'platform': dep_info},
                                'dep1': mock.MagicMock(),
                                'dep2': mock.MagicMock()}
    self.assertRaises(exceptions.NoPathFoundError,
                      dep_manager.LocalPath, 'dependency', 'platform')


text:
'''
Created on Apr 30, 2017

@author: Leo Zhong
'''

import numpy as np

# Function: K Means
# -------------
# K-Means is an algorithm that takes in a dataset and a constant
# k and returns k centroids (which define clusters of data in the
# dataset which are similar to one another).
def kmeans(X, k, maxIt):

    #get col and row
    numPoints, numDim = X.shape

    dataSet = np.zeros((numPoints, numDim + 1))
    dataSet[:, :-1] = X

    # Initialize centroids randomly
    centroids = dataSet[np.random.randint(numPoints, size = k), :]

    #Randomly assign labels to initial centorid
    centroids[:, -1] = range(1, k +1)

    # Initialize book keeping vars.
    iterations = 0
    oldCentroids = None

    # Run the main k-means algorithm
    while not shouldStop(oldCentroids, centroids, iterations, maxIt):
        print ("iteration: \n", iterations)
        print ("dataSet: \n", dataSet)
        print ("centroids: \n", centroids)
        # Save old centroids for convergence test. Book keeping.
        oldCentroids = np.copy(centroids)
        iterations += 1

        # Assign labels to each datapoint based on centroids
        updateLabels(dataSet, centroids)

        # Assign centroids based on datapoint labels
        centroids = getCentroids(dataSet, k)

    # We can get the labels too by calling getLabels(dataSet, centroids)
    return dataSet

# Function: Should Stop
# -------------
# Returns True or False if k-means is done. K-means terminates either
# because it has run a maximum number of iterations OR the centroids
# stop changing.
def shouldStop(oldCentroids, centroids, iterations, maxIt):
    if iterations > maxIt:
        return True
    return np.array_equal(oldCentroids, centroids)

# Function: Get Labels
# -------------
# Update a label for each piece of data in the dataset.
def updateLabels(dataSet, centroids):
    # For each element in the dataset, chose the closest centroid.
    # Make that centroid the element's label.
    numPoints, numDim = dataSet.shape
    for i in range(0, numPoints):
        dataSet[i, -1] = getLabelFromClosestCentroid(dataSet[i, :-1], centroids)

def getLabelFromClosestCentroid(dataSetRow, centroids):
    label = centroids[0, -1];
    minDist = np.linalg.norm(dataSetRow - centroids[0, :-1])
    for i in range(1 , centroids.shape[0]):
        dist = np.linalg.norm(dataSetRow - centroids[i, :-1])
        if dist < minDist:
            minDist = dist
            label = centroids[i, -1]
    print ("minDist:", minDist)
    return label

# Function: Get Centroids
# -------------
# Returns k random centroids, each of dimension n.
def getCentroids(dataSet, k):
    # Each centroid is the geometric mean of the points that
    # have that centroid's label. Important: If a centroid is empty (no points have
    # that centroid's label) you should randomly re-initialize it.
    result = np.zeros((k, dataSet.shape[1]))
    for i in range(1, k + 1):
        oneCluster = dataSet[dataSet[:, -1] == i, :-1]
        result[i - 1, :-1] = np.mean(oneCluster, axis = 0)
        result[i - 1, -1] = i

    return result

x1 = np.array([1, 1])
x2 = np.array([2, 1])
x3 = np.array([4, 3])
x4 = np.array([5, 4])
testX = np.vstack((x1, x2, x3, x4))

result = kmeans(testX, 2, 10)
print ("final result:")
print (result)

redpajama_set_name: RedPajamaGithub


text:
/*jshint multistr:true */

var text = "ewuihfq John awidjeiuh Josh yesterday we went shopping in roadrunnerville, john jacob Josh.";

var myName = "Josh";
var hits = [ ];

for (var i = 0; i < text.length; i++) {
    console.log(text[i]);
}


text:
"""
Tests to ensure that the visual pipeline works as expected.
"""

##########################################################################
## Imports
##########################################################################

import unittest

from yellowbrick.base import Visualizer
from yellowbrick.pipeline import VisualPipeline
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator, TransformerMixin

try:
    from unittest import mock
except ImportError:
    import mock

##########################################################################
## Mock Objects
##########################################################################

class Thing(object):
    pass

class EstimatorSpec(BaseEstimator):

    def fit(self, X, y=None, **kwargs):
        return self

MockEstimator = mock.Mock(spec = EstimatorSpec)

class TransformerSpec(BaseEstimator, TransformerMixin):

    def fit(self, X, y=None, **kwargs):
        return self

    def transform(self, X, **kwargs):
        return X

MockTransformer = mock.Mock(spec = TransformerSpec)

class VisualTransformerSpec(Visualizer, TransformerMixin):

    def fit(self, X, y=None, **kwargs):
        return self

    def transform(self, X, **kwargs):
        return X

    def draw(self, **kwargs):
        pass

    def poof(self, **kwargs):
        pass

MockVisualTransformer = mock.Mock(spec = VisualTransformerSpec)

##########################################################################
## VisualPipeline Tests
##########################################################################

class VisualPipelineTests(unittest.TestCase):

    def test_validate_steps(self):
        """
        Assert that visual transformers can be added to pipelines
        """

        # Pipeline objects have a _validate_steps method that raises an
        # TypeError if the steps don't match transforms --> estimator.

        # validate a bad intermediate transformer on the Pipeline
        with self.assertRaises(TypeError):
            pipeline = Pipeline([
                ('real', MockTransformer()),
                ('bad', Thing()),
                ('model', MockEstimator()),
            ])

        # validate a bad intermediate transformer on the VisualPipeline
        with self.assertRaises(TypeError):
            pipeline = VisualPipeline([
                ('real', MockTransformer()),
                ('bad', Thing()),
                ('model', MockEstimator()),
            ])

        # validate a bad final estimator on the Pipeline
        with self.assertRaises(TypeError):
            pipeline = Pipeline([
                ('real', MockTransformer()),
                ('bad', Thing()),
            ])

        # validate a bad final estimator on the VisualPipeline
        with self.assertRaises(TypeError):
            pipeline = VisualPipeline([
                ('real', MockTransformer()),
                ('bad', Thing()),
            ])

        # validate visual transformers on a Pipeline
        try:
            pipeline = Pipeline([
                ('real', MockTransformer()),
                ('visual', MockVisualTransformer()),
                ('model', MockEstimator()),
            ])
        except TypeError:
            self.fail("could not add a visual transformer to a Pipeline!")

        # validate visual transformers on a VisualPipeline
        try:
            pipeline = VisualPipeline([
                ('real', MockTransformer()),
                ('visual', MockVisualTransformer()),
                ('model', MockEstimator()),
            ])
        except TypeError:
            self.fail("could not add a visual transformer to a VisualPipeline!")

    def test_visual_steps_property(self):
        """
        Test the visual steps property to filter visualizers
        """

        pipeline = VisualPipeline([
            ('a', MockTransformer()),
            ('b', VisualTransformerSpec()),
            ('c', MockTransformer()),
            ('d', VisualTransformerSpec()),
            ('e', MockEstimator()),
        ])

        self.assertIn('b', pipeline.visual_steps)
        self.assertIn('d', pipeline.visual_steps)

    @unittest.skip("mocks don't work for some reason")
    def test_fit_transform_poof_and_draw_calls(self):
        """
        Test calling fit, transform, draw and poof on the pipeline
        """

        pipeline = VisualPipeline([
            ('a', MockTransformer()),
            ('b', MockVisualTransformer()),
            ('c', MockTransformer()),
            ('d', MockVisualTransformer()),
            ('e', MockEstimator()),
        ])

        X = [[1, 1, 1, 1, 1],
             [2, 2, 2, 2, 2],
             [3, 3, 3, 3, 3]]

        y =  [1, 2, 3, 4, 5]

        pipeline.fit(X, y)
        for name, step in pipeline.named_steps.items():
            step.fit.assert_called_once_with(X, y)

        pipeline.transform(X)
        for name, step in pipeline.named_steps.items():
            step.transform.assert_called_once_with(X)

        pipeline.draw()
        for name, step in pipeline.named_steps.items():
            if name in {'a', 'c', 'e'}: continue
            step.draw.assert_called_once_with()

        pipeline.poof()
        for name, step in pipeline.named_steps.items():
            if name in {'a', 'c', 'e'}: continue
            step.poof.assert_called_once_with()


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:androidfont="http://schemas.android.com/apk/res-auto"
              android:id="@+id/main_menu_container"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_weight="1"
              android:gravity="top|center"
              android:orientation="vertical">

    <FrameLayout
        android:layout_width="65dp"
        android:layout_height="65dp"
        android:layout_marginBottom="11.59dp">

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="65dp"
            android:layout_height="65dp"
            android:layout_gravity="center"
            android:contentDescription="@string/image"
            android:gravity="center"
            android:scaleType="fitXY"/>

        <com.supremainc.biostar2.view.StyledTextView
            android:id="@+id/item_badge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|top"
            android:layout_marginLeft="20dp"
            android:background="@drawable/alarm_badge"
            android:gravity="center"
            android:maxLines="1"
            android:padding="2dp"
            android:text="0"
            android:textColor="@color/white"
            android:textSize="10dp"
            android:visibility="gone"
            androidfont:typeface="roboto_medium.ttf"/>

        <ImageView
            android:id="@+id/item_badge_alert"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_gravity="center|top"
            android:layout_marginLeft="20dp"
            android:background="@drawable/badge_alert"
            android:gravity="center"
            android:visibility="gone"/>
    </FrameLayout>

    <com.supremainc.biostar2.view.StyledTextView
        android:id="@+id/item_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:maxLines="2"
        android:textColor="@drawable/selector_color_white_yellow"
        android:textSize="12dp"
        androidfont:typeface="roboto_medium.ttf"/>

</LinearLayout>


text:
Enforce img alt attribute does not contain the word image, picture, or photo. Screenreaders already announce `img` elements as an image. There is no need to use words such as *image*, *photo*, and/or *picture*.

## Rule details

This rule takes one optional object argument of type object:

```json
{
    "rules": {
        "jsx-a11y/img-redundant-alt": [ 2, {
            "components": [ "Image" ],
            "words": [ "Bild", "Foto" ],
          }],
    }
}
```

For the `components` option, these strings determine which JSX elements (**always including** `<img>`) should be checked for having redundant words in the `alt` prop value . This is a good use case when you have a wrapper component that simply renders an `img` element (like in React).

For the `words` option, these strings can be used to specify custom words that should be checked for in the alt prop, including `image`, `photo`, and `picture`. Useful for specifying words in other languages.

The rule will first check if `aria-hidden` is true to determine whether to enforce the rule. If the image is hidden, then rule will always succeed.

### Succeed
```jsx
<img src="foo" alt="Foo eating a sandwich." />
<img src="bar" aria-hidden alt="Picture of me taking a photo of an image" /> // Will pass because it is hidden.
<img src="baz" alt={`Baz taking a ${photo}`} /> // This is valid since photo is a variable name.
```

### Fail
```jsx
<img src="foo" alt="Photo of foo being weird." />
<img src="bar" alt="Image of me at a bar!" />
<img src="baz" alt="Picture of baz fixing a bug." />
```


text:
package net.violet.platform.api.actions.contacts;

import java.util.List;

import net.violet.platform.api.actions.ActionParam;
import net.violet.platform.api.authentication.SessionManager;
import net.violet.platform.api.exceptions.ForbiddenException;
import net.violet.platform.api.exceptions.InvalidContactException;
import net.violet.platform.api.exceptions.InvalidParameterException;
import net.violet.platform.api.exceptions.InvalidSessionException;
import net.violet.platform.api.exceptions.NoSuchContactException;
import net.violet.platform.datamodel.Application;
import net.violet.platform.datamodel.Contact;
import net.violet.platform.datamodel.Application.ApplicationClass;
import net.violet.platform.dataobjects.ContactData;
import net.violet.platform.dataobjects.UserData;
import net.violet.platform.util.Constantes;

public class RejectRequest extends AbstractContactAction {

	@Override
	protected Object doProcessRequest(ActionParam inParam) throws ForbiddenException, InvalidSessionException, InvalidParameterException, NoSuchContactException, InvalidContactException {

		final UserData theSessionUser = SessionManager.getUserFromSessionParam(inParam);

		final ContactData theContact = getRequestedContact(inParam);

		// Check si l'utilisateur en session est bien celui qui a recu la
		// demande d'ami
		if (theSessionUser.equals(theContact.getContact())) {
			boolean result = false;
			if (theContact.getStatus().equalsIgnoreCase(Contact.STATUS.PENDING.toString())) {
				theContact.delete();
				result = true;
			}

			return result;
		}

		throw new InvalidContactException();
	}

	/**
	 * @see net.violet.platform.api.actions.Action#isCacheable()
	 */
	public boolean isCacheable() {
		return true;
	}

	/**
	 * User informations may be cached one day
	 *
	 * @see net.violet.platform.api.actions.Action#getExpirationTime()
	 */
	public long getExpirationTime() {
		return Constantes.ONE_DAY_IN_S;
	}

	/**
	 * Read Only action
	 *
	 * @see net.violet.platform.api.actions.Action#getType()
	 */
	public ActionType getType() {
		return ActionType.UPDATE;
	}

	@Override
	public List<ApplicationClass> getAuthorizedApplicationClasses() {
		return Application.CLASSES_UI;
	}
}


text:
import { readJsonFile, writeJsonFile } from './utils/files';
import * as path from 'path';
const pkg = require('../package.json');

const appDataPath =
	process.env.APPDATA || (process.platform == 'darwin' ?
	path.join(process.env.HOME, 'Library/Preferences') :
	'/var/local');

const configFileName = path.join(appDataPath, pkg.name, 'config.json');

export interface ConfigData {
	email: string;
	password: string;
	downloadPath: string;
}

export type ConfigFieldName = keyof ConfigData;

export class Config {
	static async load(): Promise<Config> {
		const defaultValue: ConfigData = {
			email: '',
			password: '',
			downloadPath: ''
		};

		return readJsonFile(configFileName, defaultValue)
			.then(data => new Config(data));
	}

	constructor(public data: ConfigData) {
	}

	save(): Promise<void> {
		return writeJsonFile(configFileName, this.data);
	}
}


text:
<!DOCTYPE html>
<html class="reftest-wait">
<title>Reference for Embedded Style: Invalid Format</title>
<style>
::cue {
    color: green;
}
::cue(v[voice=Voice1])
{
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==)
}
</style>
<script src="/common/reftest-wait.js"></script>
<video width="320" height="180" autoplay onplaying="this.onplaying = null; this.pause(); takeScreenshot();">
    <source src="/media/white.webm" type="video/webm">
    <source src="/media/white.mp4" type="video/mp4">
    <track src="support/embedded_style_without_style.vtt" default>
</video>
</html>


text:
package com.orientechnologies.orient.graph.blueprints;

import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class GraphPolymorphicTest {

  private OrientGraph graph;

  @Before
  public void before() {
    graph = new OrientGraph("memory:" + GraphPolymorphicTest.class.getSimpleName());
  }

  @After
  public void after() {
    graph.drop();
  }

  @Test
  public void checkBrowsingAVertexClassAsEdgeClass() {
    Vertex v = graph.addVertex("class:TestVertex");
    try {
      graph.getEdge(v.getId()).getClass();
      Assert.fail();
    } catch (IllegalArgumentException e) {
    }

    try {
      graph.getEdgesOfClass("TestVertex").iterator().next().getClass();
      Assert.fail();
    } catch (IllegalArgumentException e) {
    }
  }

  @Test
  public void checkBrowsingAnUnknownClassAsEdgeClass() {
    Vertex v = graph.addVertex("class:TestVertex");
    try {
      graph.getEdge(v.getId()).getClass();
      Assert.fail();
    } catch (IllegalArgumentException e) {
    }
    try {
      graph.getEdgesOfClass("Unknown").iterator().next().getClass();
      Assert.fail();
    } catch (IllegalArgumentException e) {
    }
  }

  @Test
  public void checkBrowsingAnUnknownClassAsVertexClass() {
    Vertex v = graph.addVertex("class:TestVertex");

    try {
      graph.getVerticesOfClass("Unknown").iterator().next().getClass();
      Assert.fail();
    } catch (IllegalArgumentException e) {
    }
  }
}


text:
import React from 'react';
import PropTypes from 'prop-types';

function DragMarker({innerHeight, marginTop, marginLeft, selectionStart, selectionEnd}) {
  const width = Math.abs(selectionEnd - selectionStart);
  const x = selectionStart < selectionEnd ? selectionStart : selectionEnd;
  return (
    <rect
      className="drag-marker"
      pointerEvents="none"
      fill="black"
      opacity="0.2"
      x={x}
      y={marginTop}
      width={width}
      height={innerHeight}
    />
  );
}

DragMarker.requiresSVG = true;
DragMarker.propTypes = {
  selectionStart: PropTypes.number,
  selectionEnd: PropTypes.number
};

export default DragMarker;


text:
namespace xwalk {

// This view paints the Tizen Mobile system indicator provided by the system.
// We get to it by using the Elementary "Plug" system from EFL, reading the
// image from a shared memory area.
class TizenSystemIndicator : public views::ImageView {
 public:
  TizenSystemIndicator();
  ~TizenSystemIndicator() override;

  bool IsConnected() const;

  void SetWatcher(TizenSystemIndicatorWatcher* watcher);

  // views::View implementation.
  gfx::Size GetPreferredSize() const override;

 private:
  bool OnMousePressed(const ui::MouseEvent& event) override;
  void OnMouseReleased(const ui::MouseEvent& event) override;
  void OnMouseMoved(const ui::MouseEvent& event) override;
  void OnGestureEvent(ui::GestureEvent* event) override;

  TizenSystemIndicatorWatcher* watcher_;
  friend class TizenSystemIndicatorWidget;
};

}  // namespace xwalk

#endif  // XWALK_TIZEN_MOBILE_UI_TIZEN_SYSTEM_INDICATOR_H_


text:
require 'spec_helper'
require 'tempfile'

RSpec.describe BrickFTP::Utils::ChunkIO do
  describe '#each' do
    context 'chunk_size is nil' do
      it 'chunk has whole data' do
        Tempfile.create('spec') do |io|
          io.write('DATA')
          io.rewind

          res = +''
          called = 0
          described_class.new(io).each do |chunk|
            res << chunk.read
            called += 1
          end
          expect(res).to eq 'DATA'
          expect(called).to eq 1
        end
      end
    end

    context 'chunk_size is not nil' do
      context 'data is a StringIO' do
        it 'chunk has whole data' do
          io = StringIO.new('DATA')
          io.rewind

          res = +''
          called = 0
          described_class.new(io, chunk_size: 1).each do |chunk|
            res << chunk.read
            called += 1
          end
          expect(res).to eq 'DATA'
          expect(called).to eq 1
        end
      end

      context 'data is not a StringIO' do
        it 'split by chunk_size' do
          Tempfile.create('spec') do |io|
            io.write('DATA')
            io.rewind

            res = +''
            called = 0
            described_class.new(io, chunk_size: 1).each do |chunk|
              res << chunk.read
              called += 1
            end
            expect(res).to eq 'DATA'
            expect(called).to eq 4
          end
        end
      end
    end

    context 'without block' do
      it 'return Enumerator' do
        Tempfile.create('spec') do |io|
          io.write('DATA')
          io.rewind

          enum = described_class.new(io, chunk_size: 1).each
          expect(enum).to be_an_instance_of(Enumerator)

          res = +''
          called = 0
          enum.each do |chunk|
            res << chunk.read
            called += 1
          end
          expect(res).to eq 'DATA'
          expect(called).to eq 4
        end
      end
    end
  end
end


text:
package org.xbib.io.compress.xz;

/**
 * XZ constants.
 */
public class XZ {
    /**
     * XZ Header Magic Bytes begin a XZ file.
     * This can be useful to detect XZ compressed data.
     */
    public static final byte[] HEADER_MAGIC = {
            (byte) 0xFD, '7', 'z', 'X', 'Z', '\0'};

    /**
     * XZ Footer Magic Bytes are the last bytes of a XZ Stream.
     */
    public static final byte[] FOOTER_MAGIC = {'Y', 'Z'};

    /**
     * Integrity check ID indicating that no integrity check is calculated.
     * <p>
     * Omitting the integrity check is strongly discouraged except when
     * the integrity of the data will be verified by other means anyway,
     * and calculating the check twice would be useless.
     */
    public static final int CHECK_NONE = 0;

    /**
     * Integrity check ID for CRC32.
     */
    public static final int CHECK_CRC32 = 1;

    /**
     * Integrity check ID for CRC64.
     */
    public static final int CHECK_CRC64 = 4;

    /**
     * Integrity check ID for SHA-256.
     */
    public static final int CHECK_SHA256 = 10;

    private XZ() {
    }
}


text:
package org.apache.deltaspike.test.core.api.config.propertyconfigsource;

import org.apache.deltaspike.core.api.config.PropertyFileConfig;

/**
 * Custom PropertyFileConfig which gets picked up during
 * {@link javax.enterprise.inject.spi.ProcessAnnotatedType}.
 * The values will be available after the container got booted!
 */
public class MyCustomPropertyFileConfig implements PropertyFileConfig
{
    @Override
    public String getPropertyFileName()
    {
        return "myconfig.properties";
    }

    @Override
    public boolean isOptional()
    {
        return false;
    }
}


text:
package bqschema

import (
	"testing"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

func TestBqschema(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Bqschema Suite")
}


text:
/*
 * config.js: Default settings for all levels that winston knows about
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 *
 */

var colors = require('colors');

var config = exports,
    allColors = exports.allColors = {};

config.addColors = function (colors) {
  mixin(allColors, colors);
};

config.colorize = function (level) {
  var colorized = level;
  if (allColors[level] instanceof Array) {
    for (var i = 0, l = allColors[level].length; i < l; ++i) {
      colorized = colorized[allColors[level][i]];
    }
  } else if (allColors[level].match(/\s/)) {
    var colorArr = allColors[level].split(/\s+/);
    for (var i = 0; i < colorArr.length; ++i) {
      colorized = colorized[colorArr[i]];
    }
    allColors[level] = colorArr;
  } else {
    colorized = colorized[allColors[level]];
  }
  return colorized;
};

//
// Export config sets
//
config.cli    = require('./config/cli-config');
config.npm    = require('./config/npm-config');
config.syslog = require('./config/syslog-config');

//
// Add colors for pre-defined config sets
//
config.addColors(config.npm.colors);
config.addColors(config.syslog.colors);

function mixin (target) {
  var args = Array.prototype.slice.call(arguments, 1);

  args.forEach(function (a) {
    var keys = Object.keys(a);
    for (var i = 0; i < keys.length; i++) {
      target[keys[i]] = a[keys[i]];
    }
  });
  return target;
};


text:
module Azure::IotHub::Mgmt::V2017_07_01
  module Models
    #
    # The JSON-serialized leaf certificate
    #
    class CertificateVerificationDescription

      include MsRestAzure

      # @return [String] base-64 representation of X509 certificate .cer file
      # or just .pem file content.
      attr_accessor :certificate

      #
      # Mapper for CertificateVerificationDescription class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'CertificateVerificationDescription',
          type: {
            name: 'Composite',
            class_name: 'CertificateVerificationDescription',
            model_properties: {
              certificate: {
                client_side_validation: true,
                required: false,
                serialized_name: 'certificate',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
require 'appengine-apis/datastore_types'

module AppEngine

  # The Ruby API for the App Engine Memcache service. This offers a fast
  # distributed cache for commonly-used data. The cache is limited both in
  # duration and also in total space, so objects stored in it may be discarded
  # at any time.
  #
  # Note that null is a legal value to store in the cache, or to use as a cache
  # key. Strings are stored encoded as utf-8. To store binary data use
  # AppEngine::Datastore::Blob or +str.to_java_bytes+.
  #
  # The values returned from this API are mutable copies from the cache;
  # altering them has no effect upon the cached value itself until assigned
  # with one of the put methods. Likewise, the methods returning collections
  # return mutable collections, but changes do not affect the cache.
  #
  # Except for the #incr and #decr methods, this service does not offer
  # atomicity guarantees. In particular, operations accessing multiple
  # keys are non-atomic.
  #
  # Increment has a number of caveats to its use; please consult the method
  # documentation.
  class Memcache
    import com.google.appengine.api.memcache.Expiration
    import com.google.appengine.api.memcache.InvalidValueException
    import com.google.appengine.api.memcache.LogAndContinueErrorHandler
    import com.google.appengine.api.memcache.MemcacheServiceException
    import com.google.appengine.api.memcache.MemcacheServiceFactory
    import com.google.appengine.api.memcache.MemcacheService
    import com.google.appengine.api.memcache.StrictErrorHandler

    ADD = MemcacheService::SetPolicy::ADD_ONLY_IF_NOT_PRESENT
    REPLACE = MemcacheService::SetPolicy::REPLACE_ONLY_IF_PRESENT
    SET = MemcacheService::SetPolicy::SET_ALWAYS

    # Base Memcache exception class
    class MemcacheError < StandardError; end

    MemCacheError = MemcacheError
    ClientError = MemcacheError
    InternalError = MemcacheError

    MARSHAL_MARKER = '--JRuby Marshal Data--'

    # An exception for backend non-availability or similar error states which
    # may occur, but are not necessarily indicative of a coding or usage error
    # by the application.
    class ServerError < MemcacheError; end

    # Raised when a cache entry has content, but it cannot be read. For example:
    # - An attempt to #incr a non-integral value
    # - Version skew between your application and the data in the cache,
    #   causing a marshaling error.
    class InvalidValueError < MemcacheError; end

    def initialize(*servers)
      options = if servers[-1].kind_of? Hash
        servers[-1]
      else
        {}
      end
      if options.include?(:namespace)
        service.namespace = options[:namespace]
      end
      @readonly = options[:readonly]
    end

    # Returns the Java MemcacheService object used by this Memcache client.
    def service
      @service ||= MemcacheServiceFactory.memcache_service
    end

    def active?
      # TODO use the capability api to see if Memcache is disabled.
      true
    end

    # Empties the cache of all values. Statistics are not affected. Note that
    # #clear does not respect namespaces - this flushes the cache for every
    # namespace.
    #
    # Returns true on success, false on RPC or server error.
    def flush_all
      check_write
      with_errors do
        begin
          service.clear_all
          return true
        rescue MemcacheError
          return false
        end
      end
    end
    alias clear flush_all

    # Gets memcache statistics for this application.
    #
    # All of these statistics may reset due to various transient conditions.
    # They provide the best information available at the time of being called.
    #
    # Returns a Hash mapping statistic names to associated values:
    # [:hits] Number of cache get requests resulting in a cache hit.
    # [:misses] Number of cache get requests resulting in a cache miss.
    # [:byte_hits] Sum of bytes transferred on get requests. Rolls over to
    #              zero on overflow.
    # [:items] Number of key/value pairs in the cache.
    # [:bytes] Total size of all items in the cache.
    # [:oldest_item_age]
    #   How long in seconds since the oldest item in the
    #   cache was accessed. Effectively, this indicates how long a new
    #   item will survive in the cache without being accessed. This is
    #   _not_ the amount of time that has elapsed since the item was
    #   created.
    #
    # On error, returns +nil+.
    def stats
      with_errors do
        begin
          stats = service.statistics
          if stats
            {
              :hits => stats.hit_count,
              :misses => stats.miss_count,
              :byte_hits => stats.bytes_returned_for_hits,
              :items => stats.item_count,
              :bytes => stats.total_item_bytes,
              :oldest_item_age => stats.max_time_without_access / 1000.0
            }
          end
        rescue ServerError
          nil
        end
      end
    end

    # Fetch and return the values associated with the given +key+s from the
    # cache. Returns +nil+ for any value that wasn't in the cache.
    def get(*keys)
      multiple = (keys.size != 1)
      if !multiple && keys[0].kind_of?(Array)
        keys = keys[0]
        multiple = true
      end
      hash = get_hash(*keys)
      values = keys.collect {|key| hash[key]}
      if multiple
        values
      else
        values[0]
      end
    end
    alias [] get

    # Looks up multiple keys from memcache in one operation. This is more
    # efficient than multiple separate calls to #get.
    #
    # Args:
    # - keys: List of keys to look up.
    #
    # Returns a hash of the keys and values that were present in memcache.
    def get_hash(*keys)
      key_map = KeyMap.new(keys)
      convert_exceptions do
        map = service.getAll(key_map.java_keys)
        key_map.map_to_hash(map) do |value|
          if value.java_kind_of?(java.util.ArrayList) && value.size == 2 &&
              value[0] == MARSHAL_MARKER
            Marshal.load(String.from_java_bytes(value[1]))
          else
            value
          end
        end
      end
    end

    # Removes the given key from the cache, and prevents it from being added
    # using #add for +time+ seconds thereafter. Calls to #set are not blocked.
    #
    # Returns true if an entry existed to delete.
    def delete(key, time=nil)
      time ||= 0
      check_write
      convert_exceptions do
        service.delete(memcache_key(key), time * 1000)
      end
    end

    # Removes the given keys from the cache, and prevents them from being added
    # using #add for +time+ seconds thereafter. Calls to #set are not blocked.
    #
    # Returns the set of keys deleted. Any keys in +keys+ but not in the
    # returned set were not found in the cache.
    def delete_many(keys, time=0)
      check_write
      key_map = KeyMap.new(keys)
      convert_exceptions do
        java_keys = service.delete_all(key_map.java_keys, time * 1000)
        key_map.ruby_keys(java_keys)
      end
    end

    # Sets a key's value, iff item is not already in memcache.
    #
    # Args:
    # - key: Key to set.
    # - value: Value to set.  Any type.  If complex, will be marshaled.
    # - expiration: Optional expiration time, either relative number of seconds
    #   from current time (up to 1 month), an absolute Unix epoch time, or a
    #   Time. By default, items never expire, though items may be evicted due
    #   to memory pressure.
    #
    # Returns true if added, false on error.
    def add(key, value, expiration=0)
      put(key, value, expiration, ADD)
    end

    # Set multiple keys' values iff items are not already in memcache.
    #
    # Args:
    # - pairs: Hash of keys to values, or Array of [key, value] pairs.
    # - expiration: Optional expiration time, either relative number of seconds
    #   from current time (up to 1 month), an absolute Unix epoch time, or a
    #   Time. By default, items never expire, though items may be evicted due
    #   to memory pressure.
    #
    # Returns a list of keys whose values were NOT set.  On total success
    # this list should be empty.
    def add_many(pairs, expiration=0)
      put_many(pairs, expiration, ADD)
    end

    # Sets a key's value, regardless of previous contents in cache.
    #
    # Unlike #add and #replace, this method always sets (or
    # overwrites) the value in memcache, regardless of previous
    # contents.
    #
    # Args:
    # - key: Key to set.
    # - value: Value to set.  Any type.  If complex, will be marshaled.
    # - expiration: Optional expiration time, either relative number of seconds
    #   from current time (up to 1 month), an absolute Unix epoch time, or a
    #   Time. By default, items never expire, though items may be evicted due
    #   to memory pressure.
    #
    # Returns true if set, false on error.
    def set(key, value, expiration=0)
      put(key, value, expiration, SET)
    end

    # Set multiple keys' values at once, regardless of previous contents.
    #
    # Args:
    # - pairs: Hash of keys to values, or Array of [key, value] pairs.
    # - expiration: Optional expiration time, either relative number of seconds
    #   from current time (up to 1 month), an absolute Unix epoch time, or a
    #   Time. By default, items never expire, though items may be evicted due
    #   to memory pressure.
    #
    # Returns a list of keys whose values were NOT set.  On total success
    # this list should be empty.
    def set_many(pairs, expiration=0)
      put_many(pairs, expiration, SET)
    end

    # call-seq:
    #   cache[:foo, :bar] = 1, 2
    #
    # Syntactic sugar for calling set_many.
    def []=(*args)
      values = args.pop
      if values.kind_of? Array
        set_many(args.zip(values))
      else
        set(args, values)
      end
    end

    # Replaces a key's value, failing if item isn't already in memcache.
    #
    # Unlike #add and #replace, this method always sets (or
    # overwrites) the value in memcache, regardless of previous
    # contents.
    #
    # Args:
    # - key: Key to set.
    # - value: Value to set.  Any type.  If complex, will be marshaled.
    # - expiration: Optional expiration time, either relative number of seconds
    #   from current time (up to 1 month), an absolute Unix epoch time, or a
    #   Time. By default, items never expire, though items may be evicted due
    #   to memory pressure.
    #
    # Returns true if replaced, false on cache miss.
    def replace(key, value, expiration=0)
      put(key, value, expiration, REPLACE)
    end

    # Replace multiple keys' values, failing if the items aren't in memcache.
    #
    # Args:
    # - pairs: Hash of keys to values, or Array of [key, value] pairs.
    # - expiration: Optional expiration time, either relative number of seconds
    #   from current time (up to 1 month), an absolute Unix epoch time, or a
    #   Time. By default, items never expire, though items may be evicted due
    #   to memory pressure.
    #
    # Returns a list of keys whose values were NOT set.  On total success
    # this list should be empty.
    def replace_many(pairs, expiration=0)
      put_many(pairs, expiration, REPLACE)
    end

    # Atomically fetches, increments, and stores a given integral value.
    # "Integral" types are Fixnum and in some cases String (if the string is
    # parseable as a number. The entry must already exist.
    #
    # Internally, the value is a unsigned 64-bit integer.  Memcache
    # doesn't check 64-bit overflows.  The value, if too large, will
    # wrap around.
    #
    # Args:
    # - key: the key of the entry to manipulate
    # - delta: the size of the increment.
    #
    # Returns the post-increment value.
    #
    # Throws InvalidValueError if the object incremented is not of
    # an integral type.
    def incr(key, delta=1)
      check_write
      convert_exceptions do
        service.increment(memcache_key(key), delta)
      end
    end

    # Atomically fetches, deccrements, and stores a given integral value.
    # "Integral" types are Fixnum and in some cases String (if the string is
    # parseable as a number. The entry must already exist.
    #
    # Internally, the value is a unsigned 64-bit integer.  Memcache
    # caps decrementing below zero to zero.
    #
    # Args:
    # - key: the key of the entry to manipulate
    # - delta: the size of the decrement
    #
    # Returns the post-decrement value.
    #
    # Throws InvalidValueError if the object decremented is not of
    # an integral type.
    def decr(key, delta=1)
      check_write
      convert_exceptions do
        service.increment(memcache_key(key), -delta)
      end
    end

    # Get the name of the namespace that will be used in API calls.
    def namespace
      service.namespace
    end

    # Change the namespace used in API calls.
    def namespace=(value)
      service.namespace = value
    end

    # Returns true if the cache was created read-only.
    def readonly?
      @readonly
    end

    def inspect
      "<Memcache ns:#{namespace.inspect}, ro:#{readonly?.inspect}>"
    end

    # Returns whether the client raises an exception if there's an error
    # contacting the server. By default it will simulate a cache miss
    # instead of raising an error.
    def raise_errors?
      service.error_handler.kind_of? StrictErrorHandler
    end

    # Set whether this client raises an exception if there's an error
    # contacting the server.
    #
    # If +should_raise+ is true, a ServerError is raised whenever there
    # is an error contacting the server.
    #
    # If +should_raise+ is false (the default), a cache miss is simulated
    # instead of raising an error.
    def raise_errors=(should_raise)
      if should_raise
        service.error_handler = StrictErrorHandler.new
      else
        service.error_handler = LogAndContinueErrorHandler.new
      end
    end

    # For backwards compatibility. Simply returns nil
    def do_nothing(*args)
    end
    alias server_item_stats do_nothing
    alias server_malloc_stats do_nothing
    alias server_map_stats do_nothing
    alias server_reset_stats do_nothing
    alias server_size_stats do_nothing
    alias server_slab_stats do_nothing
    alias server_stats do_nothing
    alias servers= do_nothing

    private

    def memcache_key(obj)
      key = obj
      key = java.lang.String.new(key.to_s) if key
      key
    end

    def memcache_value(obj)
      case obj
      when Fixnum
        java.lang.Long.new(obj)
      when Float
        java.lang.Double.new(obj)
      when TrueClass, FalseClass
        java.lang.Boolean.new(obj)
      when JavaProxy, Java::JavaObject
        obj
      else
        if obj.class == String
          # Convert plain strings to Java strings
          java.lang.String.new(obj)
        else
          bytes = Marshal.dump(obj).to_java_bytes
          java.util.ArrayList.new([java.lang.String.new(MARSHAL_MARKER), bytes])
        end
      end
    end

    def memcache_expiration(amount)
      if amount.nil? || amount == 0
        nil
      elsif amount.kind_of? Time
        Expiration.on_date(amount.to_java)
      elsif amount > 86400 * 30
        millis = (amount * 1000).to_i
        Expiration.on_date(java.util.Date.new(millis))
      else
        Expiration.byDeltaMillis((amount * 1000).to_i)
      end
    end

    def check_write
      raise MemcacheError, "readonly cache" if self.readonly?
    end

    def with_errors(&block)
      saved_handler = service.error_handler
      begin
        service.error_handler = StrictErrorHandler.new
        convert_exceptions(&block)
      ensure
        service.error_handler = saved_handler
      end
    end

    def convert_exceptions
      begin
        yield
      rescue java.lang.IllegalArgumentException => ex
        raise ArgumentError, ex.message
      rescue InvalidValueException => ex
        raise InvalidValueError, ex.message
      rescue MemcacheServiceException => ex
        raise ServerError, ex.message
      end
    end

    def put(key, value, expiration, mode)
      check_write
      convert_exceptions do
        key = memcache_key(key)
        value = memcache_value(value)
        expiration = memcache_expiration(expiration)
        service.put(key, value, expiration, mode)
      end
    end

    def put_many(pairs, expiration, mode)
      check_write
      expiration = memcache_expiration(expiration)
      convert_exceptions do
        key_map = KeyMap.new
        put_map = java.util.HashMap.new
        pairs.each do |key, value|
          java_key = key_map << key
          java_value = memcache_value(value)
          put_map.put(java_key, java_value)
        end
        saved_keys = service.put_all(put_map, expiration, mode)
        key_map.missing_keys(saved_keys)
      end
    end

    class KeyMap  # :nodoc:
      def initialize(keys=[])
        @orig_keys = []
        @map = {}
        keys.each do |key|
          self << key
        end
      end

      def <<(key)
        @orig_keys << key
        string_key = if key
          key.to_s
        else
          key
        end
        @map[string_key] = key
        if string_key
          java.lang.String.new(string_key)
        else
          string_key
        end
      end

      def java_keys
        @map.keys.collect do |key|
          if key
            java.lang.String.new(key)
          else
            key
          end
        end
      end

      def ruby_keys(keys)
        keys.collect {|key| @map[key]}
      end

      def missing_keys(keys)
        @orig_keys - ruby_keys(keys)
      end

      def map_to_hash(java_map)
        hash = {}
        if java_map
          java_map.each do |key, value|
            value = yield(value)
            hash[@map[key]] = value
          end
        end
        hash
      end
    end
  end
end


text:
<?xml version='1.0' encoding='utf-8'?>
<!--
This file is part of Intake24.

Copyright 2015, 2016 Newcastle University.

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.
-->

<as-served-sets
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="./Schemas/as-served.xsd">

</as-served-sets>


text:
var Room = require('./room.server.model.js');
var Q = require('q');

module.exports = {
  newRoom: function (req, res, next) {
    var room = {};

    room.name = req.body.name;
    room.ownerName = req.user.socialData.name;
    room.owner = req.user._id;

    var createRoom = Q.nbind(Room.create, Room);

    createRoom(room)
      .then(function (createdRoom) {
        if (createdRoom) {
          res.json(createdRoom);
        }
      })
      .fail(function (error) {
        next(error);
      });
  },

  allRooms: function(req, res, next) {
    var getRooms = Q.nbind(Room.find, Room);
    getRooms({})
    .then(function(allRooms) {
      if(allRooms) {
        res.json(allRooms);
      }
    })
    .fail(function(error) {
      next(error);
    });
  },

  updateRoom: function(req, res, next) {
    //we convert the request objects into strings just to be safe(req.user._id was coming back as an object for some reason)
    var user = String(req.user._id)
    var roomCreator = String(req.body.owner)

    //if user was not the originator of hte Room, throw an error
    if (user !== roomCreator) {
      console.log('user not authorized to update this resource. sending back 401 Unauthorized')
      res.status(401)
    }

    // create promise for Room.findById
    var findRoomById = Q.nbind(Room.findById, Room);

    // attempt to find the room by the id passed in
    findRoomById(req.params.room_id)
      .then(function(foundRoom) {
        // if the room is found update the name and save
        if (foundRoom) {
          foundRoom.name = req.body.name;
          foundRoom.save(function(err) {
            if (err) {
              res.send(err);
            }
            res.json(foundRoom);
          });
        }
      })
      .fail(function(error) {
        next(error);
      });
  },

  deleteRoom: function(req, res, next) {
    //we convert the request objects into strings just to be safe(req.user._id was coming back as an object for some reason)
    var user = String(req.user._id)
    var roomCreator = String(req.body.owner)

    //if user was not the originator of hte room, throw an error
    if (user !== roomCreator) {
      console.log('user not authorized to delete this resource. sending back 401 Unauthorized')
      res.status(401)
    }

    // create promise for Room.remove method
    var removeRoom = Q.nbind(Room.remove, Room);
    // delete room based on id passed in
    removeRoom({_id: req.params.room_id})
      .then(function(removedRoom) {
        // if the room has been removed, send success
        // and id to remove from roomStore
        if(removedRoom[1].ok) {
          res.json({
            message: 'Successfully deleted.',
            _id: req.params.room_id
          });
        }
      })
      .fail(function(error) {
        next(error);
      });
  }
};


text:
from __future__ import absolute_import

import logging

from sentry.utils.services import Service
from sentry.tasks.post_process import post_process_group

logger = logging.getLogger(__name__)

class EventStream(Service):
    __all__ = (
        'publish',
    )

    def publish(self, group, event, is_new, is_sample, is_regression, is_new_group_environment, primary_hash, skip_consume=False):
        if skip_consume:
            logger.info('post_process.skip.raw_event', extra={'event_id': event.id})
        else:
            post_process_group.delay(
                group=group,
                event=event,
                is_new=is_new,
                is_sample=is_sample,
                is_regression=is_regression,
                is_new_group_environment=is_new_group_environment,
                primary_hash=primary_hash,
            )


text:
import * as React from "react";
import { FCReturn, FCProps } from "../../../typings/shared";

/**
 * Convenience interface for the custom render prop.
 */
export interface HeaderContainerRenderProps {
    isSideNavExpanded: boolean,
    onClickSideNavExpand(): void;
}

export interface HeaderContainerProps<RP = HeaderContainerRenderProps> {
    isSideNavExpanded?: boolean | undefined,
    render: React.ComponentType<RP>,
}

declare function HeaderContainer<RP = HeaderContainerRenderProps>(
    props: FCProps<HeaderContainerProps<RP>>
): FCReturn;

export default HeaderContainer;


text:
using MoG.Domain.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MoG
{
    public static class SecurityExtension
    {
        public static bool HasRight(
            this HtmlHelper htmlHelper,
            object context,
            SecureActivity activity)
        {
            return true;
            //SecurityService service = new SecurityService();
        }
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\PhpUnit;

use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class PhpUnitStrictFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface
{
    private static $assertionMap = [
        'assertAttributeEquals' => 'assertAttributeSame',
        'assertAttributeNotEquals' => 'assertAttributeNotSame',
        'assertEquals' => 'assertSame',
        'assertNotEquals' => 'assertNotSame',
    ];

    /**
     * {@inheritdoc}
     */
    public function getDefinition(): FixerDefinitionInterface
    {
        return new FixerDefinition(
            'PHPUnit methods like `assertSame` should be used instead of `assertEquals`.',
            [
                new CodeSample(
                    '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testSomeTest()
    {
        $this->assertAttributeEquals(a(), b());
        $this->assertAttributeNotEquals(a(), b());
        $this->assertEquals(a(), b());
        $this->assertNotEquals(a(), b());
    }
}
'
                ),
                new CodeSample(
                    '<?php
final class MyTest extends \PHPUnit_Framework_TestCase
{
    public function testSomeTest()
    {
        $this->assertAttributeEquals(a(), b());
        $this->assertAttributeNotEquals(a(), b());
        $this->assertEquals(a(), b());
        $this->assertNotEquals(a(), b());
    }
}
',
                    ['assertions' => ['assertEquals']]
                ),
            ],
            null,
            'Risky when any of the functions are overridden or when testing object equality.'
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isRisky(): bool
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex): void
    {
        $argumentsAnalyzer = new ArgumentsAnalyzer();
        $functionsAnalyzer = new FunctionsAnalyzer();

        foreach ($this->configuration['assertions'] as $methodBefore) {
            $methodAfter = self::$assertionMap[$methodBefore];

            for ($index = $startIndex; $index < $endIndex; ++$index) {
                $methodIndex = $tokens->getNextTokenOfKind($index, [[T_STRING, $methodBefore]]);

                if (null === $methodIndex) {
                    break;
                }

                if (!$functionsAnalyzer->isTheSameClassCall($tokens, $methodIndex)) {
                    continue;
                }

                $openingParenthesisIndex = $tokens->getNextMeaningfulToken($methodIndex);
                $argumentsCount = $argumentsAnalyzer->countArguments(
                    $tokens,
                    $openingParenthesisIndex,
                    $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex)
                );

                if (2 === $argumentsCount || 3 === $argumentsCount) {
                    $tokens[$methodIndex] = new Token([T_STRING, $methodAfter]);
                }

                $index = $methodIndex;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
    {
        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('assertions', 'List of assertion methods to fix.'))
                ->setAllowedTypes(['array'])
                ->setAllowedValues([new AllowedValueSubset(array_keys(self::$assertionMap))])
                ->setDefault([
                    'assertAttributeEquals',
                    'assertAttributeNotEquals',
                    'assertEquals',
                    'assertNotEquals',
                ])
                ->getOption(),
        ]);
    }
}


text:
#include "data_process.hpp"
/*
void display_all(std::map<long, Anime>* const alist){
  for (std::map<long, Anime>::iterator it=alist->begin(); it!=alist->end(); ++it)
    std::cout << it->second;
}*/


text:
class PeopleController < HasAccountsController
  def index
    set_collection_ivar resource_class.search(
      params[:by_text],
      :star => true,
      :page => params[:page]
    )
  end

  def show
    # Invoice scoping by state
    @invoices = resource.invoices.where("type != 'Salary'").invoice_state(params[:invoice_state])

    show!
  end

  # has_many :phone_numbers
  def new_phone_number
    if resource_id = params[:id]
      @person = Person.find(resource_id)
    else
      @person = resource_class.new
    end

    @vcard = @person.vcard
    @item = @vcard.contacts.build

    respond_with @item
  end
end


text:
using System;

/// <summary>
/// Empty
/// </summary>

public class TypeCodeEmpty
{
    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;

        //
        // TODO: Add your negative test cases here
        //
        // TestLibrary.TestFramework.LogInformation("[Negative]");
        // retVal = NegTest1() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify TypeCode.Empty .");

        try
        {
            int i = (int)TypeCode.Empty;

            if (i != 0)
            {
                TestLibrary.TestFramework.LogError("001.1", "TypeCode.Empty Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion

    #region Nagetive Test Cases
    //public bool NegTest1()
    //{
    //    bool retVal = true;

    //    TestLibrary.TestFramework.BeginScenario("NegTest1: ");

    //    try
    //    {
    //          //
    //          // Add your test logic here
    //          //
    //    }
    //    catch (Exception e)
    //    {
    //        TestLibrary.TestFramework.LogError("101", "Unexpected exception: " + e);
    //        TestLibrary.TestFramework.LogInformation(e.StackTrace);
    //        retVal = false;
    //    }

    //    return retVal;
    //}
    #endregion
    #endregion

    public static int Main()
    {
        TypeCodeEmpty test = new TypeCodeEmpty();

        TestLibrary.TestFramework.BeginTestCase("TypeCodeEmpty");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
import numpy as numpy
from matplotlib.ticker import Formatter

class _FormatterMixin(Formatter):
    """ A mpl-axes formatter mixin class """

    @classmethod
    def _sig_figs(cls, x, n, expthresh=5, forceint=False):
        """
        Formats a number with the correct number of significant digits.

        Parameters
        ----------
        x : int or float
            The number you want to format.
        n : int
            The number of significant figures it should have.
        expthresh : int, optional (default = 5)
            The absolute value of the order of magnitude at which numbers
            are formatted in exponential notation.
        forceint : bool, optional (default is False)
            If true, simply returns int(x)

        Returns
        -------
        formatted : str
            The formatted number as a string

        Examples
        --------
        >>> _sig_figs(1247.15, 3)
        '1250'
        >>> _sig_figs(1247.15, 7)
        '1247.150'

        """

        # return a string value unaltered
        if isinstance(x, str):
            out = cls._sig_figs(float(x), n, expthresh=expthresh, forceint=forceint)

        elif x == 0.0:
            out = "0"

        # check on the number provided
        elif x is not None and numpy.isfinite(x):

            # check on the _sig_figs
            if n < 1:
                raise ValueError("number of sig figs (n) must be greater " "than zero")

            elif forceint:
                out = "{:,.0f}".format(x)

            # logic to do all of the rounding
            else:
                order = numpy.floor(numpy.log10(numpy.abs(x)))

                if -1.0 * expthresh <= order <= expthresh:
                    decimal_places = int(n - 1 - order)

                    if decimal_places <= 0:
                        out = "{0:,.0f}".format(round(x, decimal_places))

                    else:
                        fmt = "{0:,.%df}" % decimal_places
                        out = fmt.format(x)

                else:
                    decimal_places = n - 1
                    fmt = "{0:.%de}" % decimal_places
                    out = fmt.format(x)

        # with NAs and INFs, just return 'NA'
        else:
            out = "NA"

        return out

    def __call__(self, x, pos=None):
        if x < (10 / self.factor):
            out = self._sig_figs(x, 1)
        elif x <= (99 / self.factor):
            out = self._sig_figs(x, 2)
        else:
            order = numpy.ceil(numpy.round(numpy.abs(numpy.log10(self.top - x)), 6))
            out = self._sig_figs(x, order + self.offset)

        return "{}".format(out)

class PctFormatter(_FormatterMixin):
    """
    Formatter class for MPL axes to display probabilities as percentages.

    Examples
    --------
    >>> from probscale import formatters
    >>> fmt = formatters.PctFormatter()
    >>> fmt(0.2)
    '0.2'
    >>> fmt(10)
    '10'
    >>> fmt(99.999)
    '99.999'

    """

    factor = 1.0
    offset = 2
    top = 100

class ProbFormatter(_FormatterMixin):
    """
    Formatter class for MPL axes to display probabilities as decimals.

    Examples
    --------
    >>> from probscale import formatters
    >>> fmt = formatters.ProbFormatter()
    >>> fmt(0.01)
    '0.01'
    >>> fmt(0.2)
    '0.20'
    >>> try:
    ...    fmt(10.5)
    ... except(ValueError):
    ...     print('formatter out of bounds')
    formatter out of bounds
    """

    factor = 100.0
    offset = 0
    top = 1


text:
<?php
/**
 * Smarty plugin
 *
 * @package    Smarty
 * @subpackage PluginsFunction
 * @author		Bismay Kumar Mohaptra
 */

function smarty_function_module($params, Smarty_Internal_Template $template) {
	$src=explode(".",$params['src']);
	if(count($src)<=1) {
		$GLOBALS['PAGETMPL']=$template->smarty;
		$_ENV['MODULECONFIG'][$params['src']]=$params;
		if(checkModule($params['src'])) {
			return loadModule($params['src']);
		} else {
			return "

Module '{$params['src']}' Not Found.
<citie>Please install it using Package Manager</citie>
";
		}
	} else {
		$GLOBALS['PAGETMPL']=$template->smarty;
		$_ENV['MODULECONFIG'][$src[0]]=$params;
		loadModuleLib($src[0],$src[1]);
	}
}
?>


text:
#ifndef FLAC__PRIVATE__OGG_MAPPING_H
#define FLAC__PRIVATE__OGG_MAPPING_H

#include "FLAC/ordinals.h"

/** The length of the 'FLAC' magic in bytes. */
#define FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH (1u)

extern const unsigned FLAC__OGG_MAPPING_PACKET_TYPE_LEN; /* = 8 bits */

extern const FLAC__byte FLAC__OGG_MAPPING_FIRST_HEADER_PACKET_TYPE; /* = 0x7f */

/** The length of the 'FLAC' magic in bytes. */
#define FLAC__OGG_MAPPING_MAGIC_LENGTH (4u)

extern const FLAC__byte * const FLAC__OGG_MAPPING_MAGIC; /* = "FLAC" */

extern const unsigned FLAC__OGG_MAPPING_VERSION_MAJOR_LEN; /* = 8 bits */
extern const unsigned FLAC__OGG_MAPPING_VERSION_MINOR_LEN; /* = 8 bits */

/** The length of the Ogg FLAC mapping major version number in bytes. */
#define FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH (1u)

/** The length of the Ogg FLAC mapping minor version number in bytes. */
#define FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH (1u)

extern const unsigned FLAC__OGG_MAPPING_NUM_HEADERS_LEN; /* = 16 bits */

/** The length of the #-of-header-packets number bytes. */
#define FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH (2u)

#endif


text:
{% assign current_url = page.url | prepend: site.github.url %}

{% if include.url == current_url %}

{% else %}

{% endif %}

{{ include.title }}