text:
title: Improved Reporting and Debugging of Data Publishing
date: 2018-01-29
authors: ['anuveyatsu']
---

We've integrated our pipelines system with the website to display more insights to our users. Any dataset you publish on DataHub could be in one of three states: **processing**, **succeeded** or **failed**. Below we explain each state in detail.

## Processing

While your dataset is being processed, you can see a dataset page with information about currently running steps. For instance, it might be creating a JSON version of your tabular data or validating it against a table schema:

![](/static/img/docs/processing-dataset.gif)

## Succeeded

This is just a regular dataset page you have seen before:

![](/static/img/docs/succeeded-dataset.png)

## Failed

If processing a dataset has failed, you would see a notice about it with a pipeline title that caused the error. You can also expand the error to read the logs and find out the reason for the failure:

![](/static/img/docs/failed-dataset.gif)

## Different versions of your dataset

Each time you publish your dataset, a revision process is triggered for it. You can consider a revision as a version of your dataset, e.g., if it is the first time you have published a particular dataset, it would have version 1 (and the next revision would increment version by 1 so it'd be 2):

`https://datahub.io/<username>/<dataset>/v/1`

It becomes useful when you've re-published your dataset several times and you want to get your data in a specific stage.

:::info
A version is a natural number (integer larger than 0) and you can access the specific version of a dataset by `/v/{number}`.
:::


text:
<?php namespace GtinValidation;

use GtinValidation\GtinFormats\Gtin8;
use GtinValidation\GtinFormats\Gtin12;
use GtinValidation\GtinFormats\Gtin13;
use GtinValidation\GtinFormats\Gtin14;
use GtinValidation\GtinFormats\InvalidGtin;

/**
 * Validates GTIN and provides access to the generated GtinFormatInterface object
 *
 * Class GtinValidator
 * @package GtinValidation
 */
class GtinValidator
{
    private $gtinObject;
    private $isValid;

    /**
     * Creates correct GTIN object, validates that object and stores
     * resulting object and validity in member variables
     *
     * @param string $gtin
     */
    public function __construct($gtin)
    {
        $this->gtinObject = $this->createGtinObject($gtin);
        $this->isValid = $this->validate($this->gtinObject);
    }

    /**
     * @return bool
     */
    public function isValid()
    {
        return $this->isValid;
    }

    /**
     * @return GtinFormatInterface
     */
    public function getGtinObject()
    {
        return $this->gtinObject;
    }

    /**
     * @param GtinFormatInterface $gtinObject
     * @return bool
     */
    private function validate(GtinFormatInterface $gtinObject)
    {
        if ($gtinObject instanceof InvalidGtin) {
            return false;
        }

        if (!$gtinObject->isValid()) {
            return false;
        }

        return true;
    }

    /**
     * @param string $gtin
     * @return GtinFormatInterface
     */
    private function createGtinObject($gtin)
    {
        $gtinObjects = [
            new Gtin8($gtin),
            new Gtin12($gtin),
            new Gtin13($gtin),
            new Gtin14($gtin)
        ];

        // Return a valid GTIN object if the GTIN
        // matches any of our desired formats
        foreach ($gtinObjects as $gtinObject) {
            if ($gtinObject->isValidFormat()) {
                return $gtinObject;
            }
        }

        return new InvalidGtin($gtin);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Wilcommerce.Core.Infrastructure;

namespace Wilcommerce.Auth.Commands.User.Handlers.Interfaces
{
    /// <summary>
    /// Handles the creation of a new administrator
    /// </summary>
    public interface ICreateNewAdministratorCommandHandler : ICommandHandlerAsync<CreateNewAdministratorCommand>
    {
    }
}


text:
#include "soloud.h"
#include "soloud_thread.h"

#if !defined(WITH_WASAPI)

namespace SoLoud
{
	result wasapi_init(Soloud *aSoloud, unsigned int aFlags, unsigned int aSamplerate, unsigned int aBuffer)
	{
		return NOT_IMPLEMENTED;
	}
};

#else

#include <windows.h>
#include <mmdeviceapi.h>
#include <audioclient.h>

#define SAFE_RELEASE(x) \
    if (0 != (x)) \
    { \
        (x)->Release(); \
        (x) = 0; \
    }

namespace SoLoud
{
    struct WASAPIData
    {
        IMMDeviceEnumerator *deviceEnumerator;
        IMMDevice *device;
        IAudioClient *audioClient;
        IAudioRenderClient *renderClient;
        HANDLE bufferEndEvent;
        HANDLE audioProcessingDoneEvent;
        Thread::ThreadHandle thread;
        Soloud *soloud;
        UINT32 bufferFrames;
        int channels;
    };

    static void wasapiSubmitBuffer(WASAPIData *aData, UINT32 aFrames)
    {
        BYTE *buffer = 0;
        if (FAILED(aData->renderClient->GetBuffer(aFrames, &buffer)))
        {
            return;
        }
		aData->soloud->mixSigned16((short *)buffer, aFrames);
        aData->renderClient->ReleaseBuffer(aFrames, 0);
    }

    static void wasapiThread(LPVOID aParam)
    {
        WASAPIData *data = static_cast<WASAPIData*>(aParam);
        wasapiSubmitBuffer(data, data->bufferFrames);
        data->audioClient->Start();
        while (WAIT_OBJECT_0 != WaitForSingleObject(data->audioProcessingDoneEvent, 0))
        {
            WaitForSingleObject(data->bufferEndEvent, INFINITE);
            UINT32 padding = 0;
            if (FAILED(data->audioClient->GetCurrentPadding(&padding)))
            {
                continue;
            }
            UINT32 frames = data->bufferFrames - padding;
            wasapiSubmitBuffer(data, frames);
        }
    }

    static void wasapiCleanup(Soloud *aSoloud)
    {
        if (0 == aSoloud->mBackendData)
        {
            return;
        }
        WASAPIData *data = static_cast<WASAPIData*>(aSoloud->mBackendData);
        SetEvent(data->audioProcessingDoneEvent);
        SetEvent(data->bufferEndEvent);
		if (data->thread)
		{
			Thread::wait(data->thread);
			Thread::release(data->thread);
		}
        CloseHandle(data->bufferEndEvent);
        CloseHandle(data->audioProcessingDoneEvent);
        if (0 != data->audioClient)
        {
            data->audioClient->Stop();
        }
        SAFE_RELEASE(data->renderClient);
        SAFE_RELEASE(data->audioClient);
        SAFE_RELEASE(data->device);
        SAFE_RELEASE(data->deviceEnumerator);
        delete data;
        aSoloud->mBackendData = 0;
        CoUninitialize();
    }

	result wasapi_init(Soloud *aSoloud, unsigned int aFlags, unsigned int aSamplerate, unsigned int aBuffer, unsigned int aChannels)
    {
        if (FAILED(CoInitializeEx(0, COINIT_MULTITHREADED)))
        {
            return UNKNOWN_ERROR;
        }
        WASAPIData *data = new WASAPIData;
        ZeroMemory(data, sizeof(WASAPIData));
        aSoloud->mBackendData = data;
        aSoloud->mBackendCleanupFunc = wasapiCleanup;

        data->bufferEndEvent = CreateEvent(0, FALSE, FALSE, 0);
        if (0 == data->bufferEndEvent)
        {
            return UNKNOWN_ERROR;
        }
        data->audioProcessingDoneEvent = CreateEvent(0, FALSE, FALSE, 0);
        if (0 == data->audioProcessingDoneEvent)
        {
            return UNKNOWN_ERROR;
        }
        if (FAILED(CoCreateInstance(__uuidof(MMDeviceEnumerator), 0, CLSCTX_ALL,
                   __uuidof(IMMDeviceEnumerator),
                   reinterpret_cast<void**>(&data->deviceEnumerator))))
        {
            return UNKNOWN_ERROR;
        }
        if (FAILED(data->deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole,
                                                                   &data->device)))
        {
            return UNKNOWN_ERROR;
        }
        if (FAILED(data->device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, 0,
                                          reinterpret_cast<void**>(&data->audioClient))))
        {
            return UNKNOWN_ERROR;
        }
        WAVEFORMATEX format;
        ZeroMemory(&format, sizeof(WAVEFORMATEX));
        format.nChannels = 2;
        format.nSamplesPerSec = aSamplerate;
        format.wFormatTag = WAVE_FORMAT_PCM;
        format.wBitsPerSample = sizeof(short)*8;
        format.nBlockAlign = (format.nChannels*format.wBitsPerSample)/8;
        format.nAvgBytesPerSec = format.nSamplesPerSec*format.nBlockAlign;
        REFERENCE_TIME dur = static_cast<REFERENCE_TIME>(static_cast<double>(aBuffer)
                                           / (static_cast<double>(aSamplerate)*(1.0/10000000.0)));
		HRESULT res = data->audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED,
			AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
			dur, 0, &format, 0);
		if (FAILED(res))
        {
            return UNKNOWN_ERROR;
        }
        data->bufferFrames = 0;
        if (FAILED(data->audioClient->GetBufferSize(&data->bufferFrames)))
        {
            return UNKNOWN_ERROR;
        }
        if (FAILED(data->audioClient->GetService(__uuidof(IAudioRenderClient),
                                                 reinterpret_cast<void**>(&data->renderClient))))
        {
            return UNKNOWN_ERROR;
        }
        if (FAILED(data->audioClient->SetEventHandle(data->bufferEndEvent)))
        {
            return UNKNOWN_ERROR;
        }
        data->channels = format.nChannels;
        data->soloud = aSoloud;
        aSoloud->postinit(aSamplerate, data->bufferFrames * format.nChannels, aFlags, 2);
        data->thread = Thread::createThread(wasapiThread, data);
        if (0 == data->thread)
        {
            return UNKNOWN_ERROR;
        }
        aSoloud->mBackendString = "WASAPI";
        return 0;
    }
};
#endif


text:
var common = require('../common');

var FrontPage = function() {

	var entityCount = element(by.binding('entityCount'));

	this.load = function() {
        return browser.get('/');
    };

    this.getEntityCount = function() {
    	return entityCount.getText();
    };

    this.typeInSearchField = function(text) {
        var searchField = element(by.css('#start-page-search input'));
        return common.typeInPromised(searchField, text);
    };

    this.getSearchButton = function() {
        return element(by.css('#start-page-search button'));
    };

};

module.exports = new FrontPage();


text:
package com.opengamma.engine.management;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.StandardMBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opengamma.DataNotFoundException;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.engine.exec.stats.TotallingGraphStatisticsGathererProvider;
import com.opengamma.engine.view.ViewDefinition;
import com.opengamma.engine.view.ViewProcess;
import com.opengamma.engine.view.client.ViewClient;
import com.opengamma.engine.view.event.ViewProcessorEventListener;
import com.opengamma.engine.view.impl.ViewProcessInternal;
import com.opengamma.engine.view.impl.ViewProcessorImpl;
import com.opengamma.id.UniqueId;
import com.opengamma.util.ArgumentChecker;

/**
 * Creates exposed MBeans and register with MBeanServer.
 */
public final class ManagementService implements ViewProcessorEventListener {

  /** Logger. */
  private static final Logger s_logger = LoggerFactory.getLogger(ManagementService.class);

  /**
   * The underlying view processor.
   */
  private final ViewProcessorImpl _viewProcessor;
  /**
   * The MBean server.
   */
  private final MBeanServer _mBeanServer;
  /**
   * The statistics gatherer.
   */
  private final TotallingGraphStatisticsGathererProvider _statisticsProvider;
  /**
   * The config.
   */
  private final ConcurrentHashMap<UniqueId, Set<String>> _calcConfigByViewProcessId = new ConcurrentHashMap<>();

