text:
from api.decorators import api_view, request_data
from api.permissions import IsAdmin, IsSuperAdminOrReadOnly
from api.dc.group.api_views import DcGroupView

__all__ = ('dc_group_list', 'dc_group')

@api_view(('GET',))
@request_data(permissions=(IsAdmin, IsSuperAdminOrReadOnly))
def dc_group_list(request, data=None):
    """
    List (:http:get:`GET </dc/(dc)/group>`) groups available in current datacenter (dc).

    .. http:get:: /dc/(dc)/group

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg request.dc: **required** - Datacenter name
        :type request.dc: string
        :arg data.full: Return list of objects with all group details (default: false)
        :type data.full: boolean
        :arg data.order_by: :ref:`Available fields for sorting <order_by>`: ``name`` (default: ``name``)
        :type data.order_by: string
        :status 200: SUCCESS
        :status 403: Forbidden
        :status 404: Datacenter not found
    """
    return DcGroupView(request, None, data).get(many=True)

# noinspection PyUnusedLocal
@api_view(('GET', 'POST', 'DELETE'))
@request_data(permissions=(IsAdmin, IsSuperAdminOrReadOnly))
def dc_group(request, name, data=None):
    """
    Show (:http:get:`GET </dc/(dc)/group/(name)>`),
    create (:http:post:`POST </dc/(dc)/group/(name)>`) or
    delete (:http:delete:`DELETE </dc/(dc)/group/(name)>`)
    a group (name) association with a datacenter (dc).

    .. http:get:: /dc/(dc)/group/(name)

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |Admin|
        :Asynchronous?:
            * |async-no|
        :arg request.dc: **required** - Datacenter name
        :type request.dc: string
        :arg request.name: **required** - Group name
        :type request.name: string
        :status 200: SUCCESS
        :status 403: Forbidden
        :status 404: Datacenter not found / Group not found

    .. http:post:: /dc/(dc)/group/(name)

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |SuperAdmin|
        :Asynchronous?:
            * |async-no|
        :arg request.dc: **required** - Datacenter name
        :type request.dc: string
        :arg request.name: **required** - Group name
        :type request.name: string

        :status 200: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 404: Datacenter not found / Group not found
        :status 406: Group already exists

    .. http:delete:: /dc/(dc)/group/(name)

        :DC-bound?:
            * |dc-yes|
        :Permissions:
            * |SuperAdmin|
        :Asynchronous?:
            * |async-no|
        :arg request.dc: **required** - Datacenter name
        :type request.dc: string
        :arg request.name: **required** - Group name
        :type request.name: string

        :status 200: SUCCESS
        :status 400: FAILURE
        :status 403: Forbidden
        :status 404: Datacenter not found / Group not found
    """
    return DcGroupView(request, name, data).response()


text:
'use strict';

angular
  .module('clientApp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngRoute'
  ])
  .config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);

    $routeProvider
      .when('/', {
        templateUrl: 'views/dashboard.html',
        controller: 'DashboardCtrl'
      })
      .when('/users', {
        templateUrl: 'views/users.html',
        controller: 'UsersCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .run(function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function(ev, data) {
     if (data.$$route && data.$$route.controller) {
       $rootScope.controller = data.$$route.controller;
     }
    });
  });

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
import classNames from 'classnames';
import { RadioButton as CoreRadio } from 'wix-ui-core/radio-button';
import { st, classes } from './Ratings.st.css';
import { ReactComponent as StarIcon } from '../../assets/icons/Star.svg';
import { RATINGS_DATA_HOOKS, RATINGS_DATA_KEYS } from './dataHooks';
import { TPAComponentProps } from '../../types';

export enum Size {
  Small = 'small',
  Large = 'large',
}

export enum Mode {
  Input = 'input',
  Display = 'display',
}

export enum Layout {
  Aside = 'aside',
  Bottom = 'bottom',
}

export interface RatingsProps extends TPAComponentProps {
  value: number;
  mode: Mode;
  onSelect?(value: number): void;
  inputOptions?: string[];
  disabled?: boolean;
  error?: boolean;
  size?: Size;
  layout?: Layout;
  ratingDisplay?: string;
  countDisplay?: string;
  'data-hook'?: string;
  name?: string;
}

interface DefaultProps {
  value: number;
  disabled: boolean;
  error: boolean;
  mode: Mode;
  size: Size;
  layout: Layout;
  inputOptions: string[];
}

interface RatingsState {
  currentHovered: number;
  currentFocus: number;
}

/** Ratings component based on IconToggle */
export class Ratings extends React.Component<RatingsProps, RatingsState> {
  static displayName = 'Ratings';
  static defaultProps: DefaultProps = {
    value: 0,
    disabled: false,
    error: false,
    mode: Mode.Input,
    size: Size.Small,
    layout: Layout.Aside,
    inputOptions: [],
  };

  state: RatingsState = {
    currentHovered: -1,
    currentFocus: -1,
  };

  _getDataAttributes() {
    const { currentHovered } = this.state;
    const { disabled, error, size } = this.props;

    return {
      [RATINGS_DATA_KEYS.Disabled]: disabled,
      [RATINGS_DATA_KEYS.Error]: error,
      [RATINGS_DATA_KEYS.Size]: size,
      [RATINGS_DATA_KEYS.Hovered]: currentHovered + 1,
    };
  }

  _handleHoverIcon = (idx: number) => {
    this.setState({ currentHovered: idx });
  };

  _handleUnHoverIcon = () => {
    this.setState({ currentHovered: -1 });
  };

  _onClick = (idx: number) => {
    const { mode, onSelect } = this.props;

    if (mode === Mode.Input && onSelect) {
      onSelect(idx);
    }
  };

  _renderContent = () => <StarIcon />;

  _renderInputOptions = () => {
    const { inputOptions, value } = this.props;
    const { currentHovered } = this.state;

    return (
      <div className={classes.labelList}>
        {currentHovered > -1 ? (
          <span
            data-hook={RATINGS_DATA_HOOKS.InputOption}
            className={classes.inputOption}
          >
            {inputOptions[currentHovered]}
          </span>
        ) : (
          <span
            data-hook={RATINGS_DATA_HOOKS.InputOptionCurrent}
            className={classNames(
              classes.inputOption,
              classes.inputOptionCurrent,
            )}
          >
            {inputOptions[value - 1]}
          </span>
        )}
      </div>
    );
  };

  _renderRatingInfo = () => {
    const { ratingDisplay, countDisplay } = this.props;
    const info = [];

    if (ratingDisplay) {
      info.push(ratingDisplay);
    }

    if (countDisplay) {
      info.push(countDisplay);
    }

    return (
      <div
        data-hook={RATINGS_DATA_HOOKS.RatingInfo}
        className={classes.ratingInfo}
      >
        {info.join(' | ')}
      </div>
    );
  };

  render() {
    const {
      value,
      disabled,
      error,
      size,
      mode,
      inputOptions,
      layout,
      ratingDisplay,
      countDisplay,
      className,
    } = this.props;
    const content = this._renderContent();
    const ratingList = Array.from(new Array(5));
    const showInputOptions = inputOptions.length && mode === Mode.Input;
    const showRatingInfo =
      (ratingDisplay || countDisplay) && mode === Mode.Display;

    return (
      <div
        className={st(
          classes.root,
          { disabled, error, size, mode, layout },
          className,
        )}
        {...this._getDataAttributes()}
        data-hook={this.props['data-hook']}
      >
        <div
          className={`${classes.iconList} ${!value ? classes.empty : ''}`}
          role={'group'}
          tabIndex={mode === Mode.Display ? -1 : undefined}
        >
          {ratingList.map((_el, idx: number) => {
            const checked = idx + 1 === value;
            const ariaLabel = inputOptions.length
              ? inputOptions[idx]
              : idx.toString();

            return (
              <CoreRadio
                key={idx}
                value={`${idx + 1}`}
                aria-label={ariaLabel}
                uncheckedIcon={content}
                checkedIcon={content}
                checked={checked}
                disabled={disabled && mode !== Mode.Display}
                onChange={() => this._onClick(idx + 1)}
                name={this.props.name}
                className={st(classes.icon, { checked })}
                data-hook={RATINGS_DATA_HOOKS.IconWrapper}
                onHover={() => this._handleHoverIcon(idx)}
                onIconBlur={this._handleUnHoverIcon}
              />
            );
          })}
        </div>
        {!!showInputOptions && this._renderInputOptions()}
        {!!showRatingInfo && this._renderRatingInfo()}
      </div>
    );
  }
}


text:
package org.locationtech.geomesa.core.iterators

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream}
import java.util.{Collection => JCollection, Date, Map => JMap}

import com.typesafe.scalalogging.slf4j.Logging
import com.vividsolutions.jts.geom._
import org.apache.accumulo.core.client.IteratorSetting
import org.apache.accumulo.core.data.{ByteSequence, Key, Range => ARange, Value}
import org.apache.accumulo.core.iterators.{IteratorEnvironment, SortedKeyValueIterator}
import org.apache.commons.codec.binary.Base64
import org.geotools.feature.simple.SimpleFeatureBuilder
import org.geotools.geometry.jts.JTSFactoryFinder
import org.joda.time.{DateTime, Interval}
import org.locationtech.geomesa.core.index.getDtgFieldName
import org.locationtech.geomesa.core.iterators.FeatureAggregatingIterator.Result
import org.locationtech.geomesa.core.iterators.TemporalDensityIterator.TimeSeries
import org.locationtech.geomesa.utils.geotools.TimeSnap

import scala.collection.mutable

class TemporalDensityIterator(other: TemporalDensityIterator, env: IteratorEnvironment)
  extends FeatureAggregatingIterator[TemporalDensityIteratorResult](other, env) {

  import org.locationtech.geomesa.core.iterators.TemporalDensityIterator.{TEMPORAL_DENSITY_FEATURE_SFT_STRING, TimeSeries}

  var snap: TimeSnap = null
  var dateTimeFieldName: String = null

  projectedSFTDef = TEMPORAL_DENSITY_FEATURE_SFT_STRING

  def this() = this(null, null)

  override def initProjectedSFTDefClassSpecificVariables(source: SortedKeyValueIterator[Key, Value],
                                                         options: JMap[String, String],
                                                         env: IteratorEnvironment): Unit = {

    dateTimeFieldName = getDtgFieldName(simpleFeatureType).getOrElse ( throw new IllegalArgumentException("dtg field required"))

    val buckets = TemporalDensityIterator.getBuckets(options)
    val bounds = TemporalDensityIterator.getTimeBounds(options)
    snap = new TimeSnap(bounds, buckets)
  }

  override def handleKeyValue(resultO: Option[TemporalDensityIteratorResult],
                              topSourceKey: Key,
                              topSourceValue: Value): TemporalDensityIteratorResult = {
    val date = originalDecoder.decode(topSourceValue.get()).getAttribute(dateTimeFieldName).asInstanceOf[Date]
    val dateTime = new DateTime(date.getTime)
    val result = resultO.getOrElse(TemporalDensityIteratorResult())
    addResultDate(dateTime, result.timeSeries)
    result
  }

  /** take a given Coordinate and add 1 to the result time that it corresponds to via the snap time */
  def addResultDate(date: DateTime, result: TimeSeries): Unit = {
    val t: DateTime = snap.t(snap.i(date))
    val cur: Long = result.getOrElse(t, 0L)
    result.put(t, cur + 1L)
  }
}