  /**
   * Should beans be categorized by view processor or not. If only one view processor is expected then setting this to false means the MBean hierarchy is simpler to navigate.
   */
  private final boolean _splitByViewProcessor;

  /**
   * Have the MBeans already been initialized for the view processor. Used to avoid trying to register on the notifyViewProcessorStarted method if registration has already happened through the
   * constructor.
   */
  private boolean _isInitialized;

  //-------------------------------------------------------------------------
  /**
   * A convenience static method which creates a ManagementService and initializes it with the supplied parameters.
   *
   * @param viewProcessor the view processor, not null
   * @param statisticsProvider the statistics provider, not null
   * @param mBeanServer the MBeanServer to register MBeans to, not null
   * @deprecated add section containing JmxManagementServiceFactory to ini file instead
   */
  @Deprecated
  public static void registerMBeans(ViewProcessorImpl viewProcessor, TotallingGraphStatisticsGathererProvider statisticsProvider, MBeanServer mBeanServer) {
    ManagementService registry = new ManagementService(viewProcessor, statisticsProvider, mBeanServer, false);
    registry.init();
  }

  //-------------------------------------------------------------------------
  /**
   * A constructor for a management service for a range of possible MBeans.
   *
   * @param viewProcessor the view processor, not null
   * @param statisticsProvider the statistics provider, not null
   * @param mBeanServer the MBeanServer to register MBeans to, not null
   * @param splitByViewProcessor if true, then classify registered beans by their view processor. Only required if more than one view processor will be running.
   */
  public ManagementService(ViewProcessorImpl viewProcessor, TotallingGraphStatisticsGathererProvider statisticsProvider, MBeanServer mBeanServer, boolean splitByViewProcessor) {
    ArgumentChecker.notNull(viewProcessor, "View Processor");
    ArgumentChecker.notNull(mBeanServer, "MBeanServer");
    ArgumentChecker.notNull(statisticsProvider, "TotallingGraphStatisticsGathererProvider");
    _viewProcessor = viewProcessor;
    _mBeanServer = mBeanServer;
    _statisticsProvider = statisticsProvider;
    _splitByViewProcessor = splitByViewProcessor;
  }

  //-------------------------------------------------------------------------
  /**
   * Call to register the mbeans in the mbean server and start and do any other required initialization.
   *
   * @throws net.sf.ehcache.CacheException - all exceptions are wrapped in CacheException
   */
  public void init() {
    try {
      initializeAndRegisterMBeans();
      _viewProcessor.getViewProcessorEventListenerRegistry().registerListener(this);
    } catch (Exception e) {
      throw new OpenGammaRuntimeException("MBean registration error", e);
    }
  }

  /**
   * @throws Exception
   * @throws InstanceAlreadyExistsException
   * @throws MBeanRegistrationException
   * @throws NotCompliantMBeanException
   */
  private void initializeAndRegisterMBeans() throws Exception {

    if (!_isInitialized) {
      initializeViewProcessor();
      initializeViewProcesses();
      initializeViewClients();
      initializeGraphExecutionStatistics();
      _isInitialized = true;
    }
  }

  private void initializeGraphExecutionStatistics() throws Exception {
    for (ViewProcess viewProcess : _viewProcessor.getViewProcesses()) {
      Set<String> configurationNames = viewProcess.getLatestViewDefinition().getAllCalculationConfigurationNames();
      _calcConfigByViewProcessId.putIfAbsent(viewProcess.getUniqueId(), configurationNames);
      for (String calcConfigName : configurationNames) {
        GraphExecutionStatisticsMBeanImpl graphStatistics = new GraphExecutionStatisticsMBeanImpl(viewProcess, _statisticsProvider, _viewProcessor.getName(), calcConfigName);
        registerGraphStatistics(graphStatistics);
      }
    }
  }

  private void initializeViewProcessor() throws Exception {
    ViewProcessorMBeanImpl viewProcessor = new ViewProcessorMBeanImpl(_viewProcessor, _splitByViewProcessor);
    registerViewProcessor(viewProcessor);
  }

  private void initializeViewProcesses() throws Exception {
    for (ViewProcessInternal viewProcess : _viewProcessor.getViewProcesses()) {
      ViewProcessMXBeanImpl viewProcessBean = new ViewProcessMXBeanImpl(viewProcess, _viewProcessor, _splitByViewProcessor);
      registerViewProcess(viewProcessBean);
    }
  }

  private void initializeViewClients() throws Exception {
    for (ViewClient viewClient : _viewProcessor.getViewClients()) {
      ViewClientMBeanImpl viewClientBean = new ViewClientMBeanImpl(viewClient, _splitByViewProcessor);
      registerViewClient(viewClientBean);
    }
  }

  //-------------------------------------------------------------------------
  private void registerGraphStatistics(GraphExecutionStatisticsMBeanImpl graphStatistics) throws Exception {
    ObjectName objectName = graphStatistics.getObjectName();
    StandardMBean mbean = new StandardMBean(graphStatistics, GraphExecutionStatisticsMBean.class);
    try {
      _mBeanServer.registerMBean(mbean, objectName);
    } catch (InstanceAlreadyExistsException e) {
      _mBeanServer.unregisterMBean(objectName);
      _mBeanServer.registerMBean(mbean, objectName);
    }
  }

  private void registerViewProcessor(ViewProcessorMBeanImpl viewProcessor) throws Exception {
    ObjectName objectName = viewProcessor.getObjectName();
    StandardMBean mBean = new StandardMBean(viewProcessor, ViewProcessorMBean.class);
    try {
      _mBeanServer.registerMBean(mBean, objectName);
    } catch (InstanceAlreadyExistsException e) {
      _mBeanServer.unregisterMBean(objectName);
      _mBeanServer.registerMBean(mBean, objectName);
    }
  }

  private void registerViewProcess(ViewProcessMXBeanImpl viewProcessBean) throws Exception {
    registerViewProcess(viewProcessBean, viewProcessBean.getObjectName());
  }

  private void registerViewProcess(ViewProcessMXBeanImpl viewProcessBean, ObjectName objectName) throws Exception {
    try {
      _mBeanServer.registerMBean(viewProcessBean, objectName);
    } catch (InstanceAlreadyExistsException e) {
      _mBeanServer.unregisterMBean(objectName);
      _mBeanServer.registerMBean(viewProcessBean, viewProcessBean.getObjectName());
    }
  }

  private void registerViewClient(ViewClientMBeanImpl viewClient) throws Exception {
    ObjectName objectName = viewClient.getObjectName();
    StandardMBean mBean = new StandardMBean(viewClient, ViewClientMBean.class);
    try {
      _mBeanServer.registerMBean(mBean, objectName);
    } catch (InstanceAlreadyExistsException e) {
      _mBeanServer.unregisterMBean(objectName);
      _mBeanServer.registerMBean(mBean, objectName);
    }
  }

  //-------------------------------------------------------------------------
  @Override
  public void notifyViewProcessAdded(UniqueId viewProcessId) {
    ViewProcessInternal view = _viewProcessor.getViewProcess(viewProcessId);
    if (view == null) {
      return;
    }
    ViewProcessMXBeanImpl viewManagement = new ViewProcessMXBeanImpl(view, _viewProcessor, _splitByViewProcessor);
    try {
      registerViewProcess(viewManagement);
    } catch (Exception e) {
      s_logger.warn("Error registering view for management for " + viewManagement.getObjectName() + " . Error was " + e.getMessage(), e);
    }
    ViewDefinition definition;
    try {
      definition = view.getLatestViewDefinition();
    } catch (DataNotFoundException e) {
      definition = null;
      s_logger.error("View process {} does not have a valid view definition", viewProcessId);
    }
    Set<String> configurationNames = Collections.emptySet();
    if (definition != null) {
      configurationNames = definition.getAllCalculationConfigurationNames();
    }
    _calcConfigByViewProcessId.putIfAbsent(viewProcessId, configurationNames);
    for (String calcConfigName : configurationNames) {
      GraphExecutionStatisticsMBeanImpl graphStatistics = new GraphExecutionStatisticsMBeanImpl(view, _statisticsProvider, _viewProcessor.getName(), calcConfigName);
      try {
        registerGraphStatistics(graphStatistics);
      } catch (Exception e) {
        s_logger.warn("Error registering GraphExecutionStatistics for management for " + graphStatistics.getObjectName() + " . Error was " + e.getMessage(), e);
      }
    }
  }

  @Override
  public void notifyViewAutomaticallyStarted(UniqueId viewProcessId, String autoStartName) {
    ViewProcessInternal view = _viewProcessor.getViewProcess(viewProcessId);
    if (view == null) {
      return;
    }
    ViewProcessMXBeanImpl viewManagement = new ViewProcessMXBeanImpl(view, _viewProcessor, _splitByViewProcessor);
    try {
      String beanNamePrefix = _splitByViewProcessor ? "com.opengamma:type=ViewProcessors,ViewProcessor=ViewProcessor " + _viewProcessor.getName() : "com.opengamma:type=ViewProcessor";
      String beanName = beanNamePrefix + ",AutoStartViews=AutoStartViews,name=AutoStart [" + autoStartName + "]";
      registerViewProcess(viewManagement, new ObjectName(beanName));
    } catch (Exception e) {
      s_logger.warn("Error registering view for management for " + viewManagement.getObjectName() + " . Error was " + e.getMessage(), e);
    }
  }

  @Override
  public void notifyViewProcessRemoved(UniqueId viewProcessId) {
    ObjectName objectName = null;
    try {
      objectName = ViewProcessMXBeanImpl.createObjectName(_viewProcessor.getName(), viewProcessId, _splitByViewProcessor);
      _mBeanServer.unregisterMBean(objectName);
    } catch (Exception e) {
      s_logger.warn("Error unregistering view for management for " + objectName + " . Error was " + e.getMessage(), e);
    }
    Set<String> configurationNames = _calcConfigByViewProcessId.get(viewProcessId);
    if (configurationNames != null) {
      //String viewDefinitionName = _viewProcessor.getViewProcess(viewProcessId).getDefinitionName();
      for (String configName : configurationNames) {
        objectName = GraphExecutionStatisticsMBeanImpl.createObjectName(_viewProcessor.getName(), viewProcessId, configName);
        try {
          _mBeanServer.unregisterMBean(objectName);
        } catch (Exception e) {
          s_logger.warn("Error unregistering view for GraphExecutionStatistics for " + objectName + " . Error was " + e.getMessage(), e);
        }
      }
    }
    _calcConfigByViewProcessId.remove(viewProcessId);
  }

  @Override
  public void notifyViewClientAdded(UniqueId viewClientId) {
    ViewClient viewClient = _viewProcessor.getViewClient(viewClientId);
    ViewClientMBeanImpl viewClientBean = new ViewClientMBeanImpl(viewClient, _splitByViewProcessor);
    try {
      registerViewClient(viewClientBean);
    } catch (Exception e) {
      s_logger.warn("Error registering view client for management for " + viewClientBean.getObjectName() + ". Error was " + e.getMessage(), e);
    }
  }

  @Override
  public void notifyViewClientRemoved(UniqueId viewClientId) {
    ObjectName objectName = null;
    try {
      objectName = ViewClientMBeanImpl.createObjectName(_viewProcessor.getName(), viewClientId, _splitByViewProcessor);
      _mBeanServer.unregisterMBean(objectName);
    } catch (Exception e) {
      s_logger.warn("Error unregistering view client for management for " + objectName + ". Error was " + e.getMessage(), e);
    }
  }

  @Override
  public void notifyViewProcessorStarted() {
    try {
      initializeAndRegisterMBeans();
    } catch (Exception e) {
      throw new OpenGammaRuntimeException("MBean registration error", e);
    }
  }

  @Override
  public void notifyViewProcessorStopped() {
    Set<ObjectName> registeredObjectNames = null;
    try {
      // ViewProcessor MBean
      registeredObjectNames = _mBeanServer.queryNames(ViewProcessorMBeanImpl.createObjectName(_viewProcessor, _splitByViewProcessor), null);
      // Other MBeans for this ViewProcessor
      registeredObjectNames.addAll(_mBeanServer.queryNames(new ObjectName("com.opengamma:*,ViewProcessor=" + _viewProcessor.toString()), null));
    } catch (MalformedObjectNameException e) {
      // this should not happen
      s_logger.warn("Error querying MBeanServer. Error was " + e.getMessage(), e);
    }

    for (ObjectName objectName : registeredObjectNames) {
      try {
        _mBeanServer.unregisterMBean(objectName);
      } catch (Exception e) {
        s_logger.warn("Error unregistering object instance " + objectName + " . Error was " + e.getMessage(), e);
      }
    }

    _isInitialized = false;
  }

}


text:
LeetCode
========
This Jun Tang's solutions to problems on LeetCode.com.


text:
import {GPGPUProgram} from './gpgpu_math';
import {getCoordsDataType} from './shader_compiler';

export class TransposeProgram implements GPGPUProgram {
  variableNames = ['A'];
  outputShape: number[];
  userCode: string;
  rank: number;

  constructor(aShape: number[], newDim: number[]) {
    const outputShape: number[] = new Array(aShape.length);
    for (let i = 0; i < outputShape.length; i++) {
      outputShape[i] = aShape[newDim[i]];
    }
    this.outputShape = outputShape;
    this.rank = outputShape.length;
    const dtype = getCoordsDataType(this.rank);
    const switched = getSwitchedCoords(newDim);

    this.userCode = `
    void main() {
      ${dtype} resRC = getOutputCoords();
      setOutput(getA(${switched}));
    }
    `;
  }
}

function getSwitchedCoords(newDim: number[]): string {
  const rank = newDim.length;
  if (rank > 6) {
    throw Error(`Transpose for rank ${rank} is not yet supported`);
  }
  const originalOrder =
      ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u', 'resRC.v'];
  const switchedCoords = new Array(rank);
  for (let i = 0; i < newDim.length; i++) {
    switchedCoords[newDim[i]] = originalOrder[i];
  }
  return switchedCoords.join();
}


text:
(function() {
'use strict';

function NumberAnimationType(property, clamping) {
  this.property = property;
  this.clamping = clamping;
}

defineMethods(NumberAnimationType, {
  maybeConvertPair: function(startKeyframe, endKeyframe, environment, underlyingValue) {
    var start = this.maybeConvertSingle(startKeyframe, environment, underlyingValue);
    if (!start) {
      return null;
    }
    var end = this.maybeConvertSingle(endKeyframe, environment, underlyingValue);
    if (!end) {
      return null;
    }
    return {
      start: start,
      end: end,
    };
  },
  maybeConvertSingle: function(keyframe, environment, underlyingValue) {
    if (!keyframe) {
      return {
        isInvalid: function(environment, underlyingValue) {
          return underlyingValue && underlyingValue.animationType != this;
        }.bind(this),
        interpolableValue: 0,
        nonInterpolableValue: null,
      };
    }

    var resolvedValue = keyframe.value;
    var isInvalid = null;
    if (resolvedValue == 'inherit') {
      resolvedValue = environment.getParent(this.property);
      var property = this.property;
      isInvalid = function(environment, underlyingValue) {
        return environment.getParent(property) != resolvedValue;
      };
    }

    var number = Number(resolvedValue);
    if (isNaN(number)) {
      return null;
    }
    return {
      isInvalid: isInvalid,
      interpolableValue: number,
      nonInterpolableValue: null,
    };
  },
  interpolate: lerp,
  add: add,
  maybeConvertEnvironment: function(environment) {
    return this._maybeConvertValue(environment.get(this.property));
  },
  apply: function(interpolableValue, nonInterpolableValue, environment) {
    environment.set(this.property, this.cssValue(interpolableValue, nonInterpolableValue));
  },
  cssValue: function(interpolableValue, nonInterpolableValue) {
    return this.clamp(interpolableValue);
  },
  clamp: function(value) {
    return (this.clamping == 'non-negative' && value < 0) ? 0 : value;
  }
});

window.NumberAnimationType = NumberAnimationType;

})();


text:
/** 03.08.2012 */
/** NOTE: Need to change the "CALL SYSPROC.ADMIN_REVALIDATE_DB_OBJECTS('TABLE', '<SCHEMA>', NULL);"-Statement - replace <SCHEMA> in Line 67 */
alter table ACT_RU_EXECUTION add CACHED_ENT_STATE_ integer;
update ACT_RU_EXECUTION set CACHED_ENT_STATE_ = 7;

alter table ACT_RU_IDENTITYLINK
add PROC_DEF_ID_ varchar(64);

create index ACT_IDX_ATHRZ_PROCEDEF on ACT_RU_IDENTITYLINK(PROC_DEF_ID_);

alter table ACT_RE_PROCDEF
    alter column KEY_ set not null;

alter table ACT_RE_PROCDEF
    alter column VERSION_ set not null;

create table ACT_HI_PROCVARIABLE (
    ID_ varchar(64) not null,
    PROC_INST_ID_ varchar(64) not null,
    NAME_ varchar(255) not null,
    VAR_TYPE_ varchar(100),
    REV_ integer,
    BYTEARRAY_ID_ varchar(64),
    DOUBLE_ double precision,
    LONG_ bigint,
    TEXT_ varchar(4000),
    TEXT2_ varchar(4000),
    primary key (ID_)
);

create index ACT_IDX_HI_PROCVAR_PROC_INST on ACT_HI_PROCVARIABLE(PROC_INST_ID_);
create index ACT_IDX_HI_PROCVAR_NAME_TYPE on ACT_HI_PROCVARIABLE(NAME_, VAR_TYPE_);

alter table ACT_HI_ACTINST
add TASK_ID_ varchar(64);

alter table ACT_HI_ACTINST
add CALL_PROC_INST_ID_ varchar(64);

/** 17.08.2012 */

/**  fill table ACT_HI_PROCVARIABLE when HISTORY_LEVEL FULL is set, could take a long time depending on the amount of data! */
insert into ACT_HI_PROCVARIABLE
  (ID_,PROC_INST_ID_,NAME_,VAR_TYPE_,REV_,BYTEARRAY_ID_,DOUBLE_,LONG_,TEXT_,TEXT2_)
  select d.ID_,d.PROC_INST_ID_,d.NAME_,d.VAR_TYPE_,d.REV_,d.BYTEARRAY_ID_,d.DOUBLE_,d.LONG_,d.TEXT_,d.TEXT2_
  from ACT_HI_DETAIL d
  inner join
    (
      select de.PROC_INST_ID_, de.NAME_, MAX(de.TIME_) as MAXTIME
      from ACT_HI_DETAIL de
      inner join ACT_HI_PROCINST p on de.PROC_INST_ID_ = p.ID_
      where p.END_TIME_ is not NULL
      group by de.PROC_INST_ID_, de.NAME_
    )
  groupeddetail on d.PROC_INST_ID_ = groupeddetail.PROC_INST_ID_
  and d.NAME_ = groupeddetail.NAME_
  and d.TIME_ = groupeddetail.MAXTIME
  and (select prop.VALUE_ from ACT_GE_PROPERTY prop where prop.NAME_ = 'historyLevel') = 3;

/** update history level to retain old history level */
update ACT_GE_PROPERTY
set VALUE_ = VALUE_ + 1,
    REV_ = REV_ + 1
where NAME_ = 'historyLevel' and VALUE_ >= 2;

CALL SYSPROC.ADMIN_REVALIDATE_DB_OBJECTS('TABLE', '<SCHEMA>', NULL);
alter table ACT_RU_EXECUTION
    add constraint ACT_FK_EXE_PROCDEF
    foreign key (PROC_DEF_ID_)
    references ACT_RE_PROCDEF (ID_);

alter table ACT_RE_PROCDEF
    add constraint ACT_UNIQ_PROCDEF
    unique (KEY_,VERSION_);

alter table ACT_RU_IDENTITYLINK
    add constraint ACT_FK_ATHRZ_PROCEDEF
    foreign key (PROC_DEF_ID_)
    references ACT_RE_PROCDEF (ID_);

alter table ACT_HI_DETAIL
  alter column PROC_INST_ID_ DROP NOT NULL;

alter table ACT_HI_DETAIL
  alter column EXECUTION_ID_ DROP NOT NULL;


text:
package com.jgoodies.uif_lite.component;

import java.awt.Component;
import java.awt.Insets;

import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

/**
 * A very light version of the JGoodies UIFactory class.
 * It consists only of static methods to create frequently used components.
 *
 * @author Karsten Lentzsch
 * @version $Revision$
 */

public final class Factory {

    /** Defines the margin used in toolbar buttons. */
    private static final Insets TOOLBAR_BUTTON_MARGIN = new Insets(1, 1, 1, 1);

    /**
     * Creates and answers a JScrollPane that has an empty
     * border.
     */
    public static JScrollPane createStrippedScrollPane(Component component) {
        JScrollPane scrollPane = new JScrollPane(component);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        return scrollPane;
    }

    /**
     * Creates and returns a JSplitPane that has empty borders.
     * Useful to avoid duplicate decorations, for example if the split pane
     * is contained by other components that already provide a border.
     *
     * @param orientation    the split pane's orientation: horizontal or vertical
     * @param comp1          the top/left component
     * @param comp2          the bottom/right component
     * @param resizeWeight   indicates how to distribute extra space
     * @return a split panes that has an empty border
     */
    public static JSplitPane createStrippedSplitPane(int orientation,
            Component comp1, Component comp2, double resizeWeight) {
        JSplitPane split = UIFSplitPane.createStrippedSplitPane(orientation, comp1, comp2);
        split.setResizeWeight(resizeWeight);
        return split;
    }

    /**
     * Creates and answers an AbstractButton
     * configured for use in a JToolBar.

     *
     * Superceded by ToolBarButton from the JGoodies UI framework.
     */
    public static AbstractButton createToolBarButton(Action action) {
        JButton button = new JButton(action);
        button.setFocusPainted(false);
        button.setMargin(TOOLBAR_BUTTON_MARGIN);
        //button.setHorizontalTextPosition(SwingConstants.CENTER);
        //button.setVerticalTextPosition(SwingConstants.BOTTOM);
        button.setText("");
        return button;
    }

}


text:
export addto!, broadcast_addto!

function addto!(dest::Array{T}, doffs::Int, src::Array{T}, soffs::Int, n::Int) where T
    @assert doffs > 0 && soffs > 0
    axpy!(n, T(1), pointer(src,soffs), 1, pointer(dest,doffs), 1)
    dest
end

function addto!(dest::CuArray{T}, doffs::Int, src::CuArray{T}, soffs::Int, n::Int) where T
    @assert doffs > 0 && soffs > 0
    axpy!(n, T(1), cupointer(src,soffs), 1, cupointer(dest,doffs), 1)
    dest
end

function addto!(dest::UniArray{T}, src::UniArray{T}) where T
    @assert length(dest) == length(src)
    addto!(dest, 1, src, 1, length(dest))
end

function addto!(dest::Array{T}, src::SubArray{T}) where T
    dest[:] = dest + src
    dest
end
function addto!(dest::SubArray{T}, src::Array{T}) where T
    dest[:] = dest + src
    dest
end

broadcast_addto!(dest::Array{T}, src::Array{T}) where T = dest .+= src
broadcast_addto!(dest::CuArray, src::CuArray) = CUDA.broadcast_addto!(dest, src)