object TemporalDensityIterator extends Logging {

  val INTERVAL_KEY = "geomesa.temporal.density.bounds"
  val BUCKETS_KEY = "geomesa.temporal.density.buckets"
  val ENCODED_TIME_SERIES: String = "timeseries"
  val TEMPORAL_DENSITY_FEATURE_SFT_STRING = s"$ENCODED_TIME_SERIES:String,geom:Geometry"

  val zeroPoint = new GeometryFactory().createPoint(new Coordinate(0,0))

  type TimeSeries = collection.mutable.HashMap[DateTime, Long]

  val geomFactory = JTSFactoryFinder.getGeometryFactory

  def configure(cfg: IteratorSetting, interval : Interval, buckets: Int) = {
    setTimeBounds(cfg, interval)
    setBuckets(cfg, buckets)
  }

  def setTimeBounds(iterSettings: IteratorSetting, interval: Interval) : Unit = {
    iterSettings.addOption(INTERVAL_KEY,  s"${interval.getStart.getMillis},${interval.getEnd.getMillis}")
  }

  def setBuckets(iterSettings: IteratorSetting, buckets: Int): Unit = {
    iterSettings.addOption(BUCKETS_KEY, s"$buckets")
  }

  def getBuckets(options: JMap[String, String]): Int = {
    options.get(BUCKETS_KEY).toInt
  }

  def getTimeBounds(options: JMap[String, String]): Interval = {
    val Array(s, e) = options.get(INTERVAL_KEY).split(",").map(_.toLong)
    new Interval(s, e)
  }

  def combineTimeSeries(ts1: TimeSeries, ts2: TimeSeries) : TimeSeries = {
    val resultTS = new collection.mutable.HashMap[DateTime, Long]()
    for (key <- ts1.keySet ++ ts2.keySet) {
      resultTS.put(key, ts1.getOrElse(key, 0L) + ts2.getOrElse(key,0L))
    }
    resultTS
  }

  def encodeTimeSeries(timeSeries: TimeSeries): String = {
    val baos = new ByteArrayOutputStream()
    val os = new DataOutputStream(baos)
    for((date,count) <- timeSeries) {
      os.writeLong(date.getMillis)
      os.writeLong(count)
    }
    os.flush()
    Base64.encodeBase64URLSafeString(baos.toByteArray)
  }

  def decodeTimeSeries(encoded: String): TimeSeries = {
    val bytes = Base64.decodeBase64(encoded)
    val is = new DataInputStream(new ByteArrayInputStream(bytes))
    val table = new collection.mutable.HashMap[DateTime, Long]()
    while(is.available() > 0) {
      val dateIdx = new DateTime(is.readLong())
      val weight = is.readLong()
      table.put(dateIdx, weight)
    }
    table
  }
}

case class TemporalDensityIteratorResult(timeSeries: TimeSeries = new mutable.HashMap[DateTime, Long]) extends Result {
  override def addToFeature(featureBuilder: SimpleFeatureBuilder): Unit =
    featureBuilder.add(TemporalDensityIterator.encodeTimeSeries(timeSeries))
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <link href="styleHome.css" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet">
        <title>Home</title>

Home

History

Entertainment

Local Arts

Local Shops

City of Lawrenceville


text:
// @module: commonjs
// @includebuiltfile: typescript_standalone.d.ts
// @noImplicitAny:true
// @strictNullChecks:true

/*
 * Note: This test is a public API sample. The sample sources can be found
         at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services
 *       Please log a "breaking change" issue for any API breaking change affecting this issue
 */

declare var process: any;
declare var console: any;
declare var fs: {
    existsSync(path: string): boolean;
    readdirSync(path: string): string[];
    readFileSync(filename: string, encoding?: string): string;
    writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; } | string): void;
    watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: { mtime: Date }, prev: { mtime: Date }) => void): void;
};
declare var path: any;

import * as ts from "typescript";