@generated function addto!(dest::CuArray{T}, src::CuSubArray{T,N}) where {T,N}
    Ct = cstring(T)
    k = Kernel("""
    __global__ void addto($Ct *dest, Array<$Ct,$N> src) {
        int idx = blockIdx.x * blockDim.x + threadIdx.x;
        if (idx >= src.length()) return;
        dest[idx] += src(idx);
    }
    """)
    quote
        @assert length(dest) == length(src)
        src.linear && return addto!(dest, 1, src.parent, src.offset+1, length(dest))
        gdims, bdims = cudims(length(dest))
        $k(gdims, bdims, pointer(dest), src)
        dest
    end
end

@generated function addto!(dest::CuSubArray{T,N}, src::CuArray{T}) where {T,N}
    Ct = cstring(T)
    k = Kernel("""
    __global__ void addto(Array<$Ct,$N> dest, $Ct *src) {
        int idx = blockIdx.x * blockDim.x + threadIdx.x;
        if (idx >= dest.length()) return;
        dest(idx) += src[idx];
    }
    """)
    quote
        @assert length(dest) == length(src)
        dest.linear && return addto!(dest.parent, dest.offset+1, src, 1, length(src))
        gdims, bdims = cudims(length(dest))
        $k(gdims, bdims, dest, pointer(src))
        dest
    end
end


text:
package system

import (
	"fmt"
	"reflect"

	"github.com/coreos/coreos-cloudinit/config"
)

// serviceContents generates the contents for a drop-in unit given the config.
// The argument must be a struct from the 'config' package.
func serviceContents(e interface{}) string {
	vars := getEnvVars(e)
	if len(vars) == 0 {
		return ""
	}

	out := "[Service]\n"
	for _, v := range vars {
		out += fmt.Sprintf("Environment=\"%s\"\n", v)
	}
	return out
}

func getEnvVars(e interface{}) []string {
	et := reflect.TypeOf(e)
	ev := reflect.ValueOf(e)

	vars := []string{}
	for i := 0; i < et.NumField(); i++ {
		if val := ev.Field(i).Interface(); !config.IsZero(val) {
			key := et.Field(i).Tag.Get("env")
			vars = append(vars, fmt.Sprintf("%s=%v", key, val))
		}
	}

	return vars
}