function watch(rootFileNames: string[], options: ts.CompilerOptions) {
    const files: ts.MapLike<{ version: number }> = {};

    // initialize the list of files
    rootFileNames.forEach(fileName => {
        files[fileName] = { version: 0 };
    });

    // Create the language service host to allow the LS to communicate with the host
    const servicesHost: ts.LanguageServiceHost = {
        getScriptFileNames: () => rootFileNames,
        getScriptVersion: (fileName) => files[fileName] && files[fileName].version.toString(),
        getScriptSnapshot: (fileName) => {
            if (!fs.existsSync(fileName)) {
                return undefined;
            }

            return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString());
        },
        getCurrentDirectory: () => process.cwd(),
        getCompilationSettings: () => options,
        getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
    };

    // Create the language service files
    const services = ts.createLanguageService(servicesHost, ts.createDocumentRegistry())

    // Now let's watch the files
    rootFileNames.forEach(fileName => {
        // First time around, emit all files
        emitFile(fileName);

        // Add a watch on the file to handle next change
        fs.watchFile(fileName,
            { persistent: true, interval: 250 },
            (curr, prev) => {
                // Check timestamp
                if (+curr.mtime <= +prev.mtime) {
                    return;
                }

                // Update the version to signal a change in the file
                files[fileName].version++;

                // write the changes to disk
                emitFile(fileName);
            });
    });

    function emitFile(fileName: string) {
        let output = services.getEmitOutput(fileName);

        if (!output.emitSkipped) {
            console.log(`Emitting ${fileName}`);
        }
        else {
            console.log(`Emitting ${fileName} failed`);
            logErrors(fileName);
        }

        output.outputFiles.forEach(o => {
            fs.writeFileSync(o.name, o.text, "utf8");
        });
    }

    function logErrors(fileName: string) {
        let allDiagnostics = services.getCompilerOptionsDiagnostics()
            .concat(services.getSyntacticDiagnostics(fileName))
            .concat(services.getSemanticDiagnostics(fileName));

        allDiagnostics.forEach(diagnostic => {
            let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
            if (diagnostic.file) {
                let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!);
                console.log(`  Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
            }
            else {
                console.log(`  Error: ${message}`);
            }
        });
    }
}

// Initialize files constituting the program as all .ts files in the current directory
const currentDirectoryFiles = fs.readdirSync(process.cwd()).
    filter(fileName=> fileName.length >= 3 && fileName.substr(fileName.length - 3, 3) === ".ts");

// Start the watcher
watch(currentDirectoryFiles, { module: ts.ModuleKind.CommonJS });


text:
//
// Author: Ian Davis <ian.f.davis@gmail.com> Copyright (c) 2007, Ian Davs
//
// Portions of this software were developed for NUnit. See NOTICE.txt for more
// information.
//
// 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.
//

#endregion

using System;
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following set
// of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Ensurance")]
[assembly: AssemblyCopyright("Copyright ©  2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]

// Version information for an assembly consists of the following four values:
//
//      Major Version Minor Version Build Number Revision
//
// You can specify all the values or you can default the Revision and Build
// Numbers by using the '*' as shown below:

[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]


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

<title>fr.ujm.tse.lt2c.satin.dictionary.test</title>
<meta name="date" content="2014-10-31">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

fr.ujm.tse.lt2c.satin.dictionary.test

Classes

TestDictionnary


text:
// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ClearQuestOleServer;
using Microsoft.TeamFoundation.Migration.ClearQuestAdapter.ConflictManagement;
using Microsoft.TeamFoundation.Migration.ClearQuestAdapter.CQInterop;
using Microsoft.TeamFoundation.Migration.ClearQuestAdapter.Exceptions;
using Microsoft.TeamFoundation.Migration.ClearQuestAdapter.Linking;
using Microsoft.TeamFoundation.Migration.BusinessModel;
using Microsoft.TeamFoundation.Migration.Toolkit;
using Microsoft.TeamFoundation.Migration.Toolkit.Linking;
using Microsoft.TeamFoundation.Migration.Toolkit.Services;
using Microsoft.TeamFoundation.Migration.Toolkit.ErrorManagement;
using System.Globalization;

namespace Microsoft.TeamFoundation.Migration.ClearQuestAdapter
{
    internal class ClearQuestLinkProvider : ILinkProvider, IServiceProvider
    {
        private readonly List<Guid> m_supportedChangeActions;               // Registered supported link change actions
        private readonly Dictionary<string, LinkType> m_supportedLinkTypes; // Registered supported link types
        private ICollection<string> m_supportedLinkTypeReferenceNamesOther; // Registered link types from the other side
        protected ICollection<IArtifactHandler> m_artifactHandlers;         // Registered artifact handlers

        protected ServiceContainer m_serviceContainer;
        protected ILinkTranslationService m_linkTranslationService;         // LinkService for creating LinkChangeGroup, etc.
        protected ConflictManager m_conflictManager;                        // Conflict Manager to register and resolve link conflicts
        protected ConfigurationService m_configurationService;              // Configuration service
        protected LinkConfigurationLookupService m_linkConfigLookupService; // LinkConfig, such as mapped link type, lookup

        private HighWaterMark<DateTime> m_hwmLink;
        private CQRecordFilters m_filters;
        private ClearQuestOleServer.Session m_userSession;                  // user session; instantiated after InitializeClient()
        #region not need until context sync requires us to access schema info
        //private ClearQuestOleServer.AdminSession m_adminSession;            // admin session; may be NULL if login info is not provided in config file
        #endregion
        private ClearQuestMigrationContext m_migrationContext;

        private ErrorManager ErrorManager
        {
            get
            {
                ErrorManager errMgr = null;
                if (m_serviceContainer != null)
                {
                    errMgr = m_serviceContainer.GetService(typeof(ErrorManager)) as ErrorManager;
                }
                return errMgr;
            }
        }

        /// <summary>
        /// C'tor
        /// </summary>
        public ClearQuestLinkProvider()
        {
            m_supportedChangeActions = new List<Guid>();
            m_supportedLinkTypes = new Dictionary<string, LinkType>();
            m_artifactHandlers = new Collection<IArtifactHandler>();
        }

        /// <summary>
        /// Gets callback method for extracting links.
        /// </summary>
        protected ExtractLinkChangeActions ExtractLinkChangeActionsCallback { get; set; }

        /// <summary>
        /// Delegate function for extracting links from the given object.
        /// </summary>
        /// <param name="source">Source of links</param>
        /// <param name="linkChangeGroups"></param>
        public delegate void ExtractLinkChangeActions(ClearQuestOleServer.Session session, OAdEntity hostRecord, List<LinkChangeGroup> linkChangeGroups);

        #region IServiceProvider Members

        public object GetService(Type serviceType)
        {
            if (serviceType == typeof(ClearQuestMigrationContext))
            {
                return m_migrationContext;
            }

            return null;
        }

        #endregion

        #region ILinkProvider Members
        /// <summary>
        /// Gets link change actions supported by this provider
        /// </summary>
        public ICollection<Guid> SupportedChangeActions
        {
            get { return m_supportedChangeActions; }
        }

        /// <summary>
        /// Gets/Sets link change actions supported by the counterparty
        /// </summary>
        public ICollection<Guid> SupportedChangeActionsOther
        {
            get;
            set;
        }

        /// <summary>
        /// Gets link types supported by this provider
        /// </summary>
        public Dictionary<string, LinkType> SupportedLinkTypes
        {
            get { return m_supportedLinkTypes; }
        }

        public ICollection<string> SupportedLinkTypeReferenceNamesOther
        {
            get
            {
                return m_supportedLinkTypeReferenceNamesOther;
            }
            set
            {
                m_supportedLinkTypeReferenceNamesOther = value;
                Debug.Assert(null != m_supportedLinkTypeReferenceNamesOther,
                             "null == m_supportedLinkTypeReferenceNamesOther");

                foreach (var supportedLinkType in m_supportedLinkTypes)
                {
                    if (m_supportedLinkTypeReferenceNamesOther.Contains(supportedLinkType.Key))
                    {
                        continue;
                    }

                    // link config lookup service returns the mapped link type on otherside if there is a mapping
                    // or the unmapped link type on this side
                    string mappedLinkType = m_linkConfigLookupService.FindMappedLinkType(m_configurationService.SourceId, supportedLinkType.Key);
                    if (!m_linkTranslationService.LinkTypeSupportedByOtherSide(mappedLinkType))
                    {
                        ExtractLinkChangeActionsCallback -= ((ILinkHandler)supportedLinkType.Value).ExtractLinkChangeActions;
                    }
                }
            }
        }

        public void Initialize(ServiceContainer serviceContainer)
        {
            Debug.Assert(null != serviceContainer, "ServiceContainer is NULL");

            m_serviceContainer = serviceContainer;

            m_linkTranslationService = serviceContainer.GetService(typeof(ILinkTranslationService)) as ILinkTranslationService;
            Debug.Assert(null != m_linkTranslationService, "ILinkTranslationService has not been properly initialized");

            m_configurationService = serviceContainer.GetService(typeof(ConfigurationService)) as ConfigurationService;
            Debug.Assert(null != m_configurationService, "ConfigurationService has not been properly initialized");

            m_hwmLink = new HighWaterMark<DateTime>(ClearQuestConstants.CqLinkHwm);
            m_configurationService.RegisterHighWaterMarkWithSession(m_hwmLink);

            m_linkConfigLookupService = m_linkTranslationService.LinkConfigurationLookupService;

            m_conflictManager = serviceContainer.GetService(typeof(ConflictManager)) as ConflictManager;

            InitializeClient();

            RegisterArtifactHandlers();

            MigrationSource migrSrcConfig = m_configurationService.MigrationSource;
            Debug.Assert(null != migrSrcConfig, "cannot get MigrationSource config from Session");
            foreach (CustomSetting setting in migrSrcConfig.CustomSettings.CustomSetting)
            {
                if (setting.SettingKey.Equals(ClearQuestConstants.CqWebRecordUrlBaseSettingKey, StringComparison.OrdinalIgnoreCase))
                {
                    string urlFormat = setting.SettingValue;
                    var recordHyperLinkType = new ClearQuestWebRecordLinkType(urlFormat);
                    m_supportedLinkTypes.Add(recordHyperLinkType.ReferenceName, recordHyperLinkType);
                    ExtractLinkChangeActionsCallback += ((ILinkHandler)recordHyperLinkType).ExtractLinkChangeActions;
                    break;
                }
            }
        }

        public ReadOnlyCollection<LinkChangeGroup> GenerateNextLinkDeltaSlice(
            LinkService linkService,
            int maxDeltaSliceSize)
        {
            try
            {
                var linkChangeGroups = new List<LinkChangeGroup>();

                if (null == ExtractLinkChangeActionsCallback)
                {
                    return linkChangeGroups.AsReadOnly();
                }

                // load high watermark; as for CQ, we store local time for queries
                m_hwmLink.Reload();
                DateTime hwmDeltaValue = m_hwmLink.Value;
                if (hwmDeltaValue.Equals(default(DateTime)))
                {
                    hwmDeltaValue = new DateTime(1900, 1, 1);
                }
                hwmDeltaValue = hwmDeltaValue.AddSeconds(-1);           // go back 1 second as we'll drop the millisec below

                string hwmDeltaValueStr = hwmDeltaValue.ToString(m_migrationContext.CQQueryDateTimeFormat, CultureInfo.InvariantCulture);

                // record current time to update HWM after processing
                DateTime newHwmValue = CQUtilityMethods.GetTimeForNewHighWaterMark(m_migrationContext.CQTimeOffsetFromServerHistoryTimesInMinutes);

                // store to be used for analysis
                WorkItemLinkStore store = new WorkItemLinkStore(m_configurationService.SourceId);

                // extract links
                var inMaxDeltaSliceSize = maxDeltaSliceSize;
                foreach (CQRecordFilter filter in m_filters)
                {
                    CQRecordQueryBase recordQuery = CQRecordQueryFactory.CreateQuery(m_userSession, filter, hwmDeltaValueStr, this);
                    foreach (ClearQuestOleServer.OAdEntity record in recordQuery)
                    {
                        // HACK HACK
                        if (record == null)
                        {
                            continue;
                        }
                        // HACK HACK

                        string recDispName = CQWrapper.GetEntityDisplayName(record);

                        TraceManager.TraceInformation("Generating linking delta for CQ Record: {0}", recDispName);

                        var perWorkItemlinkChangeGroups = new List<LinkChangeGroup>();
                        ExtractLinkChangeActionsCallback(m_userSession, record, perWorkItemlinkChangeGroups);

                        if (perWorkItemlinkChangeGroups.Count == 0)
                        {
                            TraceManager.TraceInformation("Number of links: {0}", 0);
                            continue;
                        }

                        LinkChangeGroup consolidatedLinkChangeGroup = perWorkItemlinkChangeGroups[0];
                        for (int i = 1; i < perWorkItemlinkChangeGroups.Count; ++i)
                        {
                            foreach (LinkChangeAction action in perWorkItemlinkChangeGroups[i].Actions)
                            {
                                consolidatedLinkChangeGroup.AddChangeAction(action);
                            }
                        }
                        TraceManager.TraceInformation("Number of links: {0}", consolidatedLinkChangeGroup.Actions.Count.ToString());

                        // VERY IMPORTANT STEP: update the link delta to store
                        string hostRecMigrItemId = UtilityMethods.CreateCQRecordMigrationItemId(record);
                        store.UpdatePerItemLinkChangeGroupsByCheckingRelatedItemRecords(
                            hostRecMigrItemId, consolidatedLinkChangeGroup, this);

                        if (consolidatedLinkChangeGroup.Actions.Count > 0)
                        {
                            linkChangeGroups.Add(consolidatedLinkChangeGroup);
                        }
                        maxDeltaSliceSize -= consolidatedLinkChangeGroup.Actions.Count;

                        if (maxDeltaSliceSize <= 0)
                        {
                            // size limit reached - persist groups to DB, then empty the slice and process next slice
                            linkService.AddChangeGroups(linkChangeGroups);
                            linkChangeGroups.Clear();
                            maxDeltaSliceSize = inMaxDeltaSliceSize;
                        }
                    }
                }

                // persist remaining groups to DB
                linkService.AddChangeGroups(linkChangeGroups);

                // clean up the returned link change group collection
                // when the caller (toolkit) receives an empty collection, it understands there is no more
                // delta to generate for the moment, and proceeds to next phase
                linkChangeGroups.Clear();

                // update primary Highwater Mark
                m_hwmLink.Update(newHwmValue);
                TraceManager.TraceInformation("Persisted CQ linking HWM: {0}", ClearQuestConstants.CqLinkHwm);
                TraceManager.TraceInformation("Updated CQ linking HWM: {0}", newHwmValue.ToString());

                return linkChangeGroups.AsReadOnly();
            }
            catch (Exception exception)
            {
                // [teyang] TODO CONFLICT HANDLING

                //MigrationConflict genericeConflict = WitGeneralConflictType.CreateConflict(exception);
                //var conflictManager = m_conflictManager.GetService(typeof(ConflictManager)) as ConflictManager;
                //Debug.Assert(null != conflictManager);
                //List<MigrationAction> resolutionActions;
                //ConflictResolutionResult resolveRslt =
                //    conflictManager.TryResolveNewConflict(conflictManager.SourceId, genericeConflict, out resolutionActions);
                //Debug.Assert(!resolveRslt.Resolved);
                TraceManager.TraceException(exception);
                return new List<LinkChangeGroup>().AsReadOnly();
            }
        }

        public void SubmitLinkChange(LinkService linkService)
        {
            long firstChangeGroupId = 0;
            const LinkChangeGroup.LinkChangeGroupStatus status = LinkChangeGroup.LinkChangeGroupStatus.ReadyForMigration;

            while (true)
            {
                long lastChangeGroupId;
                ReadOnlyCollection<LinkChangeGroup> pagedChangeGroups = linkService.GetLinkChangeGroups(
                    firstChangeGroupId, 10000, status, false, out lastChangeGroupId);

                if (pagedChangeGroups.Count <= 0 || lastChangeGroupId < firstChangeGroupId) break;
                firstChangeGroupId = lastChangeGroupId + 1;

                foreach (LinkChangeGroup changeGroup in pagedChangeGroups)
                {
                    if (linkService.ChangeGroupIsCompleted(changeGroup))
                    {
                        changeGroup.Status = LinkChangeGroup.LinkChangeGroupStatus.Completed;
                    }
                    else if (linkService.AllLinkMigrationInstructionsAreConflicted(changeGroup))
                    {
                        changeGroup.IsConflicted = true;
                    }
                    else
                    {
                        LinkChangeGroup.LinkChangeGroupStatus statusCache = changeGroup.Status;

                        TraceManager.TraceInformation("Start migration link change group {0}", changeGroup.GroupName);
                        BatchSubmitLinkChange(changeGroup);
                        TraceManager.TraceInformation("Finish migration link change group {0}", changeGroup.GroupName);

                        // if the change group contains the two special skip change actions
                        // we leave the group status untouched but update the action status changes, if any
                        if (linkService.ContainsSpecialSkipActions(changeGroup))
                        {
                            changeGroup.Status = statusCache;
                        }
                        else if (linkService.AllLinkMigrationInstructionsAreConflicted(changeGroup))
                        {
                            changeGroup.IsConflicted = true;
                        }
                        else if (linkService.ChangeGroupIsCompleted(changeGroup))
                        {
                            changeGroup.Status = LinkChangeGroup.LinkChangeGroupStatus.Completed;
                        }
                    }
                    linkService.SaveChangeGroupActionStatus(changeGroup);
                }
            }
        }

        public void BatchSubmitLinkChange(LinkChangeGroup linkChanges)
        {
            if (linkChanges.Actions.Count == 0)
            {
                linkChanges.Status = LinkChangeGroup.LinkChangeGroupStatus.Completed;
                return;
            }

            // group changes by work item Id
            Dictionary<string, List<LinkChangeAction>> perRecordLinkChanges = RegroupLinkChangeActions(linkChanges);

            WorkItemLinkStore relatedArtifactsStore = new WorkItemLinkStore(m_configurationService.SourceId);

            // batch-submit links of each cq record
            bool successForAllActions = true;
            foreach (var perWorkItemLinkChange in perRecordLinkChanges)
            {
                string[] identity = UtilityMethods.ParseCQRecordMigrationItemId(perWorkItemLinkChange.Key);
                OAdEntity hostEntity = CQWrapper.GetEntity(m_userSession, identity[0], identity[1]);

                foreach (LinkChangeAction linkChangeAction in perWorkItemLinkChange.Value)
                {
                    if (linkChangeAction.Status != LinkChangeAction.LinkChangeActionStatus.ReadyForMigration
                        || linkChangeAction.IsConflicted)
                    {
                        continue;
                    }

                    var handler = linkChangeAction.Link.LinkType as ILinkHandler;
                    Debug.Assert(null != handler, "linktype is not an ILinkHandler");
                    if (!handler.Update(m_migrationContext, m_userSession, hostEntity, linkChangeAction))
                    {
                        successForAllActions = false;
                        // [teyang] todo conflict handling
                        linkChangeAction.Status = LinkChangeAction.LinkChangeActionStatus.Completed;
                        linkChangeAction.IsConflicted = true;
                        TraceManager.TraceError("Failed processing link change action: {0} linked to {1}",
                                                linkChangeAction.Link.SourceArtifact.Uri,
                                                linkChangeAction.Link.TargetArtifact.Uri);
                    }
                    else
                    {
                        MarkLinkChangeActionCompleted(linkChangeAction, relatedArtifactsStore);
                    }
                }
            }

            linkChanges.Status = successForAllActions
                                 ? LinkChangeGroup.LinkChangeGroupStatus.Completed
                                 : LinkChangeGroup.LinkChangeGroupStatus.ReadyForMigration;
        }

        public bool TryGetArtifactById(
            string artifactTypeReferenceName,
            string id,
            out IArtifact artifact)
        {
            artifact = null;

            if (string.IsNullOrEmpty(id))
            {
                return false;
            }

            if (string.IsNullOrEmpty(artifactTypeReferenceName))
            {
                return false;
            }

            ArtifactType artifactType;
            bool succeeded = TryGetArtifactType(artifactTypeReferenceName, out artifactType);
            if (!succeeded)
            {
                return false;
            }
            Debug.Assert(null != artifactType, "null == artifactType");

            foreach (IArtifactHandler artifactHandler in m_artifactHandlers)
            {
                succeeded = artifactHandler.TryCreateArtifactFromId(artifactType, id, out artifact);
                if (succeeded)
                {
                    break;
                }
            }
            return succeeded;
        }

        public void RegisterSupportedLinkOperations()
        {
            m_supportedChangeActions.Add(WellKnownChangeActionId.Add);
            m_supportedChangeActions.Add(WellKnownChangeActionId.Delete);
        }

        public void RegisterSupportedLinkTypes()
        {
            // register duplicate record link type
            LinkType linkType = new ClearQuestDuplicateRecordLinkType();
            m_supportedLinkTypes.Add(linkType.ReferenceName, linkType);
            ExtractLinkChangeActionsCallback += ((ILinkHandler)linkType).ExtractLinkChangeActions;

            // register per record-type reference field & reference-list field links
            foreach (CQRecordFilter filter in m_filters)
            {
                List<LinkType> linkTypes = ClearQuestReferenceFieldLinkTypeBase.ExtractSupportedLinkTypes(
                                                m_userSession,
                                                filter.RecordType);
                foreach (LinkType lType in linkTypes)
                {
                    if (!m_supportedLinkTypes.ContainsKey(lType.ReferenceName))
                    {
                        m_supportedLinkTypes.Add(lType.ReferenceName, lType);
                        ExtractLinkChangeActionsCallback += ((ILinkHandler)lType).ExtractLinkChangeActions;
                    }
                }

                linkTypes = ClearQuestReferenceListFieldLinkTypeBase.ExtractSupportedLinkTypes(
                                m_userSession,
                                filter.RecordType);
                foreach (LinkType lType in linkTypes)
                {
                    if (!m_supportedLinkTypes.ContainsKey(lType.ReferenceName))
                    {
                        m_supportedLinkTypes.Add(lType.ReferenceName, lType);
                        ExtractLinkChangeActionsCallback += ((ILinkHandler)lType).ExtractLinkChangeActions;
                    }
                }
            }

            // register CQ-CC integration link types
        }

        public void RegisterConflictTypes(ConflictManager conflictManager, Guid sourceId)
        {
            if (conflictManager == null)
            {
                throw new ArgumentNullException("conflictManager");
            }
            m_conflictManager = conflictManager;

            m_conflictManager.RegisterConflictType(new GenericConflictType());

            m_conflictManager.RegisterConflictType(sourceId, new ClearQuestGenericConflictType(),
                                                          SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSessionCurrentTrip);

            m_conflictManager.RegisterConflictType(sourceId, new ClearQuestMissingCQDllConflictType(),
                                                          SyncOrchestrator.ConflictsSyncOrchOptions.StopConflictedSession);
        }

        public void Analyze(
            LinkService linkService,
            Guid sessionId,
            Guid sourceId)
        {
            return;
        }

        public bool TryExtractArtifactId(
            IArtifact artifact,
            out string id)
        {
            id = string.Empty;
            bool succeeded = false;

            if (null != artifact)
            {
                foreach (IArtifactHandler artifactHandler in m_artifactHandlers)
                {
                    succeeded = artifactHandler.TryExtractArtifactId(artifact, out id);
                    if (succeeded)
                    {
                        break;
                    }
                }
            }

            return succeeded;
        }

        public bool TryGetVersionControlledArtifactDetails(
            IArtifact artifact,
            out string path,
            out string changeId)
        {
            throw new NotImplementedException();
        }

        public string GetVersionControlledArtifactUri(string path, string changeId)
        {
            throw new NotImplementedException();
        }

        public List<ILink> GetLinks(
            IArtifact sourceArtifact,
            LinkType linkType)
        {
            string id;
            bool idExtractionRslt = TryExtractArtifactId(sourceArtifact, out id);
            Debug.Assert(idExtractionRslt);

            string[] identity = UtilityMethods.ParseCQRecordMigrationItemId(id);
            OAdEntity hostEntity = CQWrapper.GetEntity(m_userSession, identity[0], identity[1]);

            var links = new List<ILink>();

            if (null == ExtractLinkChangeActionsCallback)
            {
                return links;
            }

            var perWorkItemlinkChangeGroups = new List<LinkChangeGroup>();
            ExtractLinkChangeActionsCallback(m_userSession, hostEntity, perWorkItemlinkChangeGroups);

            foreach (LinkChangeGroup group in perWorkItemlinkChangeGroups)
            {
                foreach (LinkChangeAction action in group.Actions)
                {
                    if (!CQStringComparer.LinkType.Equals(action.Link.LinkType.ReferenceName, linkType.ReferenceName))
                    {
                        continue;
                    }

                    string mappedLinkType = m_linkConfigLookupService.FindMappedLinkType(m_configurationService.SourceId, action.Link.LinkType.ReferenceName);
                    if (!m_linkTranslationService.LinkTypeSupportedByOtherSide(mappedLinkType))
                    {
                        continue;
                    }

                    if (!links.Contains(action.Link))
                    {
                        links.Add(action.Link);
                    }
                }
            }

            return links;
        }

        public NonCyclicReferenceClosure CreateNonCyclicLinkReferenceClosure(
            LinkType linkType,
            IArtifact artifact)
        {
            throw new NotImplementedException();
        }

        public bool TryGetSingleParentLinkSourceArtifacts(
            LinkType linkType,
            IArtifact artifact,
            out IArtifact[] parentArtifacts)
        {
            parentArtifacts = new IArtifact[0];
            return true;
        }

        #endregion
        private ClearQuestConnectionConfig UserSessionConnConfig
        {
            get;
            set;
        }

        private ClearQuestConnectionConfig AdminSessionConnConfig
        {
            get;
            set;
        }

        private void RegisterArtifactHandlers()
        {
            m_artifactHandlers.Add(new ClearQuestRecordArtifactHandler());
            m_artifactHandlers.Add(new ClearQuestWebRecordHyperLinkArtifactHandler());
        }

        private void InitializeClient()
        {
            InitializeCQClient();
        }

        private void InitializeCQClient()
        {
            MigrationSource migrationSourceConfig = m_configurationService.MigrationSource;
            string dbSet = migrationSourceConfig.ServerUrl;
            string userDb = migrationSourceConfig.SourceIdentifier;

            ICredentialManagementService credManagementService =
                m_serviceContainer.GetService(typeof(ICredentialManagementService)) as ICredentialManagementService;

            ICQLoginCredentialManager loginCredManager =
                CQLoginCredentialManagerFactory.CreateCredentialManager(credManagementService, migrationSourceConfig);

            // connect to user session
            UserSessionConnConfig = new ClearQuestConnectionConfig(loginCredManager.UserName,
                                                           loginCredManager.Password,
                                                           userDb,
                                                           dbSet);
            m_userSession = CQConnectionFactory.GetUserSession(UserSessionConnConfig);

            #region admin session is not needed until we sync context
            //// connect to admin session
            //if (!string.IsNullOrEmpty(loginCredManager.AdminUserName))
            //{
            //    AdminSessionConnConfig = new ClearQuestConnectionConfig(loginCredManager.AdminUserName,
            //                                                                loginCredManager.AdminPassword ?? string.Empty,
            //                                                                userDb,
            //                                                                dbSet);
            //    m_adminSession = CQConnectionFactory.GetAdminSession(AdminSessionConnConfig);
            //}
            #endregion

            // parse the filter strings in the configuration file
            m_filters = new CQRecordFilters(m_configurationService.Filters, m_userSession);

            m_migrationContext = new ClearQuestMigrationContext(m_userSession, migrationSourceConfig);
        }

        private void MarkLinkChangeActionCompleted(LinkChangeAction action, WorkItemLinkStore relatedArtifactsStore)
        {
            if (action.Status == LinkChangeAction.LinkChangeActionStatus.ReadyForMigration)
            {
                action.Status = LinkChangeAction.LinkChangeActionStatus.Completed;
            }

            var actions = new List<LinkChangeAction>();
            actions.Add(action);
            relatedArtifactsStore.UpdateSyncedLinks(actions);
        }

        private Dictionary<string, List<LinkChangeAction>> RegroupLinkChangeActions(LinkChangeGroup linkChanges)
        {
            Dictionary<string, List<LinkChangeAction>> retVal = new Dictionary<string, List<LinkChangeAction>>();

            foreach (LinkChangeAction action in linkChanges.Actions)
            {
                if (!retVal.ContainsKey(action.Link.SourceArtifactId))
                {
                    retVal.Add(action.Link.SourceArtifactId, new List<LinkChangeAction>());
                }

                if (!retVal[action.Link.SourceArtifactId].Contains(action))
                {
                    retVal[action.Link.SourceArtifactId].Add(action);
                }
            }

            return retVal;
        }

        private bool TryGetArtifactType(string artifactTypeReferenceName, out ArtifactType artifactType)
        {
            artifactType = null;

            if (string.IsNullOrEmpty(artifactTypeReferenceName))
            {
                return false;
            }

            bool succeeded = false;
            foreach (var supportedLinkType in m_supportedLinkTypes)
            {
                if (CQStringComparer.LinkArtifactType.Equals(supportedLinkType.Value.SourceArtifactType.ReferenceName,
                                                             artifactTypeReferenceName))
                {
                    succeeded = true;
                    artifactType = supportedLinkType.Value.SourceArtifactType;
                    break;
                }

                if (CQStringComparer.LinkArtifactType.Equals(supportedLinkType.Value.TargetArtifactType.ReferenceName,
                                                             artifactTypeReferenceName))
                {
                    succeeded = true;
                    artifactType = supportedLinkType.Value.TargetArtifactType;
                    break;
                }
            }

            return succeeded;
        }
    }
}


text:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true');
//$json=$_GET ['json'];
require('db_config.php');
date_default_timezone_set('Asia/Kolkata');

$json = file_get_contents('php://input');
$obj = json_decode($json, true);
date_default_timezone_set('Asia/Kolkata');

	try
		{
			if($obj['api_key'] != "5+`C%@>9RvJ'y?8:"){
				$response['ResponseCode'] = "400";
		    $response['ResponseMessage'] = "Invalid api_key"; //user friendly message
		    $status['Status'] = $response;
		    header('Content-type: application/json');
		    echo json_encode($status);
				die();
			}
			$datetime2 = new DateTime($obj['DOB']);
			$datetime2 = $datetime2->format('Y-m-d');
            $result = $db->prepare("UPDATE patientprofile SET Height = :Height, Weight = :Weight, BloodGroup = :BloodGroup,  Address1 = :Address1, Address2 = :Address2, City = :City, PinCode = :PinCode, Allergies = :Allergies, Hereditory = :Hereditory where PID = :UserID");
			$result->bindParam(':UserID', $obj['UserID'], PDO::PARAM_INT);
			$result->bindParam(':Height', $obj['Height'], PDO::PARAM_STR);
			$result->bindParam(':Weight', $obj['Weight'], PDO::PARAM_STR);
			$result->bindParam(':BloodGroup', $obj['BloodGroup'], PDO::PARAM_STR);
			$result->bindParam(':Address1', $obj['Address1'], PDO::PARAM_STR);
			$result->bindParam(':Address2', $obj['Address2'], PDO::PARAM_STR);
			$result->bindParam(':City', $obj['City'], PDO::PARAM_STR);
	        $result->bindParam(':PinCode', $obj['PinCode'], PDO::PARAM_INT);
	        $result->bindParam(':Allergies', $obj['Allergies'], PDO::PARAM_STR);
	        $result->bindParam(':Hereditory', $obj['Hereditory'], PDO::PARAM_STR);
			$result->execute();

			$result2 = $db->prepare("UPDATE user SET FName = :FName, LName = :LName, Email = :Email, Pic = :Pic, DOB = :DOB, Gender = :Gender where UserID = :UserID");
			$result2->bindParam(':UserID', $obj['UserID'], PDO::PARAM_INT);
			$result2->bindParam(':Pic', $obj['Pic'], PDO::PARAM_STR);
			$result2->bindParam(':DOB', $datetime2, PDO::PARAM_STR);
			$result2->bindParam(':FName', $obj['FName'], PDO::PARAM_STR);
			$result2->bindParam(':Gender', $obj['Gender'], PDO::PARAM_INT);
			$result2->bindParam(':LName', $obj['LName'], PDO::PARAM_STR);
                        $result2->bindParam(':Email', $obj['Email'], PDO::PARAM_STR);
			$result2->execute();

			$response['ResponseMessage'] = "Info Updated Successfully";
			$response['ResponseCode'] = "200";
			  $status['Status'] = $response;
			  header('Content-type: application/json');
			  echo json_encode($status);
		}
	catch(PDOException $ex)
		{
			$response['ResponseCode'] = "500";
		    $response['ResponseMessage'] = "An Error occured!" . $ex; //user friendly message
		    $status['Status'] = $response;
		    header('Content-type: application/json');
			echo json_encode($status);
		}


text:
/*
Theme Name:         KFriedgen Theme Based on Sage
Theme URI:          https://www.katharinefriedgen.com
Description:        KFriedgen is a new theme based on Sage.
Version:            0.0.2
Author:             Katharine Friedgen
Author URI:         https://www.katharinefriedgen.com
Text Domain:        kfriedgen

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/


text:
    <component class="m-steppers-item__button"
               :is="componentToShow"
               :to="propUrl"
               :tabindex="isTabIndex"
               :role="role"
               :aria-selected="isInProgress"
               @keyup.enter="onClick"
               @click="onClick">

            <m-icon :name="iconName"
                    :svg-title="iconTitle"></m-icon>
            <m-icon class="m-steppers-item__icon-completed"
                    v-if="completed"
                    name="m-svg__completed-filled"></m-icon>

            <slot></slot>

    </component>


text:
import onClick from './onClick'

export default {
  onClick
}


text:
package cz.yetanotherview.webcamviewer.app.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import cz.yetanotherview.webcamviewer.app.R;

public class SpinnerAdapter extends ArrayAdapter<String> {

    private Activity activity;
    private String[] objects;
    private int[] icons = {R.drawable.ic_action_device_usb,
            R.drawable.ic_action_description};

    public SpinnerAdapter(Activity activity, int textViewResourceId,
                           String[] objects) {
        super(activity, textViewResourceId, objects);
        this.activity = activity;
        this.objects = objects;
    }

    @Override
    public View getDropDownView(int position, View convertView,
                                ViewGroup parent) {
        return getCustomView(position, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, parent);
    }

    private View getCustomView(int position, ViewGroup parent) {
        LayoutInflater inflater = activity.getLayoutInflater();
        View row = inflater.inflate(R.layout.spinner_item, parent, false);
        TextView label = (TextView)row.findViewById(R.id.spinner_text);
        label.setText(objects[position]);

        ImageView icon = (ImageView)row.findViewById(R.id.spinner_icon);
        icon.setImageResource(icons[position]);

        return row;
    }
}


text:
/*
 * MediaMonkey Project
 * Licenced under Apache license 2.0. Read LICENSE for details.
 */
package com.fj.android.mediamonkey.dao.sharedpref;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.fj.android.mediamonkey.R;
import com.fj.android.mediamonkey.util.IntDefUtils;
import com.fj.android.mediamonkey.util.ResourceUtils;
import com.mediamonkey.android.lib.annotation.ContentDisplayType;

/**
 * @author Francesco Jo(nimbusob@gmail.com)
 * @since 23 - Nov - 2016
 */
public class AppConfigPref {
    private SharedPreferences pref;
    private static final String KEY_LAST_USED_PLUGIN_PKG = "kLastUsedPluginPkg";
    private static final String KEY_DB_CREATED           = "kDbCreated:";

    public AppConfigPref(final Context context) {
        this.pref = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public String getLastUsedPluginPackage() {
        return pref.getString(KEY_LAST_USED_PLUGIN_PKG, "");
    }

    public void setLastUsedPluginPackage(String packageName) {
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(KEY_LAST_USED_PLUGIN_PKG, packageName);
        editor.apply();
    }

    public boolean isDatabaseCreated(String dbName) {
        return pref.getBoolean(KEY_DB_CREATED + dbName, false);
    }

    public void setDatabaseCreated(String dbName) {
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean(KEY_DB_CREATED + dbName, true);
        editor.apply();
    }

    public @ContentDisplayType int getViewerMode() {
        String keyName = ResourceUtils.getString(R.string.pref_key_viewer_mode);
        return IntDefUtils.Str2ContentDisplayType(pref.getString(keyName, "0"), ContentDisplayType.VERTICAL);
    }
}


text:
// @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com>
// @copyright 2014 Copernica BV
//
// @copyright 2017-2018 zzu_softboy <zzu_softboy@163.com>
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Created by softboy on 18/05/2017.
//

#ifndef ZAPI_LANG_EXTENSION_H
#define ZAPI_LANG_EXTENSION_H

#include "zapi/Global.h"
#include "zapi/lang/Argument.h"
#include "zapi/lang/Interface.h"
#include "zapi/vm/InvokeBridge.h"
#include "zapi/vm/AbstractClass.h"
#include "zapi/lang/internal/ExtensionPrivate.h"

#include <list>

// forware declare with namespace
namespace zapi
{
namespace ds
{
class Variant;
} // ds

namespace lang
{
class Parameters;
class Constant;
class Namespace;
class Ini;
template <typename> class Class;
} // lang
} // zapi
// end forware declare

namespace zapi
{
namespace lang
{

using zapi::ds::Variant;
using zapi::lang::Parameters;
using zapi::lang::Arguments;
using zapi::lang::Constant;
using zapi::lang::Class;
using zapi::lang::Interface;
using zapi::lang::Namespace;
using zapi::lang::Ini;
using internal::ExtensionPrivate;
using zapi::vm::AbstractClass;

class ZAPI_DECL_EXPORT Extension
{
public:
  /**
   * Constructor that defines a number of functions right away
   *
   * The first two parameters should be filled by the extension programmer with the
   * name of the extension, and the version number of the extension (like "1.0").
   * The third parameter, apiversion, does not have to be supplied and is best kept
   * to the default value. This third parameter checks whether the PHP-CPP version
   * that is currently installed on the server is the same as the PHP-CPP version
   * that was used to compile the extension with.
   *
   * @param  name        Extension name
   * @param  version     Extension version string
   * @param  apiversion  ZAPI API version (this should always be ZAPI_API_VERSION, so you better not supply it)
   */
   Extension(const char *name, const char *version = "1.0", int apiVersion = ZAPI_API_VERSION);
   Extension(const Extension &extension) = delete;
   Extension(Extension &&extension) = delete;
   virtual ~Extension();
public:
   template <typename T, typename std::decay<T>::type callable>
   Extension &registerFunction(const char *name, const Arguments &args = {});

   Extension &registerIni(const Ini &entry);
   Extension &registerIni(Ini &&entry);

   template <typename T>
   Extension &registerClass(const Class<T> &nativeClass);
   template <typename T>
   Extension &registerClass(Class<T> &&nativeClass);

   Extension &registerInterface(const Interface &interface);
   Extension &registerInterface(Interface &&interface);

   Extension &registerNamespace(const Namespace &ns);
   Extension &registerNamespace(Namespace &&ns);

   Extension &registerConstant(Constant &&constant);
   Extension &registerConstant(const Constant &constant);

   Namespace *findNamespace(const std::string &ns) const;
   AbstractClass *findClass(const std::string &clsName) const;

   size_t getIniQuantity() const;
   size_t getFunctionQuantity() const;
   size_t getConstantQuantity() const;
   size_t getNamespaceQuantity() const;
   operator void * ()
   {
      return getModule();
   }

  /**
   * Register a function to be called when the PHP engine is ready
   *
   * The callback will be called after all extensions are loaded, and all
   * functions and classes are available, but before the first pageview/request
   * is handled. You can register this callback if you want to be notified
   * when the engine is ready, for example to initialize certain things.
   *
   * @param Callback callback Function to be called
   * @return Extension Same object to allow chaining
   */
   Extension &setStartupHandler(const Callback &callback);

  /**
   * Register a function to be called when the PHP engine is going to stop
   *
   * The callback will be called right before the process is going to stop.
   * You can register a function if you want to clean up certain things.
   *
   * @param callback Function to be called
   * @return Extension Same object to allow chaining
   */
   Extension &setShutdownHandler(const Callback &callback);

  /**
   * Register a callback that is called at the beginning of each pageview/request
   *
   * You can register a callback if you want to initialize certain things
   * at the beginning of each request. Remember that the extension can handle
   * multiple requests after each other, and you may want to set back certain
   * global variables to their initial variables in front of each request
   *
   * @param Callback callback Function to be called
   * @return Extension Same object to allow chaining
   */
   Extension &setRequestStartupHandler(const Callback &callback);

  /**
   * Register a callback that is called to cleanup things after a pageview/request
   *
   * The callback will be called after _each_ request, so that you can clean up
   * certain things and make your extension ready to handle the next request.
   * This method is called onIdle because the extension is idle in between
   * requests.
   *
   * @param Callback callback Function to be called
   * @return Extension Same object to allow chaining
   */
   Extension &setRequestShutdownHandler(const Callback &callback);

   Extension &setInfoHandler(const Callback &callback);

  /**
   * Retrieve the module pointer
   *
   * This is the memory address that should be exported by the get_module()
   * function.
   *
   * @return void*
   */
   void *getModule();
   const void *getModule() const;
   const char *getName() const;
   const char *getVersion() const;
protected:
   Extension &registerFunction(const char *name, zapi::ZendCallable function, const Arguments &args);
   bool isLocked() const;
private:
   bool initialize(int moduleNumber);
private:
   ZAPI_DECLARE_PRIVATE(Extension)
  /**
   * The implementation object
   *
   * @var std::unique_ptr<ExtensionPrivate> m_implPtr
   */
   std::unique_ptr<internal::ExtensionPrivate> m_implPtr;
};

template <typename T>
Extension &Extension::registerClass(const Class<T> &nativeClass)
{
   ZAPI_D(Extension);
   if (implPtr->m_locked) {
      return *this;
   }
   // just shadow copy
   implPtr->m_classes.push_back(std::shared_ptr<AbstractClass>(new Class<T>(nativeClass)));
   return *this;
}

template <typename T>
Extension &Extension::registerClass(Class<T> &&nativeClass)
{
   ZAPI_D(Extension);
   if (implPtr->m_locked) {
      return *this;
   }
   implPtr->m_classes.push_back(std::shared_ptr<AbstractClass>(new Class<T>(std::move(nativeClass))));
   return *this;
}

template <typename T, typename std::decay<T>::type callable>
Extension &Extension::registerFunction(const char *name, const Arguments &args)
{
   return registerFunction(name, &zapi::vm::InvokeBridge<T, callable>::invoke, args);
}

} // lang
} // zapi

#endif // ZAPI_LANG_EXTENSION_H


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Chunk I/O
 *  =========
 *  Copyright 2018 Eduardo Silva <eduardo@monkey.io>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef CIO_UTILS_H
#define CIO_UTILS_H

#include <chunkio/cio_info.h>

#ifdef CIO_HAVE_GETPAGESIZE
int cio_getpagesize();
#endif

int cio_utils_recursive_delete(const char *dir);
int cio_utils_read_file(const char *path, char **buf, size_t *size);

#endif


text:
using System.Collections.Generic;

namespace Humanizer.Localisation.NumberToWords.Romanian
{
    internal class RomanianOrdinalNumberConverter
    {
        /// <summary>
        /// Lookup table converting units number to text. Index 1 for 1, index 2 for 2, up to index 9.
        /// </summary>
        private readonly Dictionary<int, string> _ordinalsUnder10 = new Dictionary<int, string>
            {
                {1, "primul|prima"},
                {2, "doilea|doua"},
                {3, "treilea|treia"},
                {4, "patrulea|patra"},
                {5, "cincilea|cincea"},
                {6, "șaselea|șasea"},
                {7, "șaptelea|șaptea"},
                {8, "optulea|opta"},
                {9, "nouălea|noua"},
            };

        private readonly string _femininePrefix = "a";
        private readonly string _masculinePrefix = "al";
        private readonly string _feminineSuffix = "a";
        private readonly string _masculineSuffix = "lea";

        public string Convert(int number, GrammaticalGender gender)
        {
            // it's easier to treat zero as a completely distinct case
            if (number == 0)
            {
                return "zero";
            }
            else if (number == 1)
            {
                // no prefixes for primul/prima
                return this.getPartByGender(_ordinalsUnder10[number], gender);
            }
            else if (number <= 9)
            {
                // units ordinals, 2 to 9, are totally different than the rest: treat them as a distinct case
                return string.Format("{0} {1}",
                                        gender == GrammaticalGender.Feminine ? _femininePrefix : _masculinePrefix,
                                        this.getPartByGender(_ordinalsUnder10[number], gender)
                                     );
            }
            else
            {
                var coverter = new RomanianCardinalNumberConverter();
                var words = coverter.Convert(number, gender);

                // remove 'de' preposition
                words = words.Replace(" de ", " ");

                if ((gender == GrammaticalGender.Feminine) && words.EndsWith("zeci"))
                {
                    words = words.Substring(0, words.Length - 4) + "zece";
                }
                else if ((gender == GrammaticalGender.Feminine) && words.Contains("zeci") && (words.Contains("milioane") || words.Contains("miliarde")))
                {
                    words = words.Replace("zeci", "zecea");
                }

                if ((gender == GrammaticalGender.Feminine) && words.StartsWith("un "))
                {
                    words = words.Substring(2).TrimStart();
                }

                if (words.EndsWith("milioane"))
                {
                    if (gender == GrammaticalGender.Feminine)
                    {
                        words = words.Substring(0, words.Length - 8) + "milioana";
                    }
                }

                var customMasculineSuffix = _masculineSuffix;
                if (words.EndsWith("milion"))
                {
                    if (gender == GrammaticalGender.Feminine)
                    {
                        words = words.Substring(0, words.Length - 6) + "milioana";
                    }
                    else
                    {
                        customMasculineSuffix = "u" + _masculineSuffix;
                    }
                }
                else if (words.EndsWith("miliard"))
                {
                    if (gender == GrammaticalGender.Masculine)
                    {
                        customMasculineSuffix = "u" + _masculineSuffix;
                    }
                }

                // trim last letter
                if ((gender == GrammaticalGender.Feminine) && (!words.EndsWith("zece") &&
                                                               (words.EndsWith("a") ||
                                                               words.EndsWith("ă") ||
                                                               words.EndsWith("e") ||
                                                               words.EndsWith("i"))))
                {
                    words = words.Substring(0, words.Length - 1);
                }

                return string.Format("{0} {1}{2}",
                                        gender == GrammaticalGender.Feminine ? _femininePrefix : _masculinePrefix,
                                        words,
                                        gender == GrammaticalGender.Feminine ? _feminineSuffix : customMasculineSuffix
                                    );
            }
        }

        private string getPartByGender(string multiGenderPart, GrammaticalGender gender)
        {
            if (multiGenderPart.Contains("|"))
            {
                var parts = multiGenderPart.Split('|');
                if (gender == GrammaticalGender.Feminine)
                {
                    return parts[1];
                }
                else
                {
                    return parts[0];
                }
            }
            else
            {
                return multiGenderPart;
            }
        }
    }
}


text:
package com.toolazydogs.jr4me.server.model;

import java.util.Map;

/**
 *
 */
public class CallParamMap extends CallParam
{
    private Map<String, Object> params;

    public Map<String, Object> getParams()
    {
        return params;
    }

    public void setParams(Map<String, Object> params)
    {
        this.params = params;
    }
}


text:
---
layout: post
---
This is part 3 of a series.  You can find [part one here]({% post_url 2005-07-11-marshaling-nested-data-structures-part-1 %}).  Please refer to that article for all of the Native definitions of the structures that I use here.

In part 2 of this series I demonstrated how you can Marshal nested data structures by flattening an array of structures into it's individual elements.  Using this is very awkward and is only practical when the size of your array is small.  This installment will get around these limitations with a bit of Marshalling help.  We'll get back indexing and remove the awkward flattening.

Once again, don't forget that the only 2 things that matter when Marshalling data

  1. Byte Size
  2. Byte Layout

When an array of structures are declared as a member of a struct, in the same manner as the Course structure, the data is inlined after the first two ints.  We can get this data to Marshall properly by inserting a structure with the same size as the array of Students.  The Native Student Structure is 52 bytes so we need a 260 byte structure.  The following will do.

``` csharp
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Size = 260 )]
public struct ArrayBlob
{
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Course
{
    public int Id;
    public int Count;
    public ArrayBlob Blob;

    /* ... Methods ... */
}
```

This structure meets all of our requirments.  Course is now properly formatted and can be Marshalled back and forth successfully.  However our student array is stuck in a chunk of data that has no access methods.  This blob is just an array of students in memory.  Getting the Students out in C would be a snap.  We could just grab the address, cast it the the appropriate pointer and run away with the Student elements.

``` c++
Student *elements = (Student*)(&(myCourse.Blob);
```

Unfortunately I'm giving these examples in Safe code so this is not allowed.  You can get the same effect with C# although it's a bit slower and forces a memory allocation. We implement this as in indexer into the Course struct.

``` csharp
public Student this[int index]
{
    get
    {
        if ( index >= Count )
        {
            throw new ArgumentOutOfRangeException();
        }

        IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(ArrayBlob)));
        try
        {
            Marshal.StructureToPtr(this.Blob, ptr, false);
            int offset = index * Marshal.SizeOf(typeof(Student));
            IntPtr structPtr = new IntPtr(ptr.ToInt32() + offset);
            return (Student)Marshal.PtrToStructure(structPtr, typeof(Student));
        }
        finally
        {
            Marshal.FreeHGlobal(ptr);
        }
    }
}
```

Some error checking was removed for brevity sake.  Granted this is still a suboptimal way of accessing the members of the structure.  Every index requires an allocation.  But if you only interop for brief times and in non perf sensitive areas this code will do just fine.  Here's an example.

``` csharp
public static class Enrollment
{
    [DllImport("Enrollment.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr CreateStudent(
        [MarshalAs(UnmanagedType.LPWStr)] String firstName,
        [MarshalAs(UnmanagedType.LPWStr)] String lastName,
        int bDay,
        int bMon,
        int bYear);

    [DllImport("Enrollment.dll", CharSet = CharSet.Unicode)]
    public static extern void UpdateStudentInfo(
        [MarshalAs(UnmanagedType.LPWStr)] String firstName,
        [MarshalAs(UnmanagedType.LPWStr)] String lastName,
        int bDay,
        int bMon,
        int bYear,
        ref Student student);

    [DllImport("Enrollment.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr GetCourseInfo(int id);
}

class MarshalFun
{
    static void Main(string[] args)
    {
        IntPtr ptr = Enrollment.GetCourseInfo(42);
        Course course = (Course)Marshal.PtrToStructure(ptr, typeof(Course));

        Student first = course[0];
        Student second = course[1];
    }
}
```

This code assumes that at least 2 students were returned from GetCourseInfo().  This code is much cleaner than the previous example.  It will also work with very large sized arrays.  However it does have undue perf and memory overhead.  Next time we'll look at a way to have the clean code and remove all of the perf problems present in the current code.

This posting is provided "AS IS" with no warranties, and confers no rights.  Use of included script samples are subject to the terms specified at **<http://www.microsoft.com/info/cpyright.htm>**.


text:
<?php

namespace Riak\Client\Core\Transport;

use Riak\Client\Core\Message\Request;

/**
 * Riak adapter strategy.
 *
 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
 */
interface Strategy
{
    /**
     * @param \Riak\Client\Core\Message\Request $request
     *
     * @return \Riak\Client\Core\Message\Response
     */
    public function send(Request $request);
}


text:
package org.eclipse.emf.cdo.internal.common.model;

import java.io.IOException;
import java.text.MessageFormat;

import org.eclipse.emf.cdo.common.model.CDOModelUtil;
import org.eclipse.emf.cdo.common.model.CDOPackageInfo;
import org.eclipse.emf.cdo.common.protocol.CDODataInput;
import org.eclipse.emf.cdo.common.protocol.CDODataOutput;
import org.eclipse.emf.cdo.internal.common.bundle.OM;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry;
import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EFactory;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.net4j.util.om.trace.ContextTracer;

/**
 * @author Eike Stepper
 */
public class CDOPackageInfoImpl implements InternalCDOPackageInfo
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CDOPackageInfoImpl.class);

  private InternalCDOPackageUnit packageUnit;

  private String packageURI;

  private String parentURI;

  private EPackage ePackage;

  public CDOPackageInfoImpl()
  {
  }

  public InternalCDOPackageUnit getPackageUnit()
  {
    return packageUnit;
  }

  public void setPackageUnit(InternalCDOPackageUnit packageUnit)
  {
    this.packageUnit = packageUnit;
  }

  public String getPackageURI()
  {
    return packageURI;
  }

  public void setPackageURI(String packageURI)
  {
    this.packageURI = packageURI;
  }

  public String getParentURI()
  {
    return parentURI;
  }

  public void setParentURI(String parentURI)
  {
    this.parentURI = parentURI;
  }

  public void write(CDODataOutput out) throws IOException
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("Writing {0}", this); //$NON-NLS-1$
    }

    out.writeCDOPackageURI(packageURI);
    out.writeCDOPackageURI(parentURI);
  }

  public void read(CDODataInput in) throws IOException
  {
    packageURI = in.readCDOPackageURI();
    parentURI = in.readCDOPackageURI();
    if (TRACER.isEnabled())
    {
      TRACER.format("Read {0}", this); //$NON-NLS-1$
    }
  }

  public EFactory getEFactory()
  {
    return getEPackage().getEFactoryInstance();
  }

  public EPackage getEPackage()
  {
    return getEPackage(true);
  }

  public EPackage getEPackage(boolean loadOnDemand)
  {
	if (ePackage == null && loadOnDemand)
    {
      packageUnit.load(true);
    }

    return ePackage;
  }

  public void setEPackage(EPackage ePackage)
  {
	this.ePackage = ePackage;
  }

  public boolean isCorePackage()
  {
    return CDOModelUtil.isCorePackage(getEPackage());
  }

  public boolean isResourcePackage()
  {
    return CDOModelUtil.isResourcePackage(getEPackage());
  }

  public boolean isTypePackage()
  {
    return CDOModelUtil.isTypesPackage(getEPackage());
  }

  public boolean isSystemPackage()
  {
    return CDOModelUtil.isSystemPackage(getEPackage());
  }

  /**
   * @deprecated As of 4.2 CDOPackageInfos are no longer mapped through Adapters.
   * @see InternalCDOPackageRegistry#registerPackageInfo(EPackage, InternalCDOPackageInfo)
   */
  @Deprecated
  public void notifyChanged(Notification notification)
  {
    throw new UnsupportedOperationException();
  }

  /**
   * @deprecated As of 4.2 CDOPackageInfos are no longer mapped through Adapters.
   * @see InternalCDOPackageRegistry#registerPackageInfo(EPackage, InternalCDOPackageInfo)
   */
  @Deprecated
  public Notifier getTarget()
  {
    throw new UnsupportedOperationException();
  }

  /**
   * @deprecated As of 4.2 CDOPackageInfos are no longer mapped through Adapters.
   * @see InternalCDOPackageRegistry#registerPackageInfo(EPackage, InternalCDOPackageInfo)
   */
  @Deprecated
  public void setTarget(Notifier newTarget)
  {
    throw new UnsupportedOperationException();
  }

  /**
   * @deprecated As of 4.2 CDOPackageInfos are no longer mapped through Adapters.
   * @see InternalCDOPackageRegistry#registerPackageInfo(EPackage, InternalCDOPackageInfo)
   */
  @Deprecated
  public void unsetTarget(Notifier oldTarget)
  {
    throw new UnsupportedOperationException();
  }

  /**
   * @deprecated As of 4.2 CDOPackageInfos are no longer mapped through Adapters.
   * @see InternalCDOPackageRegistry#registerPackageInfo(EPackage, InternalCDOPackageInfo)
   */
  @Deprecated
  public boolean isAdapterForType(Object type)
  {
    throw new UnsupportedOperationException();
  }

  public int compareTo(CDOPackageInfo o)
  {
    return getPackageURI().compareTo(o.getPackageURI());
  }

  @Override
  public String toString()
  {
    return MessageFormat.format("CDOPackageInfo[packageURI={0}, parentURI={1}]", packageURI, parentURI); //$NON-NLS-1$
  }
}


text:
%
% Perform Stereo Camera Calibration
%
% Authors:
%   Matt Holland
%   Ryan Gasik
%   Fatima Dominguez
%   Jaimiey Sears
%

%
% Config
%

% Number of calibration image pairs
numImagePairs = 3;

% Directory that the calibration images are stored in
imageDir = '.\calibrationImages\';

%The size of the squares on the calibration checkerbox
squareSize = 22; % millimeters

%
% Implementation
%

% path to the left images in the calibration pair
imageFiles1 = cell(numImagePairs, 1);

% path to the right images in the calibration pair
imageFiles2 = cell(numImagePairs, 1);

%generate path to calibration images
for i = 1:numImagePairs
    imageFiles1{i} = strcat(imageDir, sprintf('left%02d.png', i));
    imageFiles2{i} = strcat(imageDir, sprintf('right%02d.png', i));
end

%load the calibration images
images1 = cast([], 'uint8');
images2 = cast([], 'uint8');
for i = 1:numel(imageFiles1)
    %left image
    im = imread(imageFiles1{i});

    %scale down image to avoid running out of memory
    im = imresize(im, [600 800]);
    images1(:, :, :, i) = im;

    %Right Image
    im = imread(imageFiles2{i});

    %scale down image to avoid running out of memory
    im = imresize(im, [600 800]);
    images2(:, :, :, i) = im;