text:
## Iterdone
[![Build Status](https://secure.travis-ci.org/kevinbeaty/iterdone.svg)](http://travis-ci.org/kevinbeaty/iterdone)

[Itertools][1] as [ES6 Iterables][2].

Currently supports a the following functions:

```javascript
toArray: function(value)
symbol: Symbol.iterator || '@@iterator'
range: function(start?, stop, step?)
count: function(start?, step?)
cycle: function(iter)
repeat: function(elem, n?)
chain: function(/*args*/)
```

### toArray(value)
Converts the value to an iterator and iterates into an array.

### range
Create a range of integers.  From start (default 0, inclusive) to stop (exclusive) incremented by step (default 1).

### count
Creates an infinite counting iterator from start (default 0) and incremented by step (default 1)

### cycle
Creates an infinite iterator that accepts an iterable and repeatedly steps through every item of iterator. Once iterator completes, a new iterator is created from the iterable and steps through again.

### repeat
Repeats an elem up to n times.  If n is undefined, creates an infinite iterator that steps the element.

### chain
Combine multiple iterables into a chained iterable.  Once the first argument is exhausted, moves onto the next, until all argument iterables are exhausted.

[1]: https://docs.python.org/2/library/itertools.html
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/iterable


text:
'use strict';

class SignupController {
  //start-non-standard
  user = {};
  errors = {};
  submitted = false;
  //end-non-standard

  constructor(Auth, $state) {
    this.Auth = Auth;
    this.$state = $state;
    this.user.gender = true;
  }

  register(form) {
    this.submitted = true;

    if (form.$valid) {
      this.Auth.createUser({
        name: this.user.name,
        gender: this.user.gender,
        email: this.user.email,
        password: this.user.password
      })
      .then(() => {
        // Account created, redirect to home
        this.$state.go('main');
      })
      .catch(err => {
        err = err.data;
        this.errors = {};

        // Update validity of form fields that match the mongoose errors
        angular.forEach(err.errors, (error, field) => {
          console.log(error);
          console.log(field);
          form[field].$setValidity('mongoose', false);
          this.errors[field] = error.message;
        });
      });
    }
  }
}

angular.module('dandelionApp')
  .controller('SignupController', SignupController);


text:
#include <rtthread.h>

#include "inc/arc/arc_exception.h"

/* enable interrupt and set interrupt priority mask */
#define ARC_INIT_STATUS (AUX_STATUS_MASK_IE | ((-1 - INT_PRI_MIN) << 1))

extern void start_r(void);

rt_uint32_t context_switch_reqflg;
rt_uint32_t rt_interrupt_from_thread;
rt_uint32_t rt_interrupt_to_thread;

struct init_stack_frame {
	rt_uint32_t pc;
	rt_uint32_t blink;
	rt_uint32_t task;
	rt_uint32_t status32;
	rt_uint32_t r0;
};

/**
 * shutdown CPU
 */
void rt_hw_cpu_shutdown(void)
{

}

rt_uint8_t *rt_hw_stack_init(void       *tentry,
                             void       *parameter,
                             rt_uint8_t *stack_addr,
                             void       *texit)
{
    struct init_stack_frame *stack_frame;
    rt_uint8_t         *stk;

    stk  = stack_addr + sizeof(rt_uint32_t);
    stk  = (rt_uint8_t *)RT_ALIGN_DOWN((rt_uint32_t)stk, 8);
    stk -= sizeof(struct init_stack_frame);

    stack_frame = (struct init_stack_frame *)stk;

    stack_frame->pc = (rt_uint32_t)start_r;
    stack_frame->blink = (rt_uint32_t)texit;
    stack_frame->task = (rt_uint32_t)tentry;
    stack_frame->status32 = ARC_INIT_STATUS;
	stack_frame->r0 = (rt_uint32_t)parameter;

    return stk;
}

/**
 * This function set the hook, which is invoked on fault exception handling.
 *
 * @param exception_handle the exception handling hook function.
 */
void rt_hw_exception_install(rt_err_t (*exception_handle)(void *context))
{
    exception_handle = exception_handle;
}


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

<title>Uses of Class compose.ReceivingActor</title>
<meta name="date" content="2016-03-02">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
compose.ReceivingActor

Packages that use ReceivingActor

Package
Description

compose

composition

Uses of ReceivingActor in compose

Fields in compose with type parameters of type ReceivingActor

Modifier and Type
Field and Description

private java.util.function.Supplier<ReceivingActor<M,Q>>
Connection.receiverFactory

Methods in compose that return ReceivingActor

Modifier and Type
Method and Description

abstract ReceivingActor<M,P>
TransportPlay.getReceiver()

Uses of ReceivingActor in composition

Fields in composition with type parameters of type ReceivingActor

Modifier and Type
Field and Description

private Play.Character<ReceivingActor<P,P>>
AcknowledgeChannel.receiver

Methods in composition that return ReceivingActor

Modifier and Type
Method and Description

ReceivingActor<P,P>
AcknowledgeChannel.getReceiver()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
title: "Photos"
bg: white
color: black
style: center
fa-icon: photo
---


text:
package com.vividsolutions.jts.operation.buffer;

/**
 * Contains the parameters which
 * describe how a buffer should be constructed.
 *
 * @author Martin Davis
 *
 */
public class BufferParameters
{
  /**
   * Specifies a round line buffer end cap style.
   */
  public static final int CAP_ROUND = 1;
  /**
   * Specifies a flat line buffer end cap style.
   */
  public static final int CAP_FLAT = 2;
  /**
   * Specifies a square line buffer end cap style.
   */
  public static final int CAP_SQUARE = 3;

  /**
   * Specifies a round join style.
   */
  public static final int JOIN_ROUND = 1;
  /**
   * Specifies a mitre join style.
   */
  public static final int JOIN_MITRE = 2;
  /**
   * Specifies a bevel join style.
   */
  public static final int JOIN_BEVEL = 3;

  /**
   * The default number of facets into which to divide a fillet of 90 degrees.
   * A value of 8 gives less than 2% max error in the buffer distance.
   * For a max error of < 1%, use QS = 12.
   * For a max error of < 0.1%, use QS = 18.
   */
  public static final int DEFAULT_QUADRANT_SEGMENTS = 8;

  /**
   * The default mitre limit
   * Allows fairly pointy mitres.
   */
  public static final double DEFAULT_MITRE_LIMIT = 5.0;

  private int quadrantSegments = DEFAULT_QUADRANT_SEGMENTS;
  private int endCapStyle = CAP_ROUND;
  private int joinStyle = JOIN_ROUND;
  private double mitreLimit = DEFAULT_MITRE_LIMIT;
  private boolean isSingleSided = false;

  /**
   * Creates a default set of parameters
   *
   */
  public BufferParameters() {
  }

  /**
   * Creates a set of parameters with the
   * given quadrantSegments value.
   *
   * @param quadrantSegments the number of quadrant segments to use
   */
  public BufferParameters(int quadrantSegments)
  {
    setQuadrantSegments(quadrantSegments);
  }

  /**
   * Creates a set of parameters with the
   * given quadrantSegments and endCapStyle values.
   *
   * @param quadrantSegments the number of quadrant segments to use
   * @param endCapStyle the end cap style to use
   */
  public BufferParameters(int quadrantSegments,
      int endCapStyle)
  {
    setQuadrantSegments(quadrantSegments);
    setEndCapStyle(endCapStyle);
  }

  /**
   * Creates a set of parameters with the
   * given parameter values.
   *
   * @param quadrantSegments the number of quadrant segments to use
   * @param endCapStyle the end cap style to use
   * @param joinStyle the join style to use
   * @param mitreLimit the mitre limit to use
   */
  public BufferParameters(int quadrantSegments,
      int endCapStyle,
      int joinStyle,
      double mitreLimit)
  {
    setQuadrantSegments(quadrantSegments);
    setEndCapStyle(endCapStyle);
    setJoinStyle(joinStyle);
    setMitreLimit(mitreLimit);
  }

  /**
   * Gets the number of quadrant segments which will be used
   *
   * @return the number of quadrant segments
   */
  public int getQuadrantSegments()
  {
    return quadrantSegments;
  }

  /**
   * Sets the number of line segments used to approximate an angle fillet.
   *

   *
If <tt>quadSegs</tt> >= 1, joins are round, and <tt>quadSegs</tt> indicates the number of
   * segments to use to approximate a quarter-circle.
   *
If <tt>quadSegs</tt> = 0, joins are bevelled (flat)
   *
If <tt>quadSegs</tt> < 0, joins are mitred, and the value of qs
   * indicates the mitre ration limit as
   *

   * mitreLimit = |<tt>quadSegs</tt>|
   *

   *

   * For round joins, <tt>quadSegs</tt> determines the maximum
   * error in the approximation to the true buffer curve.
   * The default value of 8 gives less than 2% max error in the buffer distance.
   * For a max error of < 1%, use QS = 12.
   * For a max error of < 0.1%, use QS = 18.
   * The error is always less than the buffer distance
   * (in other words, the computed buffer curve is always inside the true
   * curve).
   *
   * @param quadrantSegments the number of segments in a fillet for a quadrant
   */
  public void setQuadrantSegments(int quadSegs)
  {
    quadrantSegments = quadSegs;

    /**
     * Indicates how to construct fillets.
     * If qs >= 1, fillet is round, and qs indicates number of
     * segments to use to approximate a quarter-circle.
     * If qs = 0, fillet is bevelled flat (i.e. no filleting is performed)
     * If qs < 0, fillet is mitred, and absolute value of qs
     * indicates maximum length of mitre according to
     *
     * mitreLimit = |qs|
     */
    if (quadrantSegments == 0)
      joinStyle = JOIN_BEVEL;
    if (quadrantSegments < 0) {
      joinStyle = JOIN_MITRE;
      mitreLimit = Math.abs(quadrantSegments);
    }

    if (quadSegs <= 0) {
      quadrantSegments = 1;
    }

    /**
     * If join style was set by the quadSegs value,
     * use the default for the actual quadrantSegments value.
     */
    if (joinStyle != JOIN_ROUND) {
      quadrantSegments = DEFAULT_QUADRANT_SEGMENTS;
    }
  }

  /**
   * Computes the maximum distance error due to a given level
   * of approximation to a true arc.
   *
   * @param quadSegs the number of segments used to approximate a quarter-circle
   * @return the error of approximation
   */
  public static double bufferDistanceError(int quadSegs)
  {
    double alpha = Math.PI / 2.0 / quadSegs;
    return 1 - Math.cos(alpha / 2.0);
  }

  /**
   * Gets the end cap style.
   *
   * @return the end cap style
   */
  public int getEndCapStyle()
  {
    return endCapStyle;
  }

  /**
   * Specifies the end cap style of the generated buffer.
   * The styles supported are {@link #CAP_ROUND}, {@link #CAP_BUTT}, and {@link #CAP_SQUARE}.
   * The default is CAP_ROUND.
   *
   * @param endCapStyle the end cap style to specify
   */
  public void setEndCapStyle(int endCapStyle)
  {
    this.endCapStyle = endCapStyle;
  }

  /**
   * Gets the join style
   *
   * @return the join style code
   */
  public int getJoinStyle()
  {
    return joinStyle;
  }

  /**
   * Sets the join style for outside (reflex) corners between line segments.
   * Allowable values are {@link JOIN_ROUND} (which is the default),
   * {@link JOIN_MITRE} and {link JOIN_BEVEL}.
   *
   * @param joinStyle the code for the join style
   */
  public void setJoinStyle(int joinStyle)
  {
    this.joinStyle = joinStyle;
  }

  /**
   * Gets the mitre ratio limit.
   *
   * @return the limit value
   */
  public double getMitreLimit()
  {
    return mitreLimit;
  }

  /**
   * Sets the limit on the mitre ratio used for very sharp corners.
   * The mitre ratio is the ratio of the distance from the corner
   * to the end of the mitred offset corner.
   * When two line segments meet at a sharp angle,
   * a miter join will extend far beyond the original geometry.
   * (and in the extreme case will be infinitely far.)
   * To prevent unreasonable geometry, the mitre limit
   * allows controlling the maximum length of the join corner.
   * Corners with a ratio which exceed the limit will be beveled.
   *
   * @param mitreLimit the mitre ratio limit
   */
  public void setMitreLimit(double mitreLimit)
  {
    this.mitreLimit = mitreLimit;
  }

  /**
   * Sets whether the computed buffer should be single-sided.
   * A single-sided buffer is constructed on only one side of each input line.
   *
   * The side used is determined by the sign of the buffer distance:
   *

   *
a positive distance indicates the left-hand side
   *
a negative distance indicates the right-hand side
   *

   * The single-sided buffer of point geometries is
   * the same as the regular buffer.
   *

   * The End Cap Style for single-sided buffers is
   * always ignored,
   * and forced to the equivalent of <tt>CAP_FLAT</tt>.
   *
   * @param isSingleSided true if a single-sided buffer should be constructed
   */
  public void setSingleSided(boolean isSingleSided)
  {
    this.isSingleSided = isSingleSided;
  }

  /**
   * Tests whether the buffer is to be generated on a single side only.
   *
   * @return true if the generated buffer is to be single-sided
   */
  public boolean isSingleSided() {
    return isSingleSided;
  }
}


text:
package papu.mvc;

import javax.persistence.EntityManagerFactory;

public interface IController<M,I>
{

	public Class<M> getModelClass();

	public EntityManagerFactory getEntityManagerFactory();

}


text:
// Copyright (C) 2018 The Android Open Source Project
//
// 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.

package com.google.gerrit.acceptance.testsuite.group;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.gerrit.acceptance.testsuite.ThrowingConsumer;
import com.google.gerrit.entities.Account;
import com.google.gerrit.entities.AccountGroup;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;

@AutoValue
public abstract class TestGroupUpdate {

  public abstract Optional<String> name();

  public abstract Optional<String> description();

  public abstract Optional<AccountGroup.UUID> ownerGroupUuid();

  public abstract Optional<Boolean> visibleToAll();

  public abstract Function<ImmutableSet<Account.Id>, Set<Account.Id>> memberModification();

  public abstract Function<ImmutableSet<AccountGroup.UUID>, Set<AccountGroup.UUID>>
      subgroupModification();

  abstract ThrowingConsumer<TestGroupUpdate> groupUpdater();

  public static Builder builder(ThrowingConsumer<TestGroupUpdate> groupUpdater) {
    return new AutoValue_TestGroupUpdate.Builder()
        .groupUpdater(groupUpdater)
        .memberModification(in -> in)
        .subgroupModification(in -> in);
  }

  @AutoValue.Builder
  public abstract static class Builder {

    public abstract Builder name(String name);

    public abstract Builder description(String description);

    public Builder clearDescription() {
      return description("");
    }

    public abstract Builder ownerGroupUuid(AccountGroup.UUID ownerGroupUUID);

    public abstract Builder visibleToAll(boolean visibleToAll);

    abstract Builder memberModification(
        Function<ImmutableSet<Account.Id>, Set<Account.Id>> memberModification);

    abstract Function<ImmutableSet<Account.Id>, Set<Account.Id>> memberModification();

    public Builder clearMembers() {
      return memberModification(originalMembers -> ImmutableSet.of());
    }

    public Builder addMember(Account.Id member) {
      Function<ImmutableSet<Account.Id>, Set<Account.Id>> previousModification =
          memberModification();
      memberModification(
          originalMembers ->
              Sets.union(previousModification.apply(originalMembers), ImmutableSet.of(member)));
      return this;
    }

    public Builder removeMember(Account.Id member) {
      Function<ImmutableSet<Account.Id>, Set<Account.Id>> previousModification =
          memberModification();
      memberModification(
          originalMembers ->
              Sets.difference(
                  previousModification.apply(originalMembers), ImmutableSet.of(member)));
      return this;
    }

    abstract Builder subgroupModification(
        Function<ImmutableSet<AccountGroup.UUID>, Set<AccountGroup.UUID>> subgroupModification);

    abstract Function<ImmutableSet<AccountGroup.UUID>, Set<AccountGroup.UUID>>
        subgroupModification();

    public Builder clearSubgroups() {
      return subgroupModification(originalMembers -> ImmutableSet.of());
    }

    public Builder addSubgroup(AccountGroup.UUID subgroup) {
      Function<ImmutableSet<AccountGroup.UUID>, Set<AccountGroup.UUID>> previousModification =
          subgroupModification();
      subgroupModification(
          originalSubgroups ->
              Sets.union(previousModification.apply(originalSubgroups), ImmutableSet.of(subgroup)));
      return this;
    }

    public Builder removeSubgroup(AccountGroup.UUID subgroup) {
      Function<ImmutableSet<AccountGroup.UUID>, Set<AccountGroup.UUID>> previousModification =
          subgroupModification();
      subgroupModification(
          originalSubgroups ->
              Sets.difference(
                  previousModification.apply(originalSubgroups), ImmutableSet.of(subgroup)));
      return this;
    }

    abstract Builder groupUpdater(ThrowingConsumer<TestGroupUpdate> groupUpdater);

    abstract TestGroupUpdate autoBuild();

    /** Executes the group update as specified. */
    public void update() {
      TestGroupUpdate groupUpdater = autoBuild();
      groupUpdater.groupUpdater().acceptAndThrowSilently(groupUpdater);
    }
  }
}


text:
import datetime
import os
import unittest

from unittest import mock
import nose

from airflow import DAG, configuration, operators
from airflow.models import TaskInstance
from airflow.operators.hive_operator import HiveOperator
from airflow.utils import timezone

configuration.load_test_config()

DEFAULT_DATE = datetime.datetime(2015, 1, 1)
DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat()
DEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10]

class HiveEnvironmentTest(unittest.TestCase):

    def setUp(self):
        configuration.load_test_config()
        args = {'owner': 'airflow', 'start_date': DEFAULT_DATE}
        dag = DAG('test_dag_id', default_args=args)
        self.dag = dag
        self.hql = """
        USE airflow;
        DROP TABLE IF EXISTS static_babynames_partitioned;
        CREATE TABLE IF NOT EXISTS static_babynames_partitioned (
            state string,
            year string,
            name string,
            gender string,
            num int)
        PARTITIONED BY (ds string);
        INSERT OVERWRITE TABLE static_babynames_partitioned
            PARTITION(ds='{{ ds }}')
        SELECT state, year, name, gender, num FROM static_babynames;
        """

class HiveOperatorConfigTest(HiveEnvironmentTest):

    def test_hive_airflow_default_config_queue(self):
        t = HiveOperator(
            task_id='test_default_config_queue',
            hql=self.hql,
            mapred_queue_priority='HIGH',
            mapred_job_name='airflow.test_default_config_queue',
            dag=self.dag)

        # just check that the correct default value in test_default.cfg is used
        test_config_hive_mapred_queue = configuration.conf.get(
            'hive',
            'default_hive_mapred_queue'
        )
        self.assertEqual(t.get_hook().mapred_queue, test_config_hive_mapred_queue)

    def test_hive_airflow_default_config_queue_override(self):
        specific_mapred_queue = 'default'
        t = HiveOperator(
            task_id='test_default_config_queue',
            hql=self.hql,
            mapred_queue=specific_mapred_queue,
            mapred_queue_priority='HIGH',
            mapred_job_name='airflow.test_default_config_queue',
            dag=self.dag)

        self.assertEqual(t.get_hook().mapred_queue, specific_mapred_queue)

class HiveOperatorTest(HiveEnvironmentTest):

    def test_hiveconf_jinja_translate(self):
        hql = "SELECT ${num_col} FROM ${hiveconf:table};"
        t = HiveOperator(
            hiveconf_jinja_translate=True,
            task_id='dry_run_basic_hql', hql=hql, dag=self.dag)
        t.prepare_template()
        self.assertEqual(t.hql, "SELECT {{ num_col }} FROM {{ table }};")

    def test_hiveconf(self):
        hql = "SELECT * FROM ${hiveconf:table} PARTITION (${hiveconf:day});"
        t = HiveOperator(
            hiveconfs={'table': 'static_babynames', 'day': '{{ ds }}'},
            task_id='dry_run_basic_hql', hql=hql, dag=self.dag)
        t.prepare_template()
        self.assertEqual(
            t.hql,
            "SELECT * FROM ${hiveconf:table} PARTITION (${hiveconf:day});")

    @mock.patch('airflow.operators.hive_operator.HiveOperator.get_hook')
    def test_mapred_job_name(self, mock_get_hook):
        mock_hook = mock.MagicMock()
        mock_get_hook.return_value = mock_hook
        t = HiveOperator(
            task_id='test_mapred_job_name',
            hql=self.hql,
            dag=self.dag)

        fake_execution_date = timezone.datetime(2018, 6, 19)
        fake_ti = TaskInstance(task=t, execution_date=fake_execution_date)
        fake_ti.hostname = 'fake_hostname'
        fake_context = {'ti': fake_ti}

        t.execute(fake_context)
        self.assertEqual(
            "Airflow HiveOperator task for {}.{}.{}.{}"
            .format(fake_ti.hostname,
                    self.dag.dag_id, t.task_id,
                    fake_execution_date.isoformat()), mock_hook.mapred_job_name)

if 'AIRFLOW_RUNALL_TESTS' in os.environ:

    import airflow.hooks.hive_hooks
    import airflow.operators.presto_to_mysql

    class HivePrestoTest(HiveEnvironmentTest):

        def test_hive(self):
            t = HiveOperator(
                task_id='basic_hql', hql=self.hql, dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive_queues(self):
            t = HiveOperator(
                task_id='test_hive_queues', hql=self.hql,
                mapred_queue='default', mapred_queue_priority='HIGH',
                mapred_job_name='airflow.test_hive_queues',
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive_dryrun(self):
            t = HiveOperator(
                task_id='dry_run_basic_hql', hql=self.hql, dag=self.dag)
            t.dry_run()

        def test_beeline(self):
            t = HiveOperator(
                task_id='beeline_hql', hive_cli_conn_id='hive_cli_default',
                hql=self.hql, dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_presto(self):
            sql = """
            SELECT count(1) FROM airflow.static_babynames_partitioned;
            """
            t = operators.presto_check_operator.PrestoCheckOperator(
                task_id='presto_check', sql=sql, dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_presto_to_mysql(self):
            t = operators.presto_to_mysql.PrestoToMySqlTransfer(
                task_id='presto_to_mysql_check',
                sql="""
                SELECT name, count(*) as ccount
                FROM airflow.static_babynames
                GROUP BY name
                """,
                mysql_table='test_static_babynames',
                mysql_preoperator='TRUNCATE TABLE test_static_babynames;',
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hdfs_sensor(self):
            t = operators.sensors.HdfsSensor(
                task_id='hdfs_sensor_check',
                filepath='hdfs://user/hive/warehouse/airflow.db/static_babynames',
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_webhdfs_sensor(self):
            t = operators.sensors.WebHdfsSensor(
                task_id='webhdfs_sensor_check',
                filepath='hdfs://user/hive/warehouse/airflow.db/static_babynames',
                timeout=120,
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_sql_sensor(self):
            t = operators.sensors.SqlSensor(
                task_id='hdfs_sensor_check',
                conn_id='presto_default',
                sql="SELECT 'x' FROM airflow.static_babynames LIMIT 1;",
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive_stats(self):
            t = operators.hive_stats_operator.HiveStatsCollectionOperator(
                task_id='hive_stats_check',
                table="airflow.static_babynames_partitioned",
                partition={'ds': DEFAULT_DATE_DS},
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_named_hive_partition_sensor(self):
            t = operators.sensors.NamedHivePartitionSensor(
                task_id='hive_partition_check',
                partition_names=[
                    "airflow.static_babynames_partitioned/ds={{ds}}"
                ],
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_named_hive_partition_sensor_succeeds_on_multiple_partitions(self):
            t = operators.sensors.NamedHivePartitionSensor(
                task_id='hive_partition_check',
                partition_names=[
                    "airflow.static_babynames_partitioned/ds={{ds}}",
                    "airflow.static_babynames_partitioned/ds={{ds}}"
                ],
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_named_hive_partition_sensor_parses_partitions_with_periods(self):
            t = operators.sensors.NamedHivePartitionSensor.parse_partition_name(
                partition="schema.table/part1=this.can.be.an.issue/part2=ok")
            self.assertEqual(t[0], "schema")
            self.assertEqual(t[1], "table")
            self.assertEqual(t[2], "part1=this.can.be.an.issue/part2=this_should_be_ok")

        @nose.tools.raises(airflow.exceptions.AirflowSensorTimeout)
        def test_named_hive_partition_sensor_times_out_on_nonexistent_partition(self):
            t = operators.sensors.NamedHivePartitionSensor(
                task_id='hive_partition_check',
                partition_names=[
                    "airflow.static_babynames_partitioned/ds={{ds}}",
                    "airflow.static_babynames_partitioned/ds=nonexistent"
                ],
                poke_interval=0.1,
                timeout=1,
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive_partition_sensor(self):
            t = operators.sensors.HivePartitionSensor(
                task_id='hive_partition_check',
                table='airflow.static_babynames_partitioned',
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive_metastore_sql_sensor(self):
            t = operators.sensors.MetastorePartitionSensor(
                task_id='hive_partition_check',
                table='airflow.static_babynames_partitioned',
                partition_name='ds={}'.format(DEFAULT_DATE_DS),
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive2samba(self):
            t = operators.hive_to_samba_operator.Hive2SambaOperator(
                task_id='hive2samba_check',
                samba_conn_id='tableau_samba',
                hql="SELECT * FROM airflow.static_babynames LIMIT 10000",
                destination_filepath='test_airflow.csv',
                dag=self.dag)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)

        def test_hive_to_mysql(self):
            t = operators.hive_to_mysql.HiveToMySqlTransfer(
                mysql_conn_id='airflow_db',
                task_id='hive_to_mysql_check',
                create=True,
                sql="""
                SELECT name
                FROM airflow.static_babynames
                LIMIT 100
                """,
                mysql_table='test_static_babynames',
                mysql_preoperator=[
                    'DROP TABLE IF EXISTS test_static_babynames;',
                    'CREATE TABLE test_static_babynames (name VARCHAR(500))',
                ],
                dag=self.dag)
            t.clear(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
            t.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE,
                  ignore_ti_state=True)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Ux Design</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

    <link href='http://fonts.googleapis.com/css?family=Lato:100,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                cv \\ portfolio

                        Greenlight Discharge Dashboard

                        Agent

                    Hospital Course Timeline

                    Pilots

                    Proposals

                    Web

                    Photography

                        Contact

Web Development - HTML5, CSS, Ruby on Rails

Co-launched mHealth Labs, a joint engineering and medical program for app development at Penn Medicine.  Developed front-end of distribution website for Cut-the-Crap Step 2 Boards Exam Series to allow student downloads.  Developed landing page for the new Penn Medicine mHealth Center of Excellence

Visit mHealth Labs site

Visit Cut The Crap site

Visit mHealth Center site

 © 2015 Katherine Choi. All Rights Reserved.


text:
module com.iluwatar.doublecheckedlocking {
	requires org.slf4j;
}


text:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;

/**
 * This is the model class for table "post".
 *
 * @property integer $post_id
 * @property string $title
 * @property string $body
 * @property string $avatar
 * @property integer $created_at
 * @property integer $updated_at
 */
class Post extends \yii\db\ActiveRecord
{
    public $image;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'post';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['image'], 'safe'],
            [['image'], 'file', 'extensions'=>'jpg, gif, png'],
            [['title', 'body'], 'required'],
            [['created_at', 'updated_at'], 'integer'],
            [['title', 'avatar', 'author'], 'string', 'max' => 100],
            [['body'], 'string', 'max' => 500],
            [['author'],'default','value'=>'Anonymous'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'post_id' => 'Post ID',
            'title' => 'Title',
            'body' => 'Text',
            'avatar' => 'Avatar',
            'author' => 'Name',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
                'value' => new Expression('NOW()'),
            ],
        ];
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Buffers;
using Xunit;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Buffers.Text;

namespace System.Text.Primitives.Tests
{
    public static class TestHelper
    {
        public const int LoadIterations = 30000;

        // Converts a hex string to binary.
        public static byte[] DecodeHex(string input)
        {
            int ParseNibble(char ch)
            {
                ch -= (char)'0';
                if (ch < 10) { return ch; }

                ch -= (char)('A' - '0');
                if (ch < 6) { return (ch + 10); }

                ch -= (char)('a' - 'A');
                if (ch < 6) { return (ch + 10); }

                throw new Exception("Invalid hex character.");
            }

            if (input.Length % 2 != 0) { throw new Exception("Invalid hex data."); }

            byte[] retVal = new byte[input.Length / 2];
            for (int i = 0; i < retVal.Length; i++)
            {
                retVal[i] = (byte)((ParseNibble(input[2 * i]) << 4) | ParseNibble(input[2 * i + 1]));
            }

            return retVal;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void DoNotIgnore(uint value, int consumed)
        {
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void DoNotIgnore(ulong value, int consumed)
        {
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void DoNotIgnore(int value, int consumed)
        {
        }

        public static void PrintTestName(string testString, [CallerMemberName] string testName = "")
        {
            if (testString != null)
            {
                Console.WriteLine("{0} called with test string \"{1}\".", testName, testString);
            }
            else
            {
                Console.WriteLine("{0} called with no test string.", testName);
            }
        }

        public static string SpanToString(Span<byte> span, SymbolTable symbolTable = null)
        {
            if (symbolTable == null || symbolTable == SymbolTable.InvariantUtf8)
            {
                Assert.Equal(OperationStatus.Done, TextEncodings.Utf8.ToUtf16Length(span, out int needed));
                Span<byte> output = new byte[needed];
                Assert.Equal(OperationStatus.Done, TextEncodings.Utf8.ToUtf16(span, output, out int consumed, out int written));
                return new string(MemoryMarshal.Cast<byte, char>(output).ToArray());
            }
            else if (symbolTable == SymbolTable.InvariantUtf16)
            {
                return new string(MemoryMarshal.Cast<byte, char>(span).ToArray());
            }

            throw new NotSupportedException();
        }

        // Borrowed from https://github.com/dotnet/corefx/blob/master/src/System.Memory/tests/AllocationHelper.cs

        private static readonly Mutex MemoryLock = new Mutex();
        private static readonly TimeSpan WaitTimeout = TimeSpan.FromSeconds(120);

        public static bool TryAllocNative(IntPtr size, out IntPtr memory)
        {
            memory = IntPtr.Zero;

            if (!MemoryLock.WaitOne(WaitTimeout))
                return false;

            try
            {
                memory = Marshal.AllocHGlobal(size);
            }
            catch (OutOfMemoryException)
            {
                memory = IntPtr.Zero;
                MemoryLock.ReleaseMutex();
            }

            return memory != IntPtr.Zero;
        }

        public static void ReleaseNative(ref IntPtr memory)
        {
            try
            {
                Marshal.FreeHGlobal(memory);
                memory = IntPtr.Zero;
            }
            finally
            {
                MemoryLock.ReleaseMutex();
            }
        }

        public static byte[] UtfEncode(string s, bool utf16)
        {
            if (utf16)
                return Text.Encoding.Unicode.GetBytes(s);
            else
                return Text.Encoding.UTF8.GetBytes(s);
        }

        // TODO: Fix Thai + symbol and adjust tests.
        // Change from new byte[] { 43 }, i.e. '+' to new byte[] { 0xE0, 0xB8, 0x9A, 0xE0, 0xB8, 0xA7, 0xE0, 0xB8, 0x81 }, i.e. 'บวก'
        static byte[][] s_thaiUtf8DigitsAndSymbols = new byte[][]
        {
            new byte[] { 0xe0, 0xb9, 0x90 }, new byte[] { 0xe0, 0xb9, 0x91 }, new byte[] { 0xe0, 0xb9, 0x92 },
            new byte[] { 0xe0, 0xb9, 0x93 }, new byte[] { 0xe0, 0xb9, 0x94 }, new byte[] { 0xe0, 0xb9, 0x95 }, new byte[] { 0xe0, 0xb9, 0x96 },
            new byte[] { 0xe0, 0xb9, 0x97 }, new byte[] { 0xe0, 0xb9, 0x98 }, new byte[] { 0xe0, 0xb9, 0x99 }, new byte[] { 0xE0, 0xB8, 0x88, 0xE0, 0xB8, 0x94 }, null,
            new byte[] { 0xE0, 0xB8, 0xAA, 0xE0, 0xB8, 0xB4, 0xE0, 0xB9, 0x88, 0xE0, 0xB8, 0x87, 0xE0, 0xB8, 0x97, 0xE0, 0xB8, 0xB5, 0xE0, 0xB9, 0x88, 0xE0, 0xB9, 0x83,
                0xE0, 0xB8, 0xAB, 0xE0, 0xB8, 0x8D, 0xE0, 0xB9, 0x88, 0xE0, 0xB9, 0x82, 0xE0, 0xB8, 0x95, 0xE0, 0xB9, 0x80, 0xE0, 0xB8, 0xAB, 0xE0, 0xB8, 0xA5, 0xE0,
                0xB8, 0xB7, 0xE0, 0xB8, 0xAD, 0xE0, 0xB9, 0x80, 0xE0, 0xB8, 0x81, 0xE0, 0xB8, 0xB4, 0xE0, 0xB8, 0x99 },
            new byte[] { 0xE0, 0xB8, 0xA5, 0xE0, 0xB8, 0x9A }, new byte[] { 43 }, new byte[] { 0xE0, 0xB9, 0x84, 0xE0, 0xB8, 0xA1, 0xE0, 0xB9, 0x88, 0xE0, 0xB9,
                0x83, 0xE0, 0xB8, 0x8A, 0xE0, 0xB9, 0x88, 0xE0, 0xB8, 0x95, 0xE0, 0xB8, 0xB1, 0xE0, 0xB8, 0xA7, 0xE0, 0xB9, 0x80, 0xE0, 0xB8, 0xA5, 0xE0, 0xB8, 0x82 },
            new byte[] { 69 }, new byte[] { 101 },
        };

        public class ThaiSymbolTable : SymbolTable
        {
            public ThaiSymbolTable() : base(s_thaiUtf8DigitsAndSymbols) { }

            public override bool TryEncode(byte utf8, Span<byte> destination, out int bytesWritten)
                => SymbolTable.InvariantUtf8.TryEncode(utf8, destination, out bytesWritten);

            public override bool TryEncode(ReadOnlySpan<byte> utf8, Span<byte> destination, out int bytesConsumed, out int bytesWritten)
                => SymbolTable.InvariantUtf8.TryEncode(utf8, destination, out bytesConsumed, out bytesWritten);

            public override bool TryParse(ReadOnlySpan<byte> source, out byte utf8, out int bytesConsumed)
                => SymbolTable.InvariantUtf8.TryParse(source, out utf8, out bytesConsumed);

            public override bool TryParse(ReadOnlySpan<byte> source, Span<byte> utf8, out int bytesConsumed, out int bytesWritten)
                => SymbolTable.InvariantUtf8.TryParse(source, utf8, out bytesConsumed, out bytesWritten);
        }

        public static SymbolTable ThaiTable = new ThaiSymbolTable();
    }
}


text:
import path = require('path');
import sign = require('azure-pipelines-tasks-ios-signing-common/ios-signing-common');
import secureFilesCommon = require('azure-pipelines-tasks-securefiles-common/securefiles-common');
import tl = require('azure-pipelines-task-lib/task');
import os = require('os');

async function run() {
    let secureFileId: string;
    let secureFileHelpers: secureFilesCommon.SecureFileHelpers;

    try {
        tl.setResourcePath(path.join(__dirname, 'task.json'));

        // Check platform is macOS since demands are not evaluated on Hosted pools
        if (os.platform() !== 'darwin') {
            throw new Error(tl.loc('InstallRequiresMac'));
        }

        if (tl.getInput('provisioningProfileLocation') === 'sourceRepository') {
            let provProfilePath: string = tl.getInput('provProfileSourceRepository', true);

            if (tl.filePathSupplied('provProfileSourceRepository') && tl.exist(provProfilePath) && tl.stats(provProfilePath).isFile()) {
                const info = await sign.installProvisioningProfile(provProfilePath);
                tl.setTaskVariable('APPLE_PROV_PROFILE_UUID', info.provProfileUUID);

                // set the provisioning profile output variable.
                tl.setVariable('provisioningProfileUuid', info.provProfileUUID);
                tl.setVariable('provisioningProfileName', info.provProfileName);

                // Set the legacy variable that doesn't use the task's refName, unlike our output variables.
                // If there are multiple InstallAppleCertificate tasks, the last one wins.
                tl.setVariable('APPLE_PROV_PROFILE_UUID', info.provProfileUUID);
            } else {
                throw tl.loc('InputProvisioningProfileNotFound', provProfilePath);
            }
        }

    } catch (err) {
        tl.setResult(tl.TaskResult.Failed, err);
    }
}

run();


text:
class CreateProgresses < ActiveRecord::Migration
  def change
    create_table :progresses do |t|
      t.string :name
      t.float :start
      t.float :current
      t.float :end
      t.boolean :stop
      t.boolean :finished

      t.timestamps
    end
    add_index :progresses, :name
  end
end


text:
@interface ChangeSkinTableViewController : BaseTableViewController

@end


text:
'use strict';

var envFactory = require('../..');
var t = require('chai').assert;
var _ = require('lodash');

describe('.getOrElseAll', function() {
  var env;
  var eventsFound = {};
  var eventsFallback = {};

  beforeEach(function() {
    env = envFactory();
    env
      .on(env.EVENT_FOUND, function(fullKeyName, value) {
        eventsFound[fullKeyName] = value;
      })
      .on(env.EVENT_FALLBACK, function(fullKeyName, $default) {
        eventsFallback[fullKeyName] = $default;
      });
    process.env = {};
    process.env.AMQP_LOGIN = 'plop';
    process.env.AMQP_GOOD_PORT = 10;
    process.env.AMQP_CONNECT = 'tRue';
    process.env.AMQP_CONNECT2 = 'false';
    process.env.AMQP_PASSWORD = '';
    process.env.A_B_C_DOVERRIDE = '2,3,4';
    process.env.MY_AWESOME_ARRAY_ALIASE_D = '5,7,8';
  });

  it('should emit events', function(done) {
    var doneAfterTwoCall = _.after(2, done);
    env
      .on(env.EVENT_FOUND, function(fullKeyName, value) {
        console.log('[env] %s was defined, using: %s', fullKeyName, String(value));
        doneAfterTwoCall();
      })
      .on(env.EVENT_FALLBACK, function(fullKeyName, $default) {
        console.log('[env] %s was not defined, using default: %s', fullKeyName, String($default));
        doneAfterTwoCall();
      })
      .getOrElseAll({
        node: {
          env: 'production'
        },
        a: {
          b: 'ok'
        }
      });
  });

  it('should return an object', function() {
    var config = env.getOrElseAll({
      AMQP: {
        LoGiN: 'guest', // add a bug inside key name (mix lower/upper case)
        PASSWORD: 'guest',
        HOST: 'localhost',
        PORT: 5672,
        connect: false,
        connect2: true,
        PLOP: {
          ok: {
            heyheyhey: true
          }
        },
        exchanges: [
          {
            name: 'exchange.one',
            type: 'topic',
            durable: true
          }, {
            name: 'exchange.one.dead',
            type: 'topic',
            durable: true
          }
        ]
      },

      a: {
        b: {
          c: {
            d: [1, 2, 3],
            dOverride: [1, 2, 3],
            dAliases: {
              $default: [1, 2, 3],
              $aliases: ['MY_AWESOME_ARRAY_ALIASE_D']
            },

            e: [true, false, true],
            eOverride: [false, true, false],
            eAliases: {
              $default: [true, false, true],
              $aliases: ['MY_AWESOME_ARRAY_ALIASE_E']
            },

            f: ['a', 'c', 'd'],
            fOverride: ['h', 'e', 'l', 'l', 'o'],
            fAliases: {
              $default: ['a', 'c', 'd'],
              $aliases: ['MY_AWESOME_ARRAY_ALIASE_F']
            },
          }
        }
      },

      c: {
        PORT: 8080,
        root: ''
      },

      MICROSTATS: {
        HASHKEY: 'B:mx:global'
      }
    });

    t.strictEqual(config.AMQP.LoGiN, 'plop');
    t.strictEqual(config.AMQP.PASSWORD, '');
    t.strictEqual(config.AMQP.PORT, 5672);
    t.strictEqual(config.AMQP.PLOP.ok.heyheyhey, true);
    t.strictEqual(config.AMQP.connect, true);
    t.strictEqual(config.AMQP.connect2, false);
    t.deepEqual(config.AMQP.exchanges, [
      {
        name: 'exchange.one',
        type: 'topic',
        durable: true
      }, {
        name: 'exchange.one.dead',
        type: 'topic',
        durable: true
      }
    ]);

    t.deepEqual(config.a.b.c.f, ['a', 'c', 'd']);
    t.deepEqual(config.a.b.c.fOverride, 'hello'.split(''));

    t.deepEqual(config.a.b.c.d, [1, 2, 3]);
    t.deepEqual(config.a.b.c.dOverride, [2, 3, 4]);
    t.deepEqual(config.a.b.c.dAliases, [5, 7, 8]);

    t.deepEqual(config.a.b.c.e, [true, false, true]);
    t.deepEqual(config.a.b.c.eOverride, [false, true, false]);

    t.strictEqual(config.c.root, '');
  });

  it('should return ask for ENV vars', function() {
    env.getOrElseAll({
      plop: {
        root_token: 'sdfopiqjsdfpoij',
        api: {
          endpoint_protocol: 'https',
          endpoint_host: 'sqdfqsdf.cleverapps.io',
          endpoint_port: ''
        },
        strategy: 'https://strategy.plop.net',
      }
    });

    t.ok(_.has(eventsFallback, 'PLOP_ROOT_TOKEN'), 'PLOP_ROOT_TOKEN');
    t.ok(_.has(eventsFallback, 'PLOP_API_ENDPOINT_PORT'), 'PLOP_API_ENDPOINT_PORT');
  });

  describe('ENV vars as array handling', () =>  {
    it('should handle array of plain objects', function() {
      process.env['ARRAYWITHOBJECT_API__0_A'] = 3;
      process.env['ARRAYWITHOBJECT_API__2_A'] = 1;

      var config = env.getOrElseAll({
        arrayWithObject: {
          api: [{
            a: 1
            }, {
            a: 2
            }]
        }
      });
      t.strictEqual(config.arrayWithObject.api[0].a, 3, 'config.arrayWithObject.api[0].a');
      t.strictEqual(config.arrayWithObject.api[1].a, 2, 'config.arrayWithObject.api[1].a');
      t.strictEqual(config.arrayWithObject.api[2].a, 1, 'config.arrayWithObject.api[2].a');

      t.ok(_.has(eventsFound, 'ARRAYWITHOBJECT_API__0_A'), 'ARRAYWITHOBJECT_API__0_A should have been found');
      t.ok(_.has(eventsFallback, 'ARRAYWITHOBJECT_API__1_A'), 'ARRAYWITHOBJECT_API__1_A should have NOT been found');
      t.ok(_.has(eventsFound, 'ARRAYWITHOBJECT_API__2_A'), 'ARRAYWITHOBJECT_API__2_A should have been found');
    });

    it('should handle an array of objects with description objects', function() {
      process.env['ARRAYWITHOBJECT_API__0_INT'] = 3;
      process.env['ARRAYWITHOBJECT_API__1_A'] = 2;
      process.env['ARRAYWITHOBJECT_API__2_INT'] = 1;

      var config = env.getOrElseAll({
        arrayWithObject: {
          api: [{
            int: {
              $default: 2,
              $type: env.types.Integer
            },
            a: 1
          }]
        }
      });

      if (!config.arrayWithObject.api[0].int) {
        // for debug only
        console.log(config.arrayWithObject.api);
      }
      t.strictEqual(config.arrayWithObject.api[0].int, 3, 'config.arrayWithObject.api[0].int');
      t.strictEqual(config.arrayWithObject.api[1].int, 2, 'config.arrayWithObject.api[1].int');
      t.strictEqual(config.arrayWithObject.api[1].a, 2, 'config.arrayWithObject.api[1].a');
      t.strictEqual(config.arrayWithObject.api[2].int, 1, 'config.arrayWithObject.api[2].int');
      t.ok(_.has(eventsFound, 'ARRAYWITHOBJECT_API__0_INT'), 'ARRAYWITHOBJECT_API__0_INT should have been found');
      t.ok(_.has(eventsFallback, 'ARRAYWITHOBJECT_API__1_INT'), 'ARRAYWITHOBJECT_API__1_INT should have NOT been found');
      t.ok(_.has(eventsFound, 'ARRAYWITHOBJECT_API__2_INT'), 'ARRAYWITHOBJECT_API__2_INT should have been found');
    });

    it('should throw an error handle array of description objects objects', function() {
      t.throws(() => {
        env.getOrElseAll({
          arrayWithObject: {
            api: [{
              $default: 2,
              $type: env.types.Integer
            }]
          }
        });
      }, 'CommonEnvRootConfigurationObjectException: ARRAYWITHOBJECT_API__0_');
    });
  });

  describe('$aliases handling', function() {
    it('should handle $default object value', function() {
      var config = env.getOrElseAll({
        a: {
          b: [{
            a: {
              $default: 'heyheyhey',
              $aliases: ['BLABLA_BLABLA', 'AMQP_LOGIN']
            }
          }, {
            a: {
              $default: 'plop2',
              $aliases: ['BLABLA_BLABLA'] // `BLABLA_BLABLA` does not exist, it should fallback on "plop"
            }
          }]
        },
        b: {
          $default: 10,
          $aliases: ['BLABLA_BLABLA', 'AMQP_GOOD_PORT', 'BLABLA_BLABLA']
        }
      });
      t.strictEqual(config.a.b[0].a, 'plop', 'should use AMQP_LOGIN value');
      t.ok(_.has(eventsFound, 'AMQP_LOGIN'), 'AMQP_LOGIN should be printed');

      t.strictEqual(config.b, 10);
      t.ok(_.has(eventsFound, 'AMQP_GOOD_PORT'), 'A_B[1]_A was defined should be printed');
    });

    it('should handle $default object value and fallback on default value', function() {
      var config = env.getOrElseAll({
        a: {
          b: [{
            a: {
              $default: 'plop2',
              $aliases: ['BLABLA_BLABLA'] // `BLABLA_BLABLA` does not exist, it should fallback on "plop"
            }
          }]
        }
      });
      t.strictEqual(config.a.b[0].a, 'plop2');
      t.ok(_.has(eventsFallback, 'A_B__0_A'), 'A_B__0_A was not defined should be printed');
    });

    describe('if $type was specified', function() {
      const env = envFactory();
      const tests = [
        {
          converter: env.types.Integer,
          val: '10',
          converted: 10
        }, {
          converter: env.types.Integer,
          val: '102039.23',
          converted: Error // because the value should be an integer
        }, {
          converter: env.types.Float,
          val: '10',
          converted: 10
        }, {
          converter: env.types.Float,
          val: '1.1',
          converted: 1.1
        }, {
          converter: env.types.Float,
          val: '102039.23',
          converted: 102039.23
        }, {
          converter: env.types.Float,
          val: 'aaa',
          converted: Error
        }, {
          converter: env.types.Boolean,
          val: 'true',
          converted: true
        }, {
          converter: env.types.Boolean,
          val: 'false',
          converted: false
        }, {
          converter: env.types.Boolean,
          val: 'TRUE',
          converted: true
        }, {
          converter: env.types.Boolean,
          val: 'oskdoskd',
          converted: Error
        }, {
          converter: env.types.String,
          val: 'string',
          converted: 'string'
        }, {
          converter: env.types.String,
          val: undefined,
          converted: Error
        }, {
          converter: env.types.Array(env.types.String),
          val: 'a,b,c,d',
          converted: ['a', 'b', 'c', 'd']
        }, {
          converter: env.types.Array(env.types.String),
          val: 'a',
          converted: ['a']
        }, {
          converter: env.types.Array(env.types.Integer),
          val: '1,2,3,4',
          converted: [1, 2, 3, 4]
        }, {
          converter: env.types.Array(env.types.Integer),
          val: '1',
          converted: [1]
        },{
          converter: env.types.Array(env.types.Integer),
          val: 'a,a',
          converted: Error
        }, {
          converter: env.types.Array(env.types.Float),
          val: '1,2.2,3,4.4',
          converted: [1, 2.2, 3, 4.4]
        }, {
          converter: env.types.Array(env.types.Float),
          val: '1.1',
          converted: [1.1]
        }, {
          converter: env.types.Array(env.types.Boolean),
          val: 'true,false,true,TRUE',
          converted: [true, false, true, true]
        }, {
          converter: env.types.Array(env.types.Boolean),
          val: 'true',
          converted: [true]
        }
      ].map(function(test) {
        return _.extend({}, {
          varName: (test.converter._name.toUpperCase() + '_' + test.val).replace('.', '_')
        }, test);
      });

      // ensure environment variables does not clash between them
      it('should have unique vairables names', function() {
        t.deepEqual(_.map(tests, 'varName'), _.chain(tests).map('varName').uniq().value());
      });

      beforeEach(function() {
        _.forEach(tests, function(v) {
          process.env[v.varName] = v.val;
        });
      });

      afterEach(function() {
        _.forEach(tests, function(v) {
          delete process.env[v.varName];
        });
      });

      _.forEach(tests, function(v) {
        describe('converter ' + v.converter._name + ' with value ' + JSON.stringify(v.val), function() {
          it('should be defined as a function', function() {
            t.ok(_.isFunction(v.converter), v.converter._name + ' should be a function');
          });

          if (v.converted === Error) {
            it('should throw an error when the converter ' + v.converter._name + ' does not receive a good value (e.g. with ' + v.val + ')', function() {

              t.throws(function() {
                env.getOrElseAll({
                  a: {
                    $type: v.converter,
                    $aliases: [v.varName]
                  }
                });
              });
            });
            return;
          }

          it('should handle ' + v.converter._name + ' converter as $type (e.g. with ' + JSON.stringify(v.val) + ')', function() {
            var config = env.getOrElseAll({
              a: {
                $type: v.converter,
                $aliases: [v.varName]
              }
            });

            t.deepEqual(config.a, v.converted);
          });

          it('should handle ' + v.converter._name + ' converter as $type (e.g. with ' + JSON.stringify(v.val) + ') whithout $aliases', function() {
            process.env.B = v.val;

            var config = env.getOrElseAll({
              b: {
                $type: v.converter
              }
            });

            delete process.env.B;

            t.deepEqual(config.b, v.converted);
          });
        });

      });

      it('throws an error if `itemConverter` was not a function', () => {
        t.throw(() => {
          env.getOrElseAll({
            a:{
              $type: env.types.Array('plop')
            }
          });
        });
      });
    });
  });

  describe('fail-fast behaviour', function() {
    it('should throw an error  $aliases was defined without nothing else', function() {
      t.throws(function() {
        env.getOrElseAll({
          thisIsA: {
            missing: [{
              sadVar: {
                $aliases: ['MISSING_VAR_' + (+new Date()), 'MISSING_VAR_2' + (+new Date())]
              }
            }]
          }
        });
      }, env.CommonEnvInvalidConfiguration);
    });

    it('should throw an error if aliases is not an array', function() {
      t.throws(function() {
        env.getOrElseAll({
          thisIsA: {
            missing: [{
              sadVar: {
                $default: 10,
                $aliases: null
              }
            }]
          }
        });
      }, Error);
    });

    it('should throw an error if $default is not defined and that no environment variables was specified', function() {
      t.throws(function() {
        env.getOrElseAll({
          thisIsA: {
            missing: [{
              sadVar: {
                $type: env.types.Float,
                $aliases: ['MISSING_VAR_' + (+new Date()), 'MISSING_VAR_2' + (+new Date())]
              }
            }]
          }
        });
      }, env.CommonEnvGetOrDieAliasesException);
    });
  });

  afterEach(function() {
    delete process.env.AMQP_LOGIN;
    delete process.env.AMQP_CONNECT;
    delete process.env.AMQP_CONNECT2;
    delete process.env.AMQP_GOOD_PORT;
    delete process.env['PLOP_API[0]_A'];
  });
});


text:
<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="msapplication-tap-highlight" content="no">

		<link rel="icon" href="<?php echo base_url('assets/images/favicon-32x32.png')?>" sizes="32x32">
		<link rel="apple-touch-icon-precomposed" href="<?php echo base_url('assets/images/favicon/apple-touch-icon-152x152.png')?>">
		<meta name="msapplication-TileColor" content="#00bcd4">
		<meta name="msapplication-TileImage" content="<?php echo base_url('assets/images/favicon/mstile-144x144.png')?>">
		<link href="<?php echo base_url('assets/materialize/css/materialize.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/css/style.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/css/custom-style.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/js/plugins/perfect-scrollbar/perfect-scrollbar.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/js/plugins/jvectormap/jquery-jvectormap.css')?>" type="text/css?>" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/js/plugins/chartist-js/chartist.min.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/js/plugins/chartist-js/chartist.min.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/materialize/js/plugins/fullcalendar/css/fullcalendar.min.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/materialize/crop/imgareaselect-default.css" />

		<link href="<?php echo base_url('assets/materialize/js/plugins/data-tables/css/jquery.dataTables.min.css')?>" type="text/css" rel="stylesheet" media="screen,projection">
		<link href="<?php echo base_url('assets/jquery-ui/jquery-ui.css')?>" rel="stylesheet" type="text/css" />

<a href="<?php echo base_url('student/profile')?>">Profile

Settings

Help

			<?php if($this->ion_auth->in_group('admin')||$this->ion_auth->in_group('cod')){ ?>

<a href="<?php echo base_url('/student')?>">Stud

<a href="<?php echo base_url('/cod')?>">COD

				<?php if($this->ion_auth->in_group('admin')){ ?>

<a href="<?php echo base_url('/admin')?>">Admin

				<?php } ?>
			<?php } ?>

<a href="<?php echo base_url('auth/logout')?>">Logout

<a href="<?php echo base_url('student/deactivate_req')?>">Deactivate account

<a href="<?php echo base_url('/student');?>" class="brand-logo darken-1">CMS

									<a href="<?php echo base_url('student/upload/upload_photo')?>" style="display:inline;">
										<img src="<?php if (file_exists('./assets/stud_uploads/'.$id.'.jpg')){echo base_url('assets/stud_uploads/'.$id.'.jpg');} else {echo base_url('assets/materialize/images/avatar.jpg');}?>" alt="" class="circle responsive-img valign profile-image">

<a href="<?php echo base_url('student/profile')?>">Profile

Settings

<a href="<?php echo base_url('/student/stud_help')?>">Help

									<?php if($this->ion_auth->in_group('admin')||$this->ion_auth->in_group('cod')){ ?>

<a href="<?php echo base_url('/student')?>">Stud

                                    <?php if($this->ion_auth->in_group('wsdc_cod')||$this->ion_auth->in_group('mess_cod')||$this->ion_auth->in_group('water_cod')||$this->ion_auth->in_group('lan_cod')){ ?>

<a href="<?php echo base_url('/cod')?>">COD

                                    <?php } ?>
                                    <?php if($this->ion_auth->in_group('admin')){ ?>

<a href="<?php echo base_url('/admin')?>"> Admin

                                    <?php } ?>
                                    <?php } ?>

<a href="<?php echo base_url('auth/logout')?>">Logout

<a href="<?php echo base_url('/student/complain_submit')?>" class="waves-effect waves-cyan">Submit Complaint

<a href="<?php echo base_url('/student/complain_status')?>" class="waves-effect waves-cyan">My Complains

<a href="<?php echo base_url('/student/companies');?>" class="waves-effect waves-cyan">All Complains

<a href="<?php echo base_url('/student/feedback_list')?>" class="waves-effect waves-cyan">Feedback