end

%Detect checkerbaord in images
[imagePoints, boardSize] = detectCheckerboardPoints(images1, images2);

% Display one image with the detected checkerboard
figure;
imshow(images1(:,:,:,1), 'InitialMagnification', 50);
hold on;
plot(imagePoints(:, 1, 1, 1), imagePoints(:, 2, 1, 1), '*-g');
title('Successful Checkerboard Detection');

% Generate world coordinates of the checkerboard points.
worldPoints = generateCheckerboardPoints(boardSize, squareSize);

% Compute the stereo camera parameters.
stereoParams = estimateCameraParameters(imagePoints, worldPoints);

% Evaluate calibration accuracy.
figure;
showReprojectionErrors(stereoParams);

%save the calibration paramaters to a file for later use
save('calibration.mat', 'stereoParams')


text:
class StuckCiJobsWorker
  include Sidekiq::Worker
  include CronjobQueue

  EXCLUSIVE_LEASE_KEY = 'stuck_ci_builds_worker_lease'.freeze

  BUILD_RUNNING_OUTDATED_TIMEOUT = 1.hour
  BUILD_PENDING_OUTDATED_TIMEOUT = 1.day
  BUILD_PENDING_STUCK_TIMEOUT = 1.hour

  def perform
    return unless try_obtain_lease

    Rails.logger.info "#{self.class}: Cleaning stuck builds"

    drop :running, BUILD_RUNNING_OUTDATED_TIMEOUT
    drop :pending, BUILD_PENDING_OUTDATED_TIMEOUT
    drop_stuck :pending, BUILD_PENDING_STUCK_TIMEOUT

    remove_lease
  end

  private

  def try_obtain_lease
    @uuid = Gitlab::ExclusiveLease.new(EXCLUSIVE_LEASE_KEY, timeout: 30.minutes).try_obtain
  end

  def remove_lease
    Gitlab::ExclusiveLease.cancel(EXCLUSIVE_LEASE_KEY, @uuid)
  end

  def drop(status, timeout)
    search(status, timeout) do |build|
      drop_build :outdated, build, status, timeout
    end
  end

  def drop_stuck(status, timeout)
    search(status, timeout) do |build|
      return unless build.stuck?
      drop_build :stuck, build, status, timeout
    end
  end

  def search(status, timeout)
    builds = Ci::Build.where(status: status).where('ci_builds.updated_at < ?', timeout.ago)
    builds.joins(:project).includes(:tags, :runner, project: :namespace).find_each(batch_size: 50).each do |build|
      yield(build)
    end
  end

  def drop_build(type, build, status, timeout)
    Rails.logger.info "#{self.class}: Dropping #{type} build #{build.id} for runner #{build.runner_id} (status: #{status}, timeout: #{timeout})"
    Gitlab::OptimisticLocking.retry_lock(build, 3) do |b|
      b.drop
    end
  end
end


text:
<?=
$this->render('/catalog/index', [
    'ctDataProvider' => $ctDataProvider,
    'ptDataProvider' => $ptDataProvider,
    'id' => $id,
]);
?>


text:
% Procedural Content - February Progress
% Mark Luo, William Morrow, Matthew Neal, Kurt Spencer
% February 29, 2015

# Overarching Goals (1/2)
* Working Game
* Nice Interface
* Easy to Use Map Designer
* Procedural Level Gen
* Good Amount of Maps

# Overarching Goals (2/2)
* User Feedback/Survey
* Continuous Integration/Deployment
* Reasonable Testing
* Static Analysis

#Goal Progress

* Working Game

* Working Interface

#Goal Progress

* Good Testing & Static Analysis

* Condinuous Integration / Deployment

#Goal Progress

* Working Map Designer

* Good Number of Levels

# Milestones
5 milestones at present

* Feb 27th: v0.1 (done right on time)
* March 6th: v0.2
* March 13th: v0.3
* March 20th: v0.4
* March 17th: v0.5

# v0.1 February 27th
* Functional, if not pretty main menu
* Main menu loads (at least one) level
* Once you reach the end of the level, game tells you you've finished the level
* Can deploy the entire thing in an automated fashion on git commits (but only when all tests pass)

# v0.2 March 6th
* Functional menu that can choose more than one level
* Editor
* Improved display math
* DB?
* Improved menus
* Menu tests

# v0.3 March 13th
* Animated Knight/Player
* Music
* Additional Tileset

#### Depends on DB status
* Save States
* Logins
* High Scores

# v0.4 March 20th
* Sound effects
* Procedural gen
* 15 levels by now

#### Depends on DB
* Save user-created mazes

# v0.5 March 27th
* Fun animation stuff
* Additional tileset
* Gates/Keys
* Winning thing
* Time limit
* Mechanical Turk

# Bad Smells

* Uneven commit history
* Late milestone planning
* Tooling turnover
* Initial language inexperience
* Poor inline documentation
* Code coverage levels
* Long open issues
* Misuses of Git branching
* JSHint issues
* Weather

#Testing

Testing is being done using the following tools:

- [Mocha Testing Framework](http://mochajs.org/)
- [Chai Assertions](http://chaijs.com/)
- [JShint Static Analysis](http://jshint.com/)
	- using html output from [jsint html reporter](https://github.c om/adrianpietka/jshint-html-reporter)
- [Istanbul Code Coverage](https://github.com/gotwarlost/istanbul)
- Our tests live in the [/test directory](https://github.com/CSC510-2015-Axitron/maze/tree/master/test) in our repo

Originally testing was done using a TestRig made by Mr. Morrow, but
we moved to a more formal type of testing as time went on to hook in
with our Continuous Integration and Continuous Deployment systems.

#Continous Integration/Continuous Deployment

Continous integration is being done through:

[Travis-CI](https://travis-ci.org/CSC510-2015-Axitron/maze)

The master branch is being tracked currently, and deployed using:

[Divshot](http://development.maze.divshot.io/)


text:
<?php

namespace OCA\UpdateNotification\AppInfo;

use OCP\AppFramework\App;

class Application extends App {
	public function __construct(array $urlParams = []) {
		parent::__construct('updatenotification', $urlParams);
	}
}


text:
'use strict';

import { module } from 'angular';

export const CORE_VALIDATION_VALIDATEUNIQUE_DIRECTIVE = 'spinnaker.core.validation.unique.directive';
export const name = CORE_VALIDATION_VALIDATEUNIQUE_DIRECTIVE; // for backwards compatibility
module(CORE_VALIDATION_VALIDATEUNIQUE_DIRECTIVE, []).directive('validateUnique', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {
      scope.$watch(
        attr.validateUnique,
        function(newVal, oldVal) {
          if (newVal !== oldVal && (ctrl.$viewValue || ctrl.$dirty)) {
            ctrl.$validate();
          }
        },
        true,
      );
      const uniqueValidator = function(value) {
        let options = scope.$eval(attr.validateUnique) || [];
        let test = value;
        if (attr.validateIgnoreCase === 'true') {
          options = options.map(function(option) {
            return option ? option.toLowerCase() : null;
          });
          test = value ? value.toLowerCase() : value;
        }
        return !options.includes(test);
      };

      ctrl.$validators.validateUnique = uniqueValidator;
    },
  };
});


text:
package org.apache.struts2.showcase.chat;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.SessionAware;

import java.util.Map;

public class ExitRoomAction extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;

	private String roomName;

	private Map session;

	public String getRoomName() {
		return roomName;
	}

	public void setRoomName(String roomName) {
		this.roomName = roomName;
	}

	private ChatService chatService;

	public ExitRoomAction(ChatService chatService) {
		this.chatService = chatService;
	}

	public String execute() throws Exception {
		User user = (User) session.get(ChatAuthenticationInterceptor.USER_SESSION_KEY);
		chatService.exitRoom(user.getName(), roomName);

		return SUCCESS;
	}

	// === SessionAware ===
	public void setSession(Map session) {
		this.session = session;
	}

}


text:
(function ($) {
	"use strict";

	// Settings

	var twitterWidget = true;					// Set to false to hide widget
	var twitterWidgetID = '690463629821419520';	// ID of your Twitter widget

	var disqusComments = false;					// Set to false to hide comments
	var disqusUser = 'disqus_shortname';		// Set to your own Disqus Shortname

	// WARNING: Do not edit below this point unless
	// you are absolutely sure of what you are doing!

	// Home template setup

	$('.home-template .post:nth-of-type(2), .home-template .post:nth-of-type(3)').removeClass('col-lg-4');

	// Navigation

	$('#mobile-nav-trigger').click(function (el) {
		el.preventDefault();

		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
			$(this).html('Show Navigation');
			$('#nav ul.nav').slideUp('fast').removeClass('active');
		} else {
			$(this).addClass('active');
			$(this).html('Close Navigation');
			$('#nav ul.nav').slideDown('fast').addClass('active');
		}
	});

	$(window).resize(function () {
		$('#mobile-nav-trigger').removeClass('active');
		$('#mobile-nav-trigger').html('Show Navigation');

		if ($('#mobile-nav-trigger').css('display') === 'none') {
			$('#nav ul.nav').show();
		} else {
			$('#nav ul.nav').hide();
		}
	});

	// Disqus comments

	if (disqusComments === true && $('#disqus_thread').length) {
		(function () {
			var dsq = document.createElement('script');
			dsq.type = 'text/javascript';
			dsq.async = true;
			dsq.src = '//' + disqusUser + '.disqus.com/embed.js';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
		})();
	} else {
		$('.post-template .post-comments').remove();
	}

	// Related posts

	$('.related-posts').ghostRelated({
		titleClass: 'h1.post-title',
		tagsClass: '.post-tags'
	});

	// Twitter widget

	if (twitterWidget === true) {
		var twitterConfig = {
			"id": twitterWidgetID,
			"domId": 'widget-tweets',
			"maxTweets": 2,
			"enableLinks": true,
			"showUser": false,
			"showInteraction": false
		};
		twitterFetcher.fetch(twitterConfig);
	} else {
		$('#widget-twitter').remove();
	}

	// Latest posts widget

	function latestPosts() {
		$.get('/rss/', function (data) {
			var $xml = $(data);
			var recent = '';
			$xml.find('item').slice(0, 5).each(function () {
				var $this = $(this),
					item = {
						title: $this.find('title').text(),
						link: $this.find('link').text(),
						description: $this.find('description').text(),
						pubDate: $this.find('pubDate').text(),
						category: $this.find('category').text()
					};
				recent += '
';
				recent += '' + item.title + '';
				recent += '
';
			});
			$('#widget-latest ul').html(recent);
		});
	}

	latestPosts();

})(jQuery);


text:
using System;

public class Balls
{
    private static int[] pockets;

    public static void Main(string[] args)
    {
        int pocketCount = int.Parse(Console.ReadLine());
        int ballCount = int.Parse(Console.ReadLine());
        int pocketSize = int.Parse(Console.ReadLine());

        pockets = new int[pocketCount];

        Gen(0, pocketSize, ballCount);
    }

    static void Gen(int index, int pocketSize, int ballsLeft)
    {
        if (index >= pockets.Length)
        {
            Console.WriteLine(string.Join(", ", pockets));
        }
        else
        {
            if (index == pockets.Length - 1)
            {
                if (ballsLeft <= pocketSize)
                {
                    pockets[index] = ballsLeft;
                    Console.WriteLine(string.Join(", ", pockets));
                }
            }
            else
            {
                int balls = Math.Min(pocketSize, ballsLeft - (pockets.Length - index - 1));
                for (int i = balls; i > 0; i--)
                {
                    pockets[index] = i;
                    Gen(index + 1, pocketSize, ballsLeft - i);
                }
            }
        }
    }
}


text:
#ifndef DATASTAX_INTERNAL_DENSE_HASH_MAP_HPP
#define DATASTAX_INTERNAL_DENSE_HASH_MAP_HPP

#include "allocator.hpp"

#include <sparsehash/dense_hash_map>

namespace datastax { namespace internal {

template <class K, class V, class HashFcn = SPARSEHASH_HASH<K>, class EqualKey = std::equal_to<K> >
class DenseHashMap
    : public sparsehash::dense_hash_map<K, V, HashFcn, EqualKey,
                                        internal::Allocator<std::pair<const K, V> > > {
public:
  typedef internal::Allocator<std::pair<const K, V> > Allocator;

  explicit DenseHashMap(size_t expected_max_items_in_table = 0, const HashFcn& hf = HashFcn(),
                        const EqualKey& eql = EqualKey(), const Allocator& alloc = Allocator())
      : sparsehash::dense_hash_map<K, V, HashFcn, EqualKey, Allocator>(expected_max_items_in_table,
                                                                       hf, eql, alloc) {}

  template <class InputIterator>
  DenseHashMap(InputIterator first, InputIterator last, const K& empty_key_val,
               size_t expected_max_items_in_table = 0, const HashFcn& hf = HashFcn(),
               const EqualKey& eql = EqualKey(), const Allocator& alloc = Allocator())
      : sparsehash::dense_hash_map<K, V, HashFcn, EqualKey, Allocator>(
            first, last, empty_key_val, expected_max_items_in_table, hf, eql, alloc) {}
};

}} // namespace datastax::internal

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Alternaria forsythiae Harter

### Remarks
null