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

<!--
Copyright 2014-2015 Grzegorz Slowikowski (gslowikowski at gmail dot com)

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.scoverage.scoverage-maven-samples.play</groupId>
        <artifactId>multimodule</artifactId>
        <version>1.0.5-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.scoverage.scoverage-maven-samples.play.multimodule</groupId>
    <artifactId>admin</artifactId>
    <packaging>play2</packaging>

    <name>SCoverage Maven Samples : Play! Framework : MultiModule : Admin</name>

    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${scala.version}</version>
        </dependency>

        <dependency>
            <groupId>com.typesafe.play</groupId>
            <artifactId>play_2.10</artifactId>
            <version>${play2.version}</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>${basedir}/app</sourceDirectory>
        <testSourceDirectory>${basedir}/test</testSourceDirectory>
        <resources>
            <resource>
                <directory>${basedir}/conf</directory>
            </resource>
            <resource>
                <directory>${basedir}/public</directory>
                <targetPath>public</targetPath>
            </resource>
        </resources>
        <!--<outputDirectory>target/scala-2.10/classes</outputDirectory>-->

        <plugins>
            <plugin>
                <groupId>com.google.code.play2-maven-plugin</groupId>
                <artifactId>play2-maven-plugin</artifactId>
                <extensions>true</extensions>
            </plugin>

            <plugin>
                <groupId>org.scoverage</groupId>
                <artifactId>scoverage-maven-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
import {Record} from 'immutable';

import RemoteColection from './RemoteCollection';

export default Record(
  {
    courses: new RemoteColection(),
  },
  'GoogleClassroom',
);

redpajama_set_name: RedPajamaGithub


text:
layout: post
comments: true
title: Pirmasis pokalbis dėl programavimo darbo - kaip jis gali atrodyti?
excerpt_separator: <!--more-->
---

Savo dar trumpos programuotojos karjeros metu jau patyriau du pokalbius dėl darbo, ir jie abu buvo labai skirtingi. Iš šios nedidelės patirties
bei pokalbių su kitais programuotojais susidariau įspūdį, jog dažniausiai pasitaikančios interviu formos yra techninis ir motyvacinis/kultūrinis pokalbiai.
Šiame straipsnyje aptarsiu keletą strategijų, kaip jiems pasirengti.

<!--more-->

Pokalbis dėl darbo, ypač techninis, yra gana baisus dalykas. Jo metu bus atskleistos tavo žinių spragos ne tik tavo pokalbio partneriui, bet
ir tau pačiai. Be to, kaip pradedančioji programuotoja tu ir taip gana miglotai suvoki kai kuriuos programavimo dalykus, o ką jau kalbėti apie
rišlų tų dalykų paaiškinimą.

Tokiam pokalbiui išties nelengva pasiruošti. Žinai, ką žinai. Tačiau čia nereiktų nuleisti rankų. Visgi, gali tikėtis, jog tavęs bus klausiama
standartinių dalykų. O kokie tie standartiniai dalykai tavo programavimo kalboje, gali lengvai *pasigūglinti*.

Taip pat siūlyčiau nebijoti atvirai pasakyti, jog tu kažko nežinai, kadangi mokymosi metu su tokia problema neteko susidurti. Taip pat
nebijok paklausti, ką reiškia tas ar kitas konceptas - taip ir pati daugiau sužinosi, ir parodysi savo smalsumą bei norą mokytis. Reikia
 nepamiršti, jog techninis pokalbis nebūtinai tikrina tik tavo technines žinias, bet ir tai, kaip tu reaguoji į netikėtas situacijas, ir
 bendrus komunikacijos įgūdžius. Ar su tavimi smagu kalbėtis? Juk dažnai tie, kurie veda pokalbį, dirbtų su tavimi. O dirbti visada smagiau su
 tokiu žmogumi, kuris geba lengvai bendrauti.

Techninio pokalbio metu gali tekti atlikti keletą užduočių - dažniausiai ant popieriaus. Visko nežinosi, ypač gali pasimiršti tiksli sintaksė.
Tokiu atveju tiesiog rašyk pseudo-kodą - taip parodysi, kaip tu mąstai.

Tokį pokalbį patyriau, kai aplikavau dėl praktikos atlikimo. Mano techninės žinios buvo tikrinamos visą valandą. Aš labai daug ko nežinojau, tačiau
pokalbio metu tvyrojo gera atmosfera, todėl galėjau atsipalaiduoti (kiek tai įmanoma tokioje situacijoje :)). Jei per pokalbį nėra sudaryta draugiška
atmosfera, gerai pagalvok, ar pati nori ten dirbti.

Antroji mano aukščiau minėta pokalbio forma - motyvacinis/kultūrinis interviu - būdingas tuomet, kai tavęs iš anksto prašo atlikti kažkokią
didesnę užduotį. Tai atskleis tavo turimus techninius įgūdžius, todėl pokalbio metu jų jau nebereikės išsamiai tikrinti. Tiesa, tokio pokalbio
 metu gali tikėtis, jog teks paaiškinti kai kurias kodo vietas. Dėl šios priežasties siūlau prieš pokalbį atidžiai peržiūrėti atliktą
 užduotį ir įsitikinti, jog pati viską ten supranti.

Šio pokalbio metu bus tikrinama tavo motyvacija ir noras tobulėti. Kodėl susidomėjai programavimu? Kaip išmokai programuoti? Kodėl nusprendei
keisti karjerą? Prieš tokį pokalbį pasistenk sau atsakyti į šiuos klausimus. Taip pat gali būti užduodami 'situaciniai' klausimai - kaip elgtumeisi
vienoje ar kitoje situacijoje. Čia bus tikrinamas gebėjimas dirbti komandoje, kadangi to bus nemažai.

Abiejų pokalbių atveju patariu nebijoti pripažinti, jog kažko nežinai. Aš pati buvau nustebusi, kai sužinojau iš labiau patyrusių kolegų, jog
vertinama tai, kaip kandidatas elgtųsi, jei jam kažkas nesigautų programuojant. Ar jis prašytų pagalbos kolegų, ar bandytų pats išsiaiškinti,
nesvarbu, kiek tai truktų?

Gal ir nustebsi (kaip ir aš kad nustebau), tačiau kur kas geriau bus vertinamas tavo noras prašyti pagalbos, nei siekis pačiai atrasti sprendimo
būdą. Taip yra todėl, jog pačiai išspręsti problemą užtruktų kur kas ilgiau, nei pasiklausti labiau patyrusių kolegų, kurie greičiausiai jau
buvo su tuo susidūrę.

Nepamiršk, jog pokalbis yra galimybė tiek darbdaviui įvertinti tavo atitikimą turimai pozicijai, tiek tau įsitikinti, ar tai yra ta įmonė,
kuri patenkins tavo kaip jaunosios programuotojos poreikius. Tau svarbu užsitikrinti, jog darbe turėsi tam tikrą mentorių, kuris galės tau
 suteikti reikiamą pagalbą - o jos neabejotinai prireiks. Paklausk, ar turėsi tokį žmogų, iš kurio galėsi mokytis?

Taip pat pasiteirauk apie naudojamas technologijas - ar tai yra tos technologijos, su kuriomis tu nori dirbti? Jei tau teks dirbti su labai
  senomis technologijomis, gali greitai prarasti motyvaciją, nes visi norime dirbti su moderniais dalykais.

Svarbiausia - žiūrėti į kiekvieną tokį pokalbį kaip į pamoką, ir kažko iš tos pamokos pasiimti. Juk darbo keitimas yra vienas geriausių ir greičiausių
būdų pasikelti atlyginimą, tad labai tikėtina, kad per savo programavimo karjerą teks atlaikyti ne vieną tokį pokalbį.

![Job interview](/assets/job-interview.jpg)

 Gali ir tu turi patirties darbo pokalbiuose dėl programavimo? Dalinkis ja komentaruose!


text:
// A module that queries Universal Data Cube data.
//
// Curran Kelleher 4/9/2014
define([], function () {
  return function (dashboard) {
    var model = new Backbone.Model();
    model.wire(['source', 'dataSet', 'query'], function (source, dataSet, query) {

      // Get the `data` component from the dashboard configuration,
      // which is responsible for loading data sources.
      dashboard.getComponent('data', function (dataComponent) {

        // Extract the UDC context from the `data` component.
        var udc = dataComponent.udc;

        // Wait for the data set to load.
        udc.waitFor(source, dataSet, function () {

          // Query the data cube for the X dimension domain.
          /* TODO refactor the API so (source, dataSet) are not needed */
          var xDomainCodes = udc.getDomain(source, dataSet, query.x),
              xDomainCodeList = udc.getCodeList(source, dataSet, query.x),

              /* TODO generalize handling of X dimensions, special case Time */
              // Parse X dimension domain values into JS Date objects.
              xDomainDates = xDomainCodes.map( function (yearStr) {
                return new Date(yearStr, 0);
              }),
              // Use the `slice` option as the basis for the current cell.
              cell = _.clone(query.slices);

          model.set('result', xDomainCodes.map(function (code, i) {

            // Set the X dimension value for the current cell
            // to the X domain value.
            cell[query.x] = {
              code: code,
              codeList: xDomainCodeList
            };

            // Map X domain objects to data element objects with
            return {

              // * `x` The date corresponding to the X domain value.
              x: xDomainDates[i],

              // * `y` The measure value from the data cube for
              // the current cell and the configured Y measure.
              y: udc.getValue(source, dataSet, cell, query.y)
            };
          }));
        });
      });
    });
    return model;
  };
});


text:
FX_BOOL FX_File_Exist(const CFX_ByteStringC& fileName) {
  FX_DWORD dwAttri = ::GetFileAttributesA(fileName.GetCStr());
  if (dwAttri == -1) {
    return FALSE;
  }
  return (dwAttri & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
FX_BOOL FX_File_Exist(const CFX_WideStringC& fileName) {
  FX_DWORD dwAttri = ::GetFileAttributesW((LPCWSTR)fileName.GetPtr());
  if (dwAttri == -1) {
    return FALSE;
  }
  return (dwAttri & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
IFXCRT_FileAccess* FXCRT_FileAccess_Create() {
  return new CFXCRT_FileAccess_Win64;
}
void FXCRT_Windows_GetFileMode(FX_DWORD dwMode,
                               FX_DWORD& dwAccess,
                               FX_DWORD& dwShare,
                               FX_DWORD& dwCreation) {
  dwAccess = GENERIC_READ;
  dwShare = FILE_SHARE_READ | FILE_SHARE_WRITE;
  if (!(dwMode & FX_FILEMODE_ReadOnly)) {
    dwAccess |= GENERIC_WRITE;
    dwCreation = (dwMode & FX_FILEMODE_Truncate) ? CREATE_ALWAYS : OPEN_ALWAYS;
  } else {
    dwCreation = OPEN_EXISTING;
  }
}
#ifdef __cplusplus
extern "C" {
#endif
WINBASEAPI BOOL WINAPI GetFileSizeEx(HANDLE hFile, PLARGE_INTEGER lpFileSize);
WINBASEAPI BOOL WINAPI SetFilePointerEx(HANDLE hFile,
                                        LARGE_INTEGER liDistanceToMove,
                                        PLARGE_INTEGER lpNewFilePointer,
                                        DWORD dwMoveMethod);
#ifdef __cplusplus
}
#endif
CFXCRT_FileAccess_Win64::CFXCRT_FileAccess_Win64() : m_hFile(NULL) {}
CFXCRT_FileAccess_Win64::~CFXCRT_FileAccess_Win64() {
  Close();
}
FX_BOOL CFXCRT_FileAccess_Win64::Open(const CFX_ByteStringC& fileName,
                                      FX_DWORD dwMode) {
  if (m_hFile) {
    return FALSE;
  }
  FX_DWORD dwAccess, dwShare, dwCreation;
  FXCRT_Windows_GetFileMode(dwMode, dwAccess, dwShare, dwCreation);
  m_hFile = ::CreateFileA(fileName.GetCStr(), dwAccess, dwShare, NULL,
                          dwCreation, FILE_ATTRIBUTE_NORMAL, NULL);
  if (m_hFile == INVALID_HANDLE_VALUE) {
    m_hFile = NULL;
  }
  return m_hFile != NULL;
}
FX_BOOL CFXCRT_FileAccess_Win64::Open(const CFX_WideStringC& fileName,
                                      FX_DWORD dwMode) {
  if (m_hFile) {
    return FALSE;
  }
  FX_DWORD dwAccess, dwShare, dwCreation;
  FXCRT_Windows_GetFileMode(dwMode, dwAccess, dwShare, dwCreation);
  m_hFile = ::CreateFileW((LPCWSTR)fileName.GetPtr(), dwAccess, dwShare, NULL,
                          dwCreation, FILE_ATTRIBUTE_NORMAL, NULL);
  if (m_hFile == INVALID_HANDLE_VALUE) {
    m_hFile = NULL;
  }
  return m_hFile != NULL;
}
void CFXCRT_FileAccess_Win64::Close() {
  if (!m_hFile) {
    return;
  }
  ::CloseHandle(m_hFile);
  m_hFile = NULL;
}
void CFXCRT_FileAccess_Win64::Release() {
  delete this;
}
FX_FILESIZE CFXCRT_FileAccess_Win64::GetSize() const {
  if (!m_hFile) {
    return 0;
  }
  LARGE_INTEGER size = {};
  if (!::GetFileSizeEx(m_hFile, &size)) {
    return 0;
  }
  return (FX_FILESIZE)size.QuadPart;
}
FX_FILESIZE CFXCRT_FileAccess_Win64::GetPosition() const {
  if (!m_hFile) {
    return (FX_FILESIZE)-1;
  }
  LARGE_INTEGER dist = {};
  LARGE_INTEGER newPos = {};
  if (!::SetFilePointerEx(m_hFile, dist, &newPos, FILE_CURRENT)) {
    return (FX_FILESIZE)-1;
  }
  return (FX_FILESIZE)newPos.QuadPart;
}
FX_FILESIZE CFXCRT_FileAccess_Win64::SetPosition(FX_FILESIZE pos) {
  if (!m_hFile) {
    return (FX_FILESIZE)-1;
  }
  LARGE_INTEGER dist;
  dist.QuadPart = pos;
  LARGE_INTEGER newPos = {};
  if (!::SetFilePointerEx(m_hFile, dist, &newPos, FILE_BEGIN)) {
    return (FX_FILESIZE)-1;
  }
  return (FX_FILESIZE)newPos.QuadPart;
}
size_t CFXCRT_FileAccess_Win64::Read(void* pBuffer, size_t szBuffer) {
  if (!m_hFile) {
    return 0;
  }
  size_t szRead = 0;
  if (!::ReadFile(m_hFile, pBuffer, (DWORD)szBuffer, (LPDWORD)&szRead, NULL)) {
    return 0;
  }
  return szRead;
}
size_t CFXCRT_FileAccess_Win64::Write(const void* pBuffer, size_t szBuffer) {
  if (!m_hFile) {
    return 0;
  }
  size_t szWrite = 0;
  if (!::WriteFile(m_hFile, pBuffer, (DWORD)szBuffer, (LPDWORD)&szWrite,
                   NULL)) {
    return 0;
  }
  return szWrite;
}
size_t CFXCRT_FileAccess_Win64::ReadPos(void* pBuffer,
                                        size_t szBuffer,
                                        FX_FILESIZE pos) {
  if (!m_hFile) {
    return 0;
  }
  if (pos >= GetSize()) {
    return 0;
  }
  if (SetPosition(pos) == (FX_FILESIZE)-1) {
    return 0;
  }
  return Read(pBuffer, szBuffer);
}
size_t CFXCRT_FileAccess_Win64::WritePos(const void* pBuffer,
                                         size_t szBuffer,
                                         FX_FILESIZE pos) {
  if (!m_hFile) {
    return 0;
  }
  if (SetPosition(pos) == (FX_FILESIZE)-1) {
    return 0;
  }
  return Write(pBuffer, szBuffer);
}
FX_BOOL CFXCRT_FileAccess_Win64::Flush() {
  if (!m_hFile) {
    return FALSE;
  }
  return ::FlushFileBuffers(m_hFile);
}
FX_BOOL CFXCRT_FileAccess_Win64::Truncate(FX_FILESIZE szFile) {
  if (SetPosition(szFile) == (FX_FILESIZE)-1) {
    return FALSE;
  }
  return ::SetEndOfFile(m_hFile);
}
FX_BOOL FX_File_Delete(const CFX_ByteStringC& fileName) {
  return ::DeleteFileA(fileName.GetCStr());
}
FX_BOOL FX_File_Delete(const CFX_WideStringC& fileName) {
  return ::DeleteFileW((LPCWSTR)fileName.GetPtr());
}
FX_BOOL FX_File_Copy(const CFX_ByteStringC& fileNameSrc,
                     const CFX_ByteStringC& fileNameDst) {
  return ::CopyFileA(fileNameSrc.GetCStr(), fileNameDst.GetCStr(), FALSE);
}
FX_BOOL FX_File_Copy(const CFX_WideStringC& fileNameSrc,
                     const CFX_WideStringC& fileNameDst) {
  return ::CopyFileW((LPCWSTR)fileNameSrc.GetPtr(),
                     (LPCWSTR)fileNameDst.GetPtr(), FALSE);
}
FX_BOOL FX_File_Move(const CFX_ByteStringC& fileNameSrc,
                     const CFX_ByteStringC& fileNameDst) {
  return ::MoveFileA(fileNameSrc.GetCStr(), fileNameDst.GetCStr());
}
FX_BOOL FX_File_Move(const CFX_WideStringC& fileNameSrc,
                     const CFX_WideStringC& fileNameDst) {
  return ::MoveFileW((LPCWSTR)fileNameSrc.GetPtr(),
                     (LPCWSTR)fileNameDst.GetPtr());
}
#endif


text:
<?php

namespace TestSupport\Service;

use TestSupport\Helper\TestSupportAccessTokenManager;
use DvsaCommon\Constants\Role;
use Zend\View\Model\JsonModel;

class SchemeManagerService
{
    /**
     * @var AccountDataService
     */
    protected $accountDataService;

    public function __construct(AccountDataService $accountDataService)
    {
        $this->accountDataService = $accountDataService;
    }

    /**
     * Create a Scheme Manager with the data supplied.
     *
     * @param array $data
     *
     * @return JsonModel
     */
    public function create(array $data)
    {
        TestSupportAccessTokenManager::addSchemeManagerAsRequestorIfNecessary($data);
        $resultJson = $this->accountDataService->create($data, Role::DVSA_SCHEME_MANAGEMENT);
        $this->accountDataService->addRole($resultJson->data['personId'], Role::DVSA_SCHEME_MANAGEMENT);

        return $resultJson;
    }
}


text:
title: EMPOWER-2
articlename: >-
  Comparison of Pharmacy Claims and Electronic Pill Bottles for Measurement of
  Medication Adherence Among Myocardial Infarction Patients.
date: '2018-07-24'
summary: >-
  Pharmacy claims data provide useful but not complete data for medication
  adherence monitoring. New wireless technologies have the potential to provide
  additional data about clinical outcomes.
authors: >-
  Mehta SJ, Asch DA, Troxel AB, Lim R, Lewey J, Wang W, Zhu J, Norton L, Marcus
  N, Volpp KG.
source: 'https://www.ncbi.nlm.nih.gov/pubmed/30045159'
journal: Med Care
---


text:
package org.intellij.plugins.markdown.lang.references;

import com.intellij.openapi.paths.PathReferenceManager;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.*;
import com.intellij.util.ProcessingContext;
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile;
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkDestinationImpl;
import org.jetbrains.annotations.NotNull;

import static com.intellij.patterns.PlatformPatterns.psiElement;
import static com.intellij.patterns.PlatformPatterns.psiFile;

public class MarkdownReferenceProvider extends PsiReferenceContributor {
  @Override
  public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    final PsiElementPattern.Capture<MarkdownLinkDestinationImpl> linkDestinationCapture =
      psiElement(MarkdownLinkDestinationImpl.class).inFile(psiFile(MarkdownFile.class));

    registrar.registerReferenceProvider(linkDestinationCapture, new LinkDestinationReferenceProvider());
  }

  private static class LinkDestinationReferenceProvider extends PsiReferenceProvider {
    @Override
    public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
      return PathReferenceManager.getInstance().createReferences(element, false, true, true);
    }
  }
}


text:
package com.asakusafw.spark.compiler.planning;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

import com.asakusafw.lang.compiler.common.ComplexAttribute;

/**
 * Extra information for the partitioned sub-plan inputs/outputs.
 */
public class PartitionGroupInfo implements ComplexAttribute {

    private final DataSize dataSize;

    /**
     * Creates a new instance.
     * @param dataSize the data size scale
     */
    public PartitionGroupInfo(DataSize dataSize) {
        this.dataSize = dataSize;
    }

    /**
     * Returns the data size scale of the target partition group.
     * @return the data size scale
     */
    public DataSize getDataSize() {
        return dataSize;
    }

    @Override
    public Map<String, ?> toMap() {
        Map<String, Object> results = new LinkedHashMap<>();
        results.put("dataSize", Util.toLabel(getDataSize())); //$NON-NLS-1$
        return results;
    }

    @Override
    public String toString() {
        return toMap().toString();
    }

    /**
     * Represents data size scale for {@link PartitionGroupInfo}.
     */
    public enum DataSize {

        /**
         * Tiny data-sets.
         */
        TINY,

        /**
         * Small data-sets.
         */
        SMALL,

        /**
         * Regular data-sets.
         */
        REGULAR,

        /**
         * Large data-sets.
         */
        LARGE,

        /**
         * Huge data-sets.
         */
        HUGE,
        ;

        /**
         * Returns whether this is larger than the target one.
         * @param other the target data size
         * @return {@code true} if this is larger than the target, otherwise {@code false}
         */
        public boolean isLargetThan(DataSize other) {
            return this.ordinal() > other.ordinal();
        }

        /**
         * Returns the symbol of this scale.
         * @return the symbol
         */
        public String getSymbol() {
            return name().toLowerCase(Locale.ENGLISH);
        }

        /**
         * Returns the element which has the provided symbol.
         * @param symbol the symbol
         * @return the related element, or {@code null} if there is no such an element
         */
        public static DataSize find(String symbol) {
            return Lazy.SYMBOLS.get(symbol);
        }

        private static final class Lazy {

            static final Map<String, DataSize> SYMBOLS;
            static {
                Map<String, DataSize> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
                for (DataSize element : values()) {
                    map.put(element.getSymbol(), element);
                }
                SYMBOLS = Collections.unmodifiableMap(map);
            }

            private Lazy() {
                return;
            }
        }

    }
}


text:
import random

from rollbar.lib import build_key_matcher, text
from rollbar.lib.transforms import Transform

class ScrubTransform(Transform):
    def __init__(self, suffixes=None, redact_char='*', randomize_len=True):
        super(ScrubTransform, self).__init__()
        self.suffix_matcher = build_key_matcher(suffixes, type='suffix')
        self.redact_char = redact_char
        self.randomize_len = randomize_len

    def in_scrub_fields(self, key):
        return self.suffix_matcher(key)

    def redact(self, val):
        if self.randomize_len:
            _len = random.randint(3, 20)
        else:
            try:
                _len = len(val)
            except:
                _len = len(text(val))

        return self.redact_char * _len

    def default(self, o, key=None):
        if self.in_scrub_fields(key):
            return self.redact(o)

        return o

__all__ = ['ScrubTransform']


text:
.. currentmodule:: gffutils

.. _introduction:

Introduction
============
:mod:`gffutils` is a Python package for working with `GFF
<http://www.sanger.ac.uk/resources/software/gff/spec.htm>`_ and `GTF
<http://mblab.wustl.edu/GTF22.html>`_ files in a hierarchical manner.  It
allows operations which would be complicated or time-consuming using
a text-file-only approach.

Below is a short demonstration of :mod:`gffutils`. For the full documentation,
see :doc:`contents`.

Example file
------------
Consider the first gene on chromosome 2L in *Drosophila melanogaster*, CG11023.
Here is a graphical representation of this gene's three alternative
transcripts, from `FlyBase <http://flybase.org/reports/FBgn0031208.html>`_ :

.. image:: flybase-FBgn0031208.png

:mod:`gffutils` ships with the GFF annotation of this gene, downloaded from
`release 5.54 of FlyBase
<ftp://ftp.flybase.net/genomes/Drosophila_melanogaster/dmel_r5.54_FB2013_06/gff/>`_.
We'll be using it to describe some features of :mod:`gffutils`, because it
contains just enough complexity to be representative of a real-world,
genome-wide GFF file.

Let's look at what the file contains:

>>> import gffutils
>>> fn = gffutils.example_filename('intro_docs_example.gff')
>>> print(open(fn).read()) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	gene	7529	9484	.	+	.	ID=FBgn0031208;Name=CG11023;Ontology_term=SO:0000010,SO:0000087,GO:0016929,GO:0016926,GO:0006508;Dbxref=FlyBase:FBan0011023,FlyBase_Annotation_IDs:CG11023,GB_protein:ACZ94128,GB_protein:AAO41164,GB:AI944728,GB:AJ564667,GB_protein:CAD92822,GB:BF495604,UniProt/TrEMBL:Q86BM6,INTERPRO:IPR003653,GB_protein:AGB92323,UniProt/TrEMBL:M9PAY1,OrthoDB7_Drosophila:EOG796K1P,OrthoDB7_Diptera:EOG7X1604,EntrezGene:33155,UniProt/TrEMBL:E1JHP8,UniProt/TrEMBL:Q6KEV3,OrthoDB7_Insecta:EOG7Q8QM7,OrthoDB7_Arthropoda:EOG7R5K68,OrthoDB7_Metazoa:EOG7D59MP,InterologFinder:33155,BIOGRID:59420,FlyAtlas:CG11023-RA,GenomeRNAi:33155;gbunit=AE014134;derived_computed_cyto=21A5-21A5
2L	FlyBase	mRNA	7529	9484	.	+	.	ID=FBtr0300689;Name=CG11023-RB;Parent=FBgn0031208;Dbxref=REFSEQ:NM_001169365,FlyBase_Annotation_IDs:CG11023-RB;score_text=Strongly Supported;score=11
2L	FlyBase	mRNA	7529	9484	.	+	.	ID=FBtr0300690;Name=CG11023-RC;Parent=FBgn0031208;Dbxref=REFSEQ:NM_175941,FlyBase_Annotation_IDs:CG11023-RC;score_text=Strongly Supported;score=15
2L	FlyBase	mRNA	7529	9484	.	+	.	ID=FBtr0330654;Name=CG11023-RD;Parent=FBgn0031208;Dbxref=FlyBase_Annotation_IDs:CG11023-RD,REFSEQ:NM_001272857;score_text=Strongly Supported;score=11
2L	FlyBase	exon	7529	8116	.	+	.	Name=CG11023:1;Parent=FBtr0300689,FBtr0300690,FBtr0330654;parent_type=mRNA
2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0300689,FBtr0300690;parent_type=mRNA
2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	CDS	7680	8116	.	+	0	Name=CG11023-cds;Parent=FBtr0300689,FBtr0300690;parent_type=mRNA
2L	FlyBase	CDS	7680	8116	.	+	0	Name=CG11023-cds;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	intron	8117	8228	.	+	.	Name=CG11023-in;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	intron	8117	8192	.	+	.	Name=CG11023-in;Parent=FBtr0300689;parent_type=mRNA
2L	FlyBase	intron	8117	8192	.	+	.	Name=CG11023-in;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	exon	8193	9484	.	+	.	Name=CG11023:3;Parent=FBtr0300689;parent_type=mRNA
2L	FlyBase	CDS	8193	8610	.	+	1	Name=CG11023-cds;Parent=FBtr0300689;parent_type=mRNA
2L	FlyBase	CDS	8193	8589	.	+	1	Name=CG11023-cds;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	exon	8193	8589	.	+	.	Name=CG11023:2;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	exon	8229	9484	.	+	.	Name=CG11023:4;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	CDS	8229	8610	.	+	1	Name=CG11023-cds;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	intron	8590	8667	.	+	.	Name=CG11023-in;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300689;parent_type=mRNA
2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	three_prime_UTR	9277	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	exon	8668	9484	.	+	.	Name=CG11023:5;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	CDS	8668	9276	.	+	0	Name=CG11023-cds;Parent=FBtr0300690;parent_type=mRNA
<BLANKLINE>

While this is a (relatively) simple gene, the annotation looks quite complex.
In no particular order, some comments about this annotation:

- The gene has lots of attributes (last column), which would be nice to be able
  to access from Python.

- The gene and mRNA features have "ID" attributes, while UTRs, exons, CDSs, and
  introns only have "Name" attributes, e.g.::

    gene: ID=FBgn0031208;Name=CG11023...
    mRNA: ID=FBtr0300689;Name=CG11023-RB...
    exon: Name=CG11023:1...

- The "Name" attributes of UTRs, exons, CDSs, and introns contain the "Name"
  attribute of the parent gene, followed by some extra info.  For exons, it's
  a colon and a number; for introns its "-in", and so on.  But the "Parent"
  mRNA is indicated with the mRNA's "ID" attribute, e.g.,::

    exon: Name=CG11023:3;Parent=FBtr0300689;

  For routine tasks like counting reads in exons (say, with `HTSeq
  <http://www-huber.embl.de/users/anders/HTSeq/doc/overview.html>`_), it would
  be nice to be able to add a "gene_id" attribute to exons.  That is, change::

    exon: Name=CG11023:3;Parent=FBtr0300689;

  to::

    exon: Name=CG11023:3;Parent=FBtr0300689;gene_id=FBgn0031208;

  Then, we could use `htseq-count` like this::

    htseq-count --type=exon --idattr=gene_id reads.sam fixed_annotation.gff

- UTRs, exons, CDSs, and introns have the same name for different features.
  For example, these two introns have different coordinates and have different
  mRNA parents, yet have the same "Name" attribute::

    2L	FlyBase	intron	8117	8228	.	+	.	Name=CG11023-in;Parent=FBtr0330654;parent_type=mRNA
    2L	FlyBase	intron	8117	8192	.	+	.	Name=CG11023-in;Parent=FBtr0300689;parent_type=mRNA

  It would be nice to have unique IDs for these features so we could
  differentiate them for, say, counting the unique introns of a gene or
  generating a file of splice junctions.

Create the database
-------------------
The first step to working with :mod:`gffutils` is to import the file into
a local sqlite3 file-based database.  The :func:`gffutils.create_db` function
is used for this, and it takes many optional arguments for configuring how to
interpret your GFF or GTF file.

.. doctest::
    :hide:

    from __future__ import print_function

>>> db = gffutils.create_db(fn, dbfn='test.db', force=True, keep_order=True,
... merge_strategy='merge', sort_attribute_values=True)

Here, `force=True` will overwrite any existing database, `keep_order=True`
will maintain the order of the attributes (ID, Name, Parent, and so on), and
`sort_attribute_values=True` will ensure the values of each attribute are
always sorted.  These latter two settings are necessary here for this
documentation (which undergoes automated testing) to have predictable output,
but in general you can gain a speedup by using the default `keep_order=False`
and `sort_attributes_order=False`.

If your input file follows the GFF or GTF file format specifications, this is
all you need to create a database.  But real-world files don't always
completely adhere to the format specifications.  So :mod:`gffutils` provides lots
of configuration options to tailor the pre-processing to your particular file
-- see :doc:`database-import` for more details, and :doc:`examples` for more
practical examples.

Use the database
----------------

Once the database has been created, downstream code can connect to it simply
by:

>>> import gffutils
>>> db = gffutils.FeatureDB('test.db', keep_order=True)

Features are accessed by name:

>>> gene = db['FBgn0031208']
>>> gene
<Feature gene (2L:7529-9484[+]) at 0x...>

Inspect fields from the GFF line:

>>> gene.start
7529

>>> gene.end
9484

Attributes are stored in the `attributes` dictionary.  Values are always in
a list, even if there's only one item:

>>> gene.attributes['Name']
['CG11023']

Attributes can also be accessed from the :class:`Feature` object itself, to
save some typing:

>>> gene['Name']
['CG11023']

Printing a :class:`Feature` reproduces the original GFF line as faithfully as
possible.  See the :ref:`dialects` section for more details on how this is
handled and configured.

>>> print(gene)  #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	gene	7529	9484	.	+	.	ID=FBgn0031208;Name=CG11023;Ontology_term=SO:0000010,SO:0000087,GO:0016929,GO:0016926,GO:0006508;Dbxref=FlyBase:FBan0011023,FlyBase_Annotation_IDs:CG11023,GB_protein:ACZ94128,GB_protein:AAO41164,GB:AI944728,GB:AJ564667,GB_protein:CAD92822,GB:BF495604,UniProt/TrEMBL:Q86BM6,INTERPRO:IPR003653,GB_protein:AGB92323,UniProt/TrEMBL:M9PAY1,OrthoDB7_Drosophila:EOG796K1P,OrthoDB7_Diptera:EOG7X1604,EntrezGene:33155,UniProt/TrEMBL:E1JHP8,UniProt/TrEMBL:Q6KEV3,OrthoDB7_Insecta:EOG7Q8QM7,OrthoDB7_Arthropoda:EOG7R5K68,OrthoDB7_Metazoa:EOG7D59MP,InterologFinder:33155,BIOGRID:59420,FlyAtlas:CG11023-RA,GenomeRNAi:33155;gbunit=AE014134;derived_computed_cyto=21A5-21A5

Get all the mRNAs for a gene:

>>> for i in db.children(gene, featuretype='mRNA', order_by='start'):
...     print(i) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	mRNA	7529	9484	.	+	.	ID=FBtr0300689;Name=CG11023-RB;Dbxref=REFSEQ:NM_001169365,FlyBase_Annotation_IDs:CG11023-RB;Parent=FBgn0031208;score_text=Strongly Supported;score=11
2L	FlyBase	mRNA	7529	9484	.	+	.	ID=FBtr0300690;Name=CG11023-RC;Dbxref=REFSEQ:NM_175941,FlyBase_Annotation_IDs:CG11023-RC;Parent=FBgn0031208;score_text=Strongly Supported;score=15
2L	FlyBase	mRNA	7529	9484	.	+	.	ID=FBtr0330654;Name=CG11023-RD;Dbxref=FlyBase_Annotation_IDs:CG11023-RD,REFSEQ:NM_001272857;Parent=FBgn0031208;score_text=Strongly Supported;score=11

Get all the exons for a gene:

>>> for i in db.children(gene, featuretype='exon', order_by='start'):
...     print(i) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	exon	7529	8116	.	+	.	Name=CG11023:1;Parent=FBtr0300689,FBtr0300690,FBtr0330654;parent_type=mRNA
2L	FlyBase	exon	8193	9484	.	+	.	Name=CG11023:3;Parent=FBtr0300689;parent_type=mRNA
2L	FlyBase	exon	8193	8589	.	+	.	Name=CG11023:2;Parent=FBtr0300690;parent_type=mRNA
2L	FlyBase	exon	8229	9484	.	+	.	Name=CG11023:4;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	exon	8668	9484	.	+	.	Name=CG11023:5;Parent=FBtr0300690;parent_type=mRNA

Does this gene have any constitutive exons (exons found in every alternative
transcript)?  This is an example of something that would be difficult to do
using only standard text file processing tools, and demonstrates the usefulness
of the :mod:`gffutils`:

>>> mRNA_count = len(list(db.children(gene, featuretype='mRNA')))
>>> constitutive_exons = []
>>> for exon in db.features_of_type('exon', order_by='start'):
...     parents = db.parents(exon, featuretype='mRNA')
...     if len(list(parents)) == mRNA_count:
...         constitutive_exons.append(exon)
>>> print(constitutive_exons)
[<Feature exon (2L:7529-8116[+]) at 0x...>]

Retrieve entries by genomic coordinates, which uses the `UCSC binning strategy
<http://genome.cshlp.org/content/12/6/996/F7.expansion.html>`_:

>>> list(db.region(region=('2L', 9277, 10000), completely_within=True))
[<Feature three_prime_UTR (2L:9277-9484[+]) at 0x...>]

Retrieve UTRs that overlap the gene (note that a feature can be provided as the
coordinates):

>>> for UTR in db.region(gene, featuretype=['three_prime_UTR', 'five_prime_UTR']):
...     print(UTR) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0300689,FBtr0300690;parent_type=mRNA
2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300689;parent_type=mRNA
2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	three_prime_UTR	9277	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300690;parent_type=mRNA

Now let's illustrate a problem in the GFF file as it is currently formatted by
trying to get the consitutive 5'UTRs in the same way we got the constitutive
exons above:

>>> constitutive_5UTRs = []
>>> for utr in db.features_of_type('five_prime_UTR', order_by='start'):
...     parents = db.parents(utr, featuretype='mRNA')
...     if len(list(parents)) == mRNA_count:
...         constitutive_5UTRs.append(utr)
>>> print(constitutive_5UTRs)
[]

Yikes!  What happened?  This is because by default, each line in the GFF file
is treated as a unique feature.  From this perspective, the first 5'UTR has two
parents, and the second 5'UTR has one parent -- there are zero 5'UTRs with all
three transcripts as parents.

What we'd really like to do is to merge the features that have identical IDs
and coordinates.  Specifically, we'd like to have these two features::

    2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0300689,FBtr0300690;parent_type=mRNA
    2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0330654;parent_type=mRNA

become a single feature::

    2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0300689,FBtr0300690,FBtr0330654;parent_type=mRNA

Similarly, we'd like these three 3'UTRs::

    2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300689;parent_type=mRNA
    2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0330654;parent_type=mRNA
    2L	FlyBase	three_prime_UTR	9277	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300690;parent_type=mRNA

to become two (merging only the first two because they have identical
coordinates)::

    2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300689,FBtr0330654;parent_type=mRNA
    2L	FlyBase	three_prime_UTR	9277	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300690;parent_type=mRNA

In order to do this, we need to change how features are loaded into the
database by using `merge_strategy=True` and `id_spec=['ID', 'Name']`.  You can
read more about exactly what these arguments do, and other ways of tweaking the
import, at :ref:`database-ids`.  But for now, let's see what happens:

>>> db2 = gffutils.create_db(fn, dbfn='test.db', force=True, keep_order=True,
... sort_attribute_values=True,
... merge_strategy='merge',
... id_spec=['ID', 'Name'])

>>> for utr in db2.features_of_type('five_prime_UTR', order_by='start'):
...     parents = db2.parents(utr, featuretype='mRNA')
...     if len(list(parents)) == mRNA_count:
...         constitutive_5UTRs.append(utr)
>>> print(constitutive_5UTRs)
[<Feature five_prime_UTR (2L:7529-7679[+]) at 0x...>]

Let's look at all the 5'UTRs in the database to see how the merge strategy
affected them:

>>> for i in db2.features_of_type('five_prime_UTR'):
...
...     print(i) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	five_prime_UTR	7529	7679	.	+	.	Name=CG11023-u5;Parent=FBtr0300689,FBtr0300690,FBtr0330654;parent_type=mRNA

Aha! A single 5'UTR.  What about 3'UTRs?

>>> for i in db2.features_of_type('three_prime_UTR'):
...     print(i) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	three_prime_UTR	8611	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300689,FBtr0330654;parent_type=mRNA
2L	FlyBase	three_prime_UTR	9277	9484	.	+	.	Name=CG11023-u3;Parent=FBtr0300690;parent_type=mRNA

>>> for i in db2.features_of_type('intron'):
...     print(i) #doctest:+NORMALIZE_WHITESPACE
2L	FlyBase	intron	8117	8228	.	+	.	Name=CG11023-in;Parent=FBtr0330654;parent_type=mRNA
2L	FlyBase	intron	8117	8192	.	+	.	Name=CG11023-in;Parent=FBtr0300689,FBtr0300690;parent_type=mRNA
2L	FlyBase	intron	8590	8667	.	+	.	Name=CG11023-in;Parent=FBtr0300690;parent_type=mRNA


text:
namespace media {

DemuxerConfigs::DemuxerConfigs()
    : audio_codec(kUnknownAudioCodec),
      audio_channels(0),
      audio_sampling_rate(0),
      is_audio_encrypted(false),
      audio_codec_delay_ns(-1),
      audio_seek_preroll_ns(-1),
      video_codec(kUnknownVideoCodec),
      is_video_encrypted(false) {}

DemuxerConfigs::~DemuxerConfigs() {}

AccessUnit::AccessUnit() : is_end_of_stream(false), is_key_frame(false) {}

AccessUnit::~AccessUnit() {}

DemuxerData::DemuxerData() : type(DemuxerStream::UNKNOWN) {}

DemuxerData::~DemuxerData() {}

namespace {

const char* AsString(DemuxerStream::Type stream_type) {
  switch (stream_type) {
    case DemuxerStream::UNKNOWN:
      return "UNKNOWN";
    case DemuxerStream::AUDIO:
      return "AUDIO";
    case DemuxerStream::VIDEO:
      return "VIDEO";
    case DemuxerStream::TEXT:
      return "TEXT";
    case DemuxerStream::NUM_TYPES:
      return "NUM_TYPES";
  }
  NOTREACHED();
  return nullptr;  // crash early
}

const char* AsString(DemuxerStream::Status status) {
  switch (status) {
    case DemuxerStream::kOk:
      return "kOk";
    case DemuxerStream::kAborted:
      return "kAborted";
    case DemuxerStream::kConfigChanged:
      return "kConfigChanged";
  }
  NOTREACHED();
  return nullptr;  // crash early
}

}  // namespace (anonymous)

}  // namespace media

std::ostream& operator<<(std::ostream& os, media::DemuxerStream::Type type) {
  os << media::AsString(type);
  return os;
}

std::ostream& operator<<(std::ostream& os, const media::AccessUnit& au) {
  os << "status:" << media::AsString(au.status)
     << (au.is_end_of_stream ? " EOS" : "")
     << (au.is_key_frame ? " KEY_FRAME" : "") << " pts:" << au.timestamp
     << " size:" << au.data.size();
  return os;
}

std::ostream& operator<<(std::ostream& os, const media::DemuxerConfigs& conf) {
  os << "duration:" << conf.duration;

  if (conf.audio_codec == media::kUnknownAudioCodec &&
      conf.video_codec == media::kUnknownVideoCodec) {
    os << " no audio, no video";
    return os;
  }

  if (conf.audio_codec != media::kUnknownAudioCodec) {
    os << " audio:" << media::GetCodecName(conf.audio_codec)
       << " channels:" << conf.audio_channels
       << " rate:" << conf.audio_sampling_rate
       << (conf.is_audio_encrypted ? " encrypted" : "")
       << " delay (ns):" << conf.audio_codec_delay_ns
       << " preroll (ns):" << conf.audio_seek_preroll_ns;

    if (!conf.audio_extra_data.empty()) {
      os << " extra:{" << std::hex;
      for (uint8_t byte : conf.audio_extra_data)
        os << " " << std::setfill('0') << std::setw(2) << (int)byte;
      os << "}" << std::dec;
    }
  }

  if (conf.video_codec != media::kUnknownVideoCodec) {
    os << " video:" << media::GetCodecName(conf.video_codec) << " "
       << conf.video_size.width() << "x" << conf.video_size.height()
       << (conf.is_video_encrypted ? " encrypted" : "");
  }

  return os;
}


text:
<template name="docsModalTemplate">

Documents for {{caseNum}}

                        {{#each docLinks}}

{{this.title}}

                        {{/each}}

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

</template>


text:
package Google::Ads::GoogleAds::V11::Common::Value;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    booleanValue => $args->{booleanValue},
    doubleValue  => $args->{doubleValue},
    floatValue   => $args->{floatValue},
    int64Value   => $args->{int64Value},
    stringValue  => $args->{stringValue}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
package org.adbcj.mysql.codec;

import java.io.IOException;
import java.io.InputStream;

public class BoundedInputStream extends InputStream {

    private final InputStream in;
    private int remaining;

    public BoundedInputStream(InputStream in, int length) {
        this.in = in;
        this.remaining = length;
    }

    @Override
    public int read() throws IOException {
        int i = in.read();
        if (i >= 0) {
            remaining --;
        }
        if (remaining < 0) {
            throw new IllegalStateException("Buffer overrun");
        }
        return i;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int i = in.read(b, off, len);
        remaining -= i;
        if (remaining < 0) {
            throw new IllegalStateException("Read too many bytes");
        }
        return i;
    }

    @Override
    public long skip(long n) throws IOException {
        long i = in.skip(n);
        remaining -= i;
        if (remaining < 0) {
            throw new IllegalStateException("Read too many bytes");
        }
        return i;
    }

    public int getRemaining() {
        return remaining;
    }

}


text:
#include "xlsxcontenttypes_p.h"
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QFile>
#include <QMapIterator>
#include <QBuffer>
#include <QDebug>

namespace QXlsx {

ContentTypes::ContentTypes(CreateFlag flag)
    :AbstractOOXmlFile(flag)
{
    m_package_prefix = QStringLiteral("application/vnd.openxmlformats-package.");
    m_document_prefix = QStringLiteral("application/vnd.openxmlformats-officedocument.");

    m_defaults.insert(QStringLiteral("rels"), m_package_prefix + QStringLiteral("relationships+xml"));
    m_defaults.insert(QStringLiteral("xml"), QStringLiteral("application/xml"));
}

void ContentTypes::addDefault(const QString &key, const QString &value)
{
    m_defaults.insert(key, value);
}

void ContentTypes::addOverride(const QString &key, const QString &value)
{
    m_overrides.insert(key, value);
}

void ContentTypes::addDocPropApp()
{
    addOverride(QStringLiteral("/docProps/app.xml"), m_document_prefix + QStringLiteral("extended-properties+xml"));
}

void ContentTypes::addDocPropCore()
{
    addOverride(QStringLiteral("/docProps/core.xml"), m_package_prefix + QStringLiteral("core-properties+xml"));
}

void ContentTypes::addStyles()
{
    addOverride(QStringLiteral("/xl/styles.xml"), m_document_prefix + QStringLiteral("spreadsheetml.styles+xml"));
}

void ContentTypes::addTheme()
{
    addOverride(QStringLiteral("/xl/theme/theme1.xml"), m_document_prefix + QStringLiteral("theme+xml"));
}

void ContentTypes::addWorkbook()
{
    addOverride(QStringLiteral("/xl/workbook.xml"), m_document_prefix + QStringLiteral("spreadsheetml.sheet.main+xml"));
}

void ContentTypes::addWorksheetName(const QString &name)
{
    addOverride(QStringLiteral("/xl/worksheets/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.worksheet+xml"));
}

void ContentTypes::addChartsheetName(const QString &name)
{
    addOverride(QStringLiteral("/xl/chartsheets/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.chartsheet+xml"));
}

void ContentTypes::addDrawingName(const QString &name)
{
    addOverride(QStringLiteral("/xl/drawings/%1.xml").arg(name), m_document_prefix + QStringLiteral("drawing+xml"));
}

void ContentTypes::addChartName(const QString &name)
{
    addOverride(QStringLiteral("/xl/charts/%1.xml").arg(name), m_document_prefix + QStringLiteral("drawingml.chart+xml"));
}

void ContentTypes::addCommentName(const QString &name)
{
    addOverride(QStringLiteral("/xl/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.comments+xml"));
}

void ContentTypes::addTableName(const QString &name)
{
    addOverride(QStringLiteral("/xl/tables/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.table+xml"));
}

void ContentTypes::addExternalLinkName(const QString &name)
{
    addOverride(QStringLiteral("/xl/externalLinks/%1.xml").arg(name), m_document_prefix + QStringLiteral("spreadsheetml.externalLink+xml"));
}

void ContentTypes::addSharedString()
{
    addOverride(QStringLiteral("/xl/sharedStrings.xml"), m_document_prefix + QStringLiteral("spreadsheetml.sharedStrings+xml"));
}

void ContentTypes::addVmlName()
{
    addOverride(QStringLiteral("vml"), m_document_prefix + QStringLiteral("vmlDrawing"));
}

void ContentTypes::addCalcChain()
{
    addOverride(QStringLiteral("/xl/calcChain.xml"), m_document_prefix + QStringLiteral("spreadsheetml.calcChain+xml"));
}

void ContentTypes::addVbaProject()
{
    //:TODO
    addOverride(QStringLiteral("bin"), QStringLiteral("application/vnd.ms-office.vbaProject"));
}

void ContentTypes::clearOverrides()
{
    m_overrides.clear();
}

void ContentTypes::saveToXmlFile(QIODevice *device) const
{
    QXmlStreamWriter writer(device);

    writer.writeStartDocument(QStringLiteral("1.0"), true);
    writer.writeStartElement(QStringLiteral("Types"));
    writer.writeAttribute(QStringLiteral("xmlns"), QStringLiteral("http://schemas.openxmlformats.org/package/2006/content-types"));

    {
    QMapIterator<QString, QString> it(m_defaults);
    while (it.hasNext()) {
        it.next();
        writer.writeStartElement(QStringLiteral("Default"));
        writer.writeAttribute(QStringLiteral("Extension"), it.key());
        writer.writeAttribute(QStringLiteral("ContentType"), it.value());
        writer.writeEndElement();//Default
    }
    }

    {
    QMapIterator<QString, QString> it(m_overrides);
    while (it.hasNext()) {
        it.next();
        writer.writeStartElement(QStringLiteral("Override"));
        writer.writeAttribute(QStringLiteral("PartName"), it.key());
        writer.writeAttribute(QStringLiteral("ContentType"), it.value());
        writer.writeEndElement(); //Override
    }
    }

    writer.writeEndElement();//Types
    writer.writeEndDocument();

}

bool ContentTypes::loadFromXmlFile(QIODevice *device)
{
    m_defaults.clear();
    m_overrides.clear();

    QXmlStreamReader reader(device);
    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType token = reader.readNext();
        if (token == QXmlStreamReader::StartElement) {
            if (reader.name() == QLatin1String("Default")) {
                QXmlStreamAttributes attrs = reader.attributes();
                QString extension = attrs.value(QLatin1String("Extension")).toString();
                QString type = attrs.value(QLatin1String("ContentType")).toString();
                m_defaults.insert(extension, type);
            } else if (reader.name() == QLatin1String("Override")) {
                QXmlStreamAttributes attrs = reader.attributes();
                QString partName = attrs.value(QLatin1String("PartName")).toString();
                QString type = attrs.value(QLatin1String("ContentType")).toString();
                m_overrides.insert(partName, type);
            }
        }

        if (reader.hasError()) {
            qDebug()<<reader.errorString();
        }
    }
    return true;
}

} //namespace QXlsx


text:
.. _upgrade-to-3.1.4:

########################################
3.1.4 release notes - Unreleased - Draft
########################################

*******************
What's new in 3.1.4
*******************

Bug Fixes
=========

* Fix use structure migration
* Fix fix_tree command
* Remove some warning for Django 1.9
* Fix using scroll bar of plugin menu in Firefox & IE moves plugins
* Fix JS error when using PageSelectWidget
* Fix whitespace markup issues in draft mode
* Detect plugin migrations layout in tests

Thanks
======

TBD


text:
[itggoteborg.github.io](https://itggoteborg.github.io)
=====================

Är du intresserad av programmering?
Den som vill är välkommen att komma och sätta sig, ovavsett tidigare erfarenheter av programmering!
Om du redan kan programmera så kanske du kan vara till hjälp för någon som inte har någon erfarenhet av programmering.

Kolla även in på vår [facebooksida](https://facebook.com/ITGGotProgrammering) för att få information om när och var vi träffas.


text:
package com.a.aykut.tryazuremobileservices;

import android.content.Context;
import android.util.Log;

/**
 * Created by Aykut on 15.08.2015.
 */
public class LogHelper {

  public static void setLogInfo(Context context, String value) {
    Log.i(context.getClass().getName(), value);
  }

}


text:
module.exports = function ($) {
  $.now = Date.now()
  $.year = new Date().getFullYear()
  $.layout('html5')
}


text:
import { createStore, combineReducers } from 'redux'

import userReducer from './reducers/user-reducer'
import itemsReducer from './reducers/items-reducer'

const reducer = combineReducers({
  user: userReducer,
  items: itemsReducer
})

const store = createStore(reducer)

export default store


text:
/**
 * Created by hernan on 17/11/2017.
 */

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
    selector : 'lt-entry-pagination',
    templateUrl : './show-entry.component.html',
    styles : ['']
})

export class ShowEntryComponent implements OnInit {
    @Input() entry: string;
    listEntry: number [] = [];

    @Output() onEntry = new EventEmitter<number>();

    constructor() {}
    ngOnInit() {
        const entries = this.entry.split('-');
        const maxNumber = parseInt(entries[0], 10);
        const grouping = parseInt(entries[1], 10);
        const iterator = maxNumber / grouping;

        for (let i = 0 ; i < iterator; i++) {
            const number = (i + 1) * grouping;
            this.listEntry.push(number);
        }

        this.onEntry.emit(this.listEntry[0]);
    }

    passVal(event) {
        this.onEntry.emit(parseInt(event, 10));
    }
}


text:
/**
 * [description]
 *
 * @function Phaser.Geom.Point.Ceil
 * @since 3.0.0
 *
 * @generic {Phaser.Geom.Point} O - [point,$return]
 *
 * @param {Phaser.Geom.Point} point - [description]
 *
 * @return {Phaser.Geom.Point} [description]
 */
var Ceil = function (point)
{
    return point.setTo(Math.ceil(point.x), Math.ceil(point.y));
};

module.exports = Ceil;


text:
<meta http-equiv="refresh" content="0; URL=../../../doc/html/date_time.html">

Automatic redirection failed, please go to
../../../doc/html/date_time.html

© Copyright CrystalClear Software, Inc 2003-2006

 Use, modification, and distribution are subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
www.boost.org/LICENSE_1_0.txt)


text:
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace Ku.Core.Cache.Redis
{
    internal class RedisDatabaseProvider : IRedisDatabaseProvider
    {
        /// <summary>
        /// The options.
        /// </summary>
        private readonly RedisOptions _options;

        /// <summary>
        /// The connection multiplexer.
        /// </summary>
        private readonly Lazy<ConnectionMultiplexer> _connectionMultiplexer;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:EasyCaching.Redis.RedisDatabaseProvider"/> class.
        /// </summary>
        /// <param name="options">Options.</param>
        public RedisDatabaseProvider(IOptions<RedisOptions> options)
        {
            _options = options.Value;
            _connectionMultiplexer = new Lazy<ConnectionMultiplexer>(CreateConnectionMultiplexer);
        }

        /// <summary>
        /// Gets the database connection.
        /// </summary>
        public IDatabase GetDatabase()
        {
            return _connectionMultiplexer.Value.GetDatabase(_options.Database);
        }

        /// <summary>
        /// Gets the server list.
        /// </summary>
        /// <returns>The server list.</returns>
        public IEnumerable<IServer> GetServerList()
        {
            var endpoints = GetMastersServersEndpoints();

            foreach (var endpoint in endpoints)
            {
                yield return _connectionMultiplexer.Value.GetServer(endpoint);
            }
        }

        /// <summary>
        /// Creates the connection multiplexer.
        /// </summary>
        /// <returns>The connection multiplexer.</returns>
        private ConnectionMultiplexer CreateConnectionMultiplexer()
        {
            var configurationOptions = new ConfigurationOptions
            {
                ConnectTimeout = _options.ConnectionTimeout,
                Password = _options.Password,
                Ssl = _options.IsSsl,
                SslHost = _options.SslHost,
                AllowAdmin = _options.AllowAdmin
            };

            foreach (var endpoint in _options.Endpoints)
            {
                configurationOptions.EndPoints.Add(endpoint.Host, endpoint.Port);
            }

            return ConnectionMultiplexer.Connect(configurationOptions.ToString());
        }

        /// <summary>
        /// Gets the masters servers endpoints.
        /// </summary>
        private List<EndPoint> GetMastersServersEndpoints()
        {
            var masters = new List<EndPoint>();
            foreach (var ep in _connectionMultiplexer.Value.GetEndPoints())
            {
                var server = _connectionMultiplexer.Value.GetServer(ep);
                if (server.IsConnected)
                {
                    //Cluster
                    if (server.ServerType == ServerType.Cluster)
                    {
                        masters.AddRange(server.ClusterConfiguration.Nodes.Where(n => !n.IsSlave).Select(n => n.EndPoint));
                        break;
                    }
                    // Single , Master-Slave
                    if (server.ServerType == ServerType.Standalone && !server.IsSlave)
                    {
                        masters.Add(ep);
                        break;
                    }
                }
            }
            return masters;
        }
    }

    internal interface IRedisDatabaseProvider
    {
        IDatabase GetDatabase();

        IEnumerable<IServer> GetServerList();
    }
}


text:
from types import CodeType
from typing import Any, Mapping, Optional, Union
import typing

from . import context, parser, printer, runtime

if typing.TYPE_CHECKING:
    from . import finders  # noqa: F401
    from . import statements  # noqa: F401

__all__ = ["Sketch"]

class Sketch:
    """
    A compiled, reusable template object.

    :class:`.Sketch` can be initialized directly with arguments, or
    by a subclass of :class:`.BaseSketchFinder`.

    :arg __content: The content of this sketch. This can be a string or a
        bytestring. If a bytestring
        is passed, the content will be decoded with :code:`source_encoding`
        from :code:`skt_ctx`.
        This argument must be passed positionally and must be the first
        argument.
    :arg path: The path of the sketch, used by :class:`.SketchFinder` to
        resolve file relationship. Default: :code:`<string>`.
    :arg skt_ctx: The subclass of :class:`.BaseSketchContext` to be used by the
        :class:`.Sketch` Default: :code:`None`.
        (Create a new :class:`.AsyncioSketchContext` upon initialization).
    :arg finder: The finder used by the current sketch to include or inherit
        from other sketches. Default: :code:`None`.
    """

    def __init__(
        self,
        __content: Union[str, bytes],
        *,
        path: str = "<string>",
        skt_ctx: Optional["context.BaseSketchContext"] = None,
        finder: Optional["finders.BaseSketchFinder"] = None,
    ) -> None:
        self._path = path

        self._ctx = skt_ctx or context.AsyncioSketchContext()

        self._finder = finder

        if isinstance(__content, bytes):
            self._content = __content.decode(self._ctx.source_encoding)

        else:
            self._content = __content

        self._root = parser.SketchParser.parse_sketch(self)

    @property
    def _compiled_code(self) -> CodeType:
        if not hasattr(self, "_printed_skt"):
            self._printed_skt = printer.PythonPrinter.print_sketch(self)

        return self._printed_skt

    def _get_runtime(
        self, skt_globals: Mapping[str, Any]
    ) -> runtime.SketchRuntime:
        skt_globals = skt_globals

        exec(self._compiled_code, skt_globals)  # type: ignore

        return skt_globals["_SktCurrentRuntime"](  # type: ignore
            self, skt_globals=skt_globals
        )

    async def draw(self, **kwargs: Any) -> str:
        """
        Draw the sketch to :code:`str`.

        :arg \\*\\*kwargs: All the keyword arguments will become global
            variables in the runtime.

        .. warning::

            The exceptions raised in the runtime will pop up from this method.
        """
        runtime = self._get_runtime(skt_globals=kwargs)

        await runtime._draw()

        return runtime._skt_result


text:
class RiskyCard < ActiveRecord::Base

  acts_as_paranoid

  belongs_to :account

  validates :fingerprint, :account, presence: true

end


text:
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
    namespace ss
    {
        namespace formula
        {
            namespace eval
            {
typedef ::SubArray< ::poi::ss::formula::eval::ValueEval, ::java::lang::ObjectArray > ValueEvalArray;
            } // eval
        } // formula
    } // ss
} // poi

poi::ss::formula::functions::NumericFunction_20::NumericFunction_20()
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
    ctor();
}

double poi::ss::formula::functions::NumericFunction_20::evaluate(double d)
{
    return MathX::sinh(d);
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::ss::formula::functions::NumericFunction_20::class_()
{
    static ::java::lang::Class* c = ::class_(u"", 0);
    return c;
}

poi::ss::formula::eval::ValueEval* poi::ss::formula::functions::NumericFunction_20::evaluate(int32_t srcRowIndex, int32_t srcColumnIndex, ::poi::ss::formula::eval::ValueEval* arg0)
{
    return super::evaluate(srcRowIndex, srcColumnIndex, arg0);
}

poi::ss::formula::eval::ValueEval* poi::ss::formula::functions::NumericFunction_20::evaluate(::poi::ss::formula::eval::ValueEvalArray* args, int32_t srcRowIndex, int32_t srcColumnIndex)
{
    return super::evaluate(args, srcRowIndex, srcColumnIndex);
}

java::lang::Class* poi::ss::formula::functions::NumericFunction_20::getClass0()
{
    return class_();
}


text:
<?php

include("./include/auth.php");

api_plugin_hook('logout_pre_session_destroy');

/* Clear session */
setcookie(session_name(),"",time() - 3600,"/");
session_destroy();

api_plugin_hook('logout_post_session_destroy');

/* Check to see if we are using Web Basic Auth */
if (read_config_option("auth_method") == "2") {
	if (api_plugin_hook_function('custom_logout_message', OPER_MODE_NATIVE) == OPER_MODE_RESKIN) {
		exit;
	}

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

	<title>Logout of Cacti</title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

To end your Cacti session please close your web browser.

Return to Cacti

		<?php

}else{
	/* Default action */
	header("Location: index.php");
	exit;
}

?>


text:
 define([
	'backbone',
	'underscore',
	'marionette',
	'collections/comments',
	'views/comment/commentView',
	'hbs!templates/user/profile'
	], function(Backbone, _, Marionette, CommentCollection, CommentView, template) {

	    var UserProfileView = Backbone.Marionette.ItemView.extend({

	    	initialize: function () {
	    		var self = this;
	    		this.comments = new CommentCollection(this.model.toJSON().comments.items);
	    		this.commentView = new CommentView({
	    			collection: this.comments,
	    			target: { libelle: 'userId', value: self.model.get("id") }
	    		});
	    	},

	    	ui:{
	    		commentArea: '.comment-area'
	    	},

	    	template: template,

	    	onRender: function () {
	    		this.ui.commentArea.html(this.commentView.render().el);
	    	}
	    });

	    return UserProfileView;
});


text:
namespace System.Configuration {
    using System.Configuration.Internal;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Globalization;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Security.Permissions;
    using System.Security;
    using System.Text;
    using System.Xml;

    // Information about a stream used in configuration
    class StreamInfo {
        private string  _sectionName;   // the section the stream contains for configSource, null for a full config file
        private string  _configSource;  // the configSource directive that generated this stream, null for a full config file
        private string  _streamName;    // name of the stream
        private bool    _isMonitored;   // is the stream currently monitored?
        private object  _version;       // version that we're monitoring

        internal StreamInfo(string sectionName, string configSource, string streamName) {
            _sectionName = sectionName;
            _configSource = configSource;
            _streamName = streamName;
        }

        private StreamInfo() {
        }

        internal StreamInfo Clone() {
            StreamInfo clone = new StreamInfo();

            clone._sectionName  = this._sectionName;
            clone._configSource = this._configSource;
            clone._streamName   = this._streamName;
            clone._isMonitored  = this._isMonitored;
            clone._version      = this._version;

            return clone;
        }

        internal string SectionName {
            get { return _sectionName; }
        }

        internal string ConfigSource {
            get { return _configSource; }
        }

        internal string StreamName {
            get { return _streamName; }
        }

        internal bool IsMonitored {
            get { return _isMonitored; }
            set { _isMonitored = value;}
        }

        internal object Version {
            get { return _version; }
            set { _version = value; }
        }
    }
}


text:
package org.apache.geode.cache.client.internal.locator;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.geode.DataSerializer;
import org.apache.geode.distributed.internal.ServerLocation;
import org.apache.geode.internal.serialization.DataSerializableFixedID;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;

/**
 * A response from a locator to a client Indicating which server to connect to for client to server
 * traffic.
 *
 */
public class ClientConnectionResponse extends ServerLocationResponse {

  private ServerLocation server;

  private boolean serverFound = false;

  /** For data serializer */
  public ClientConnectionResponse() {
    super();
  }

  public ClientConnectionResponse(ServerLocation server) {
    this.server = server;
    if (server != null) {
      this.serverFound = true;
    }
  }

  @Override
  public void fromData(DataInput in,
      DeserializationContext context) throws IOException, ClassNotFoundException {
    this.serverFound = DataSerializer.readPrimitiveBoolean(in);
    if (this.serverFound) {
      server = new ServerLocation();
      server.fromData(in);
    }
  }

  @Override
  public void toData(DataOutput out,
      SerializationContext context) throws IOException {
    boolean serverFound = server != null;
    DataSerializer.writePrimitiveBoolean(serverFound, out);
    if (serverFound) {
      server.toData(out);
    }
  }

  public ServerLocation getServer() {
    return server;
  }

  @Override
  public String toString() {
    return "ClientConnectionResponse{server=" + getServer() + "}";
  }

  @Override
  public int getDSFID() {
    return DataSerializableFixedID.CLIENT_CONNECTION_RESPONSE;
  }

  @Override
  public boolean hasResult() {
    return this.serverFound;
  }

}


text:
import array
import datetime
import socket
import struct
import time

SYNC=True
ASYNC=False
nt = [ 0, 1, 0, 0, 1, 2, 4, 8, 4, 8, 1, 0, 0, 4, 4, 8, 0, 4, 4, 4 ]  #byte length of different datatypes

class Month:
    def __init__(self, x):
        self.i = x
    def __str__(self):
        m = self.i + 24000
        y = m / 12
        return '%(decade)02d%(year)02d-%(month)02d' % {'decade': y/100, 'year': y % 100, 'month':(m+1)%12}
    def __eq__(self, obj):
        if isinstance(obj, Month) : return obj.i == self.i
        return False
class Minute:
    def __init__(self, x):
        self.i = x
    def __str__(self):
        return '%(hour)02d:%(minute)02d' % {'hour': self.i/60, 'minute': self.i % 60}
    def __eq__(self, obj):
        if isinstance(obj, Minute) : return obj.i == self.i
        return False
class Second:
    def __init__(self, x):
        self.i = x
    def __str__(self):
        return '%(minute)s:%(second)02d' % {'minute': str(Minute(self.i/60)), 'second': self.i % 60}
    def __eq__(self, obj):
        if isinstance(obj, Second) : return obj.i == self.i
        return False
class Dict:
    """Dict is a generalized dict.  It just contains the keys and values as two objects and provides a way to
    interact with it."""
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.length = len(x)

    def __len__(self):
        return self.length

    def __iter__(self):
        self.index = 0
        return self

    def next(self):
        if self.index > self.length-1:
            raise StopIteration
        k,v = self.x[self.index], self.y[self.index]
        self.index += 1
        return k,v
    def __str__(self):
        string = ""
        for k,v in self:
            string += '[' +','.join(str(item) for item in k) + ']' + ','.join((str(item) for item in v)) + "\n"
        self.index = 0
        return string
    def __eq__(self, obj):
        if isinstance(obj, Dict) : return self.y == obj.y and self.x == obj.x
        return False

class Flip:
    """Flip is a different way to look at table data held in a Dict
    It assumes that the dictionary contains values which are equal length arrays"""
    def __init__(self, d):
        self.x = []  #column names
        self.y = []  #column data (stored by column)
        for k,v in d:
            self.x.append(k)
            self.y.append(v)
        self.length = len(self.y[0])
        self.index = 0
    def __len__(self):
        return self.length
    def __iter__(self):
        self.index = 0
        return self
    def next(self):
        """Return the row"""
        if self.index > self.length-1:
            raise StopIteration
        row = []
        for v in self.y:
            row.append(v[self.index])
        self.index += 1
        return row
    def __str__(self):
        string = ""
        for row in self:
            string += ','.join((str(item) for item in row)) + "\n"
        self.index = 0
        return string
    def __eq__(self, obj):
        if isinstance(obj, Flip) : return self.y == obj.y and self.x == obj.x
        return False
    def __getitem__(self, index):
        row = []
        for v in self.y:
            row.append(v[index])
        return row

def td(x):
    """A Dict containing two Flips is how keyed tables are encoded, td joins the 2 Dict objects into a single Flip object"""
    if isinstance(x, Flip): return x
    if not isinstance(x, Dict): raise Exception('This function takes a Dict type')
    a = x.x
    b = x.y
    x = []
    for item in a.x: x.append(item)
    for item in b.x: x.append(item)
    y = []
    for item in a.y: y.append(item)
    for item in b.y: y.append(item)
    return Flip(Dict(x,y))

# 86400000 is number of milliseconds in a day
# 10957 is days offset between UNIX Epoch and kdb Epoch
k = 86400000 * 10957
STDOFFSET = -time.timezone

class q:

    RECONNECT_ATTEMPTS = 5  # Number of reconnect attempts to make before throwing exception
    RECONNECT_WAIT = 5000 # Milliseconds to wait between reconnect attempts
    MAX_MSG_QUERY_LENGTH = 1024 # Maximum number of characters from query to return in exception message
    MAX_MSG_LIST_LENGTH = 100 # Maximum length of a data list specified in a query before it is summarized in exception message

    def lg(self, x):
        """local time to UTC offset"""
        return x + STDOFFSET

    def gl(self, x):
        """UTC to local time offset"""
        return x - STDOFFSET

    def __init__(self, host, port, user=''):
        self.host=host
        self.port=port
        self.user=user
        self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect()

    def close(self):
        self.sock.close()

    def connect(self, attempts=1):
        if self.host=='' :
            raise Exception('bad host')
        for attempt in range(attempts):
            try:
                self.sock.connect((self.host,self.port))
                login = array.array('b')  #signed char array (bytes)
                login.fromstring(self.user)
                login.append(0) #null terminated string
                self.sock.send(login.tostring())
                result = self.sock.recv(1)  #blocking recv
                #print ':', result
                if not result:
                    raise Exception("access denied")

            except:
                raise Exception ('unable to connect to host')

    def ns(self, str):
        if str=='' or str==None:
            return 0
        else:
            return str.find('\000')

    def n(self, x):
        if isinstance(x, Dict):
            return self.n(x.x)
        elif isinstance(x, array.array) or isinstance(x, list):
            return len(x)
        else:
            return 1

    def _nx(self, x):
        qtype = self._qtype(x)
        if qtype == 99:
            return 1 + self._nx(x.x) + self._nx(x.y)
        if qtype == 98:
            return 3 + self._nx(x.x) + self._nx(x.y)
        if qtype < 0:
            if qtype == -11:
                return 2+len(x)
            else:
                return 1 + nt[-qtype]
        j = 6
        n = self.n(x)
        if qtype == 0 or qtype == 11:
            for i in range(0, n):
                if qtype == 0:
                    j += self._nx(x[i])
                else:
                    1 + len(x[i])
        else :
            j += n * nt[qtype];
        return j;

    def _qtype(self, x):
        """Encode the type of x as an integer that is interpreted by q"""
        #TODO figure out how to deal with array types
        if isinstance(x, list):return 0

        if isinstance(x, array.array):
            if x.typecode == 'c':
                return 10
            elif x.typecode == 'h':
                return 10
            elif x.typecode == 'i':
                return 6
            elif x.typecode == 'l':
                return 7
            elif x.typecode == 'f':
                return 8
            elif x.typecode == 'd':
                return 8
            else:
                return 0

        if isinstance(x,bool):
            return -1
        elif isinstance(x,int):
            return -6
        elif isinstance(x,float):
            return -8
        elif isinstance(x,long):
            return -7
        elif isinstance(x,str):
            return -11
        elif isinstance(x,Month):
            return -13
        elif isinstance(x,datetime.datetime):
            return -15
        elif isinstance(x,datetime.date):
            return -14
        elif isinstance(x,Minute):
            return -17
        elif isinstance(x,Second):
            return -18
        elif isinstance(x,datetime.time):
            return -19
        elif isinstance(x,Flip):
            return 98
        elif isinstance(x,Dict):
            return 99
        else:
            return 0

    def _wb(self, x, message):
        message.fromstring(struct.pack('b', x))

    def _wc(self, x, message):
        message.fromstring(struct.pack('c', x))

    def _wi(self, x, message):
        message.fromstring(struct.pack('>i', x))

    def _wd(self, x, message):
        message.fromstring(struct.pack('>i', x.toordinal() - datetime.date(2000, 1, 1).toordinal()))

    def _wdt(self, x, message):
        message.fromstring(struct.pack('>d', (self.lg( time.mktime(x.timetuple())+(x.microsecond/1000000.) )*1000. -k) / 8.64e7 ))

    def _wt(self, x, message):
        message.fromstring(struct.pack('>i', ( x.hour*3600 + x.minute*60 + x.second + (x.microsecond+100)/1000000. )*1000. ))

    def _we(self, x, message):
        message.fromstring(struct.pack('>f', x))

    def _wj(self, x, message):
        message.fromstring(struct.pack('>l', x))

    def _wf(self, x, message):
        message.fromstring(struct.pack('>d', x))

    def _wh(self, x, message):
        message.fromstring(struct.pack('>h', x))

    def _ws(self, x, message):
        message.fromstring(x)
        message.fromstring(struct.pack('b',0))

    def _wdict(self, x, message):
        self._write(x.x, message)
        self._write(x.y, message)

    def _wmms(self, x, message):
        message.fromstring(struct.pack('>i', x.i))

    def _write(self, x, message):
        """determine the type of x and write it to the binary message for output"""
        t = self._qtype(x)
        message.fromstring(struct.pack('b', t))

        writeType = {
            -1: self._wb,
             -4: self._wb,
             -5: self._wh,
            -6: self._wi,
            -7: self._wj,
            -8: self._we,
            -9: self._wf,
            -10: self._wc,
            -11: self._ws,
            -13: self._wmms,
            -14: self._wd,
            -15: self._wdt,
            -17: self._wmms,
            -18: self._wmms,
            -19: self._wt,
            0: self._write,
            1: self._wb,
             4: self._wb,
             5: self._wh,
             6: self._wi,
             7: self._wj,
             8: self._we,
             9: self._wf,
             10: self._wc,
             11: self._ws,
             13: self._wmms,
             14: self._wd,
             15: self._wdt,
             17: self._wmms,
             18: self._wmms,
             19: self._wt
             }

        if t < 0 :
            writeType[t](x, message)
            return

        if t == 99:
            self._write(x.x, message)
            self._write(x.y, message)
            return

        message.fromstring(struct.pack('b', 0))

        if t == 98:
            message.fromstring(struct.pack('b', 99))
            self._write(x.x, message)
            self._write(x.y, message)
            return

        n = self.n(x)
        message.fromstring(struct.pack('>i', n))

        for i in range(0, n):
            writeType[t](x[i], message)

    def k(self, query, args=None):
        global SYNC
        if isinstance(query, str) and args is None:
            self._send(SYNC, array.array('c',query))
        else:
            stuff = [array.array('c',query),]
            for item in args:
                stuff.append(item)
            self._send(SYNC, stuff )
        return self._readFromServer()

    def _send(self, sync, query):
        n = self._nx(query) + 8
        if sync:
            message = array.array('b', [0,1,0,0]) # 1 for synchronous requests
        else:
            message = array.array('b', [0,0,0,0]) # 1 for synchronous requests
        message.fromstring(struct.pack('>i', n)) # n is the total lengh of the message ( in bytes)
        self._write(query, message)
        self.sock.send(message)

    def _readFromServer(self):
        """read the response from the server"""
        header = self.sock.recv(8)
        little_endian = struct.unpack('b', header[0:1])[0] == 1  #byte order

        self.offset = 4
        dataSize = self._ri(little_endian, header)

        inputBytes = self.recv_size(self.sock, dataSize - 8)
        #ensure that it reads all the data
        if struct.unpack('b', inputBytes[0:struct.calcsize('b')])[0] == -128 :
            self.offset = 1
            raise Exception(self._rs(little_endian, inputBytes))
        self.offset =0
        return self._r(little_endian, inputBytes)

    def recv_size(self, the_socket, size):
        """read size bytes from the socket."""
        #data length is packed into 8 bytes
        total_len=0;total_data=[]
        sock_data='';recv_size=min(size,8192)
        while total_len<size:
            sock_data=the_socket.recv(recv_size)
            total_data.append(sock_data)
            total_len=sum([len(i) for i in total_data ])
        return ''.join(total_data)

    def _endian_decide(self,little_endian,fmt):
        """pick between two types for conversion based on endianness"""
        if little_endian:
            return fmt
        else:
            return '>'+fmt

    def _rb(self, little_endian, bytearray):
        """retrieve byte from bytearray at offset"""
        val = struct.unpack('b', bytearray[self.offset:self.offset+1])[0]
        self.offset+=1
        return val

    def _rc(self, little_endian, bytearray):
        """retrieve char from bytearray at offset"""
        val = struct.unpack('c', bytearray[self.offset:self.offset+1])[0]
        self.offset+=1
        return val

    def _ri(self, little_endian, bytearray):
        """retrieve integer from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'i'), bytearray[self.offset:self.offset+4])[0]
        self.offset+=4
        return val

    def _rd(self, little_endian, bytearray):
        """retrieve date from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'i'), bytearray[self.offset:self.offset+4])[0]
        self.offset+=4
        delta=datetime.timedelta(milliseconds=8.64e7*val)
        return datetime.date.fromtimestamp(self.gl(946684800)) + delta  #946684800 is conversion from UNIX epoch to KDB epoch

    def _rt(self, little_endian, bytearray):
        """retrieve time from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'i'), bytearray[self.offset:self.offset+4])[0]
        self.offset+=4
        return (datetime.datetime.fromordinal(1) + datetime.timedelta(milliseconds=val)).time()

    def _rdt(self, little_endian, bytearray):
        """retrieve datetime from bytearray at offset.  kdb stores dates relative to 2000.01.01"""
        val = struct.unpack(self._endian_decide(little_endian,'d'), bytearray[self.offset:self.offset+8])[0]
        self.offset+=8
        delta=datetime.timedelta(milliseconds=8.64e7*val)  #8.64e7 is milliseconds in a day
        return datetime.datetime.fromtimestamp(self.gl(946684800)) + delta  #946684800 is conversion from UNIX epoch to KDB epoch

    def _re(self, little_endian, bytearray):
        """retrieve float from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'f'), bytearray[self.offset:self.offset+4])[0]
        self.offset+=4
        return val

    def _rj(self, little_endian, bytearray):
        """retrieve long from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'q'), bytearray[self.offset:self.offset+8])[0]
        self.offset+=8
        return val

    def _rf(self, little_endian, bytearray):
        """retrieve double from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'d'), bytearray[self.offset:self.offset+8])[0]
        self.offset+=8
        return val

    def _rh(self, little_endian, bytearray):
        """retrieve integer from bytearray at offset"""
        val = struct.unpack(self._endian_decide(little_endian,'h'), bytearray[self.offset:self.offset+2])[0]
        self.offset+=2
        return val

    def _rs(self, little_endian, bytearray):
        """retrieve null terminated string from bytearray"""
        end = bytearray.find("\0",self.offset)
        val = bytearray[self.offset:end]
        self.offset = end+1
        return val

    def _r(self, little_endian, bytearray):
        """General retrieve data from bytearray.  format is type number followed by data"""
        t = self._rb(little_endian, bytearray)
        readType = {
            -1: lambda: self._rb(little_endian, bytearray),
            -4: lambda: self._rb(little_endian, bytearray),
            -5: lambda: self._rh(little_endian, bytearray),
            -6: lambda: self._ri(little_endian, bytearray),
            -7: lambda: self._rj(little_endian, bytearray),
            -8: lambda: self._re(little_endian, bytearray),
            -9: lambda: self._rf(little_endian, bytearray),
            -10: lambda: self._rc(little_endian, bytearray),
            -11: lambda: self._rs(little_endian, bytearray),
            -13: lambda: Month(self._ri(little_endian, bytearray)),
            -14: lambda: self._rd(little_endian, bytearray),
            -15: lambda: self._rdt(little_endian, bytearray),
            -17: lambda: Minute(self._ri(little_endian, bytearray)),
            -18: lambda: Second(self._ri(little_endian, bytearray)),
            -19: lambda: self._rt(little_endian, bytearray),
            0: lambda: self._r(little_endian, bytearray),
            1: lambda: self._rb(little_endian, bytearray),
             4: lambda: self._rb(little_endian, bytearray),
             5: lambda: self._rh(little_endian, bytearray),
             6: lambda: self._ri(little_endian, bytearray),
             7: lambda: self._rj(little_endian, bytearray),
             8: lambda: self._re(little_endian, bytearray),
             9: lambda: self._rf(little_endian, bytearray),
             10: lambda: self._rc(little_endian, bytearray),
             11: lambda: self._rs(little_endian, bytearray),
             13: lambda: Month(self._ri(little_endian, bytearray)),
             14: lambda: self._rd(little_endian, bytearray),
             15: lambda: self._rdt(little_endian, bytearray),
             17: lambda: Minute(self._ri(little_endian, bytearray)),
             18: lambda: Second(self._ri(little_endian, bytearray)),
             19: lambda: self._rt(little_endian, bytearray)
            }
        if t < 0 :
            #In this case the value is a scalar
            if readType.has_key(t) : return readType[t]()
        if t > 99 :
            if t == 100 :
                self._rs(little_endian, bytearray)
                return self._r(little_endian, bytearray)
            if t < 104 :
                if self._rb(little_endian, bytearray) == 0 and t == 101:
                    return None
                else:
                    return "func"
            self.offset = len(bytearray)
            return "func"

        if t == 99:
            keys = self._r(little_endian, bytearray)
            values = self._r(little_endian, bytearray)
            return Dict(keys, values)

        self.offset+=1;

        if t == 98:
            return Flip(self._r(little_endian, bytearray))

        n=self._ri(little_endian, bytearray) #length of the array
        val = []
        for i in range(0, n):
            item = readType[t]()
            val.append( item )
        return val


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus epixylon Bull.

### Remarks
null


text:
<?php namespace ABD\Mailer;

interface MailerInterface extends MailConfigurationInterface, MessageInterface {

    public function error();

}


text:
/*
 * $Id$
 **********************************************************************************
 *
 * Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
 *
 * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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 uk.ac.ox.oucs.vle;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.sakaiproject.api.app.scheduler.JobDetailWrapper;
import org.sakaiproject.api.app.scheduler.SchedulerManager;
import org.sakaiproject.api.app.scheduler.TriggerWrapper;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.app.scheduler.JobDetailWrapperImpl;
import org.sakaiproject.component.app.scheduler.TriggerWrapperImpl;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.tool.api.Tool;

public class SchedulerTool extends HttpServlet {

	private static final Log LOG = LogFactory.getLog(SchedulerTool.class);

	private Scheduler scheduler;

	private ServerConfigurationService serverConfigurationService;

	public SchedulerTool() {
	}

	/**
	 *
	 * @param scheduler
	 */
	public List<JobDetailWrapper> processRefreshJobs() {

		List<JobDetailWrapper> jobDetailWrapperList = new ArrayList<JobDetailWrapper>();

		try {
			String[] jobNames = scheduler.getJobNames(Scheduler.DEFAULT_GROUP);

			for (int i = 0; i < jobNames.length; i++) {
				JobDetailWrapper jobDetailWrapper = new JobDetailWrapperImpl();
				jobDetailWrapper.setJobDetail(scheduler.getJobDetail(
						jobNames[i], Scheduler.DEFAULT_GROUP));
				Trigger[] triggerArr = scheduler.getTriggersOfJob(jobNames[i],
						Scheduler.DEFAULT_GROUP);
				List<TriggerWrapper> triggerWrapperList = new ArrayList<TriggerWrapper>();
				TriggerWrapper tw;

				for (int j = 0; j < triggerArr.length; j++) {
					tw = new TriggerWrapperImpl();
					tw.setTrigger(triggerArr[j]);
					triggerWrapperList.add(tw);
				}

				jobDetailWrapper.setTriggerWrapperList(triggerWrapperList);
				jobDetailWrapperList.add(jobDetailWrapper);
			}

		} catch (SchedulerException e) {
			LOG.error("scheduler error while getting job detail");
		}

		return jobDetailWrapperList;
	}

	/**
	 * This method runs the current job only once, right now
	 *
	 * @return String
	 */
	public String processRunJobNow(String jobName) {

		try {
			List<JobDetailWrapper> jobDetailWrapperList = processRefreshJobs();

			JobDetailWrapper selectedJobDetailWrapper = null;

			for (JobDetailWrapper jobDetailWrapper : jobDetailWrapperList) {
				if (jobDetailWrapper.getJobDetail().getName().equals(jobName)) {
					selectedJobDetailWrapper = jobDetailWrapper;
				}
			}

			scheduler.triggerJob(selectedJobDetailWrapper.getJobDetail()
					.getName(), selectedJobDetailWrapper.getJobDetail()
					.getGroup());

			return "success";

		} catch (Exception e) {
			LOG.error("Failed to trigger job now");
			return "error";
		}
	}

	@Override
	public void init() throws ServletException {
		SchedulerManager schedulerManager = (SchedulerManager) ComponentManager
				.get(org.sakaiproject.api.app.scheduler.SchedulerManager.class);
		scheduler = schedulerManager.getScheduler();
		if (scheduler == null) {
			throw new ServletException("Couldn't get the scheduler.");
		}
		serverConfigurationService = (ServerConfigurationService) ComponentManager.
				get(ServerConfigurationService.class);
		if (serverConfigurationService == null) {
			throw new ServletException("Couldn't get the server configuration service.");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ServletContext context = getServletContext();
		List<JobDetailWrapper> jobDetailWrapperList = processRefreshJobs();

		request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
		request.setAttribute("jobDetailList", jobDetailWrapperList);

		request.setAttribute("skinRepo",
				serverConfigurationService.getString("skin.repo", "/library/skin"));

		request.setAttribute("skinDefault",
				serverConfigurationService.getString("skin.default", "default"));

		RequestDispatcher dispatcher = context
				.getRequestDispatcher("/static/quartz.jsp");
		dispatcher.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Map<String, String[]> requestParams = request.getParameterMap();
		String[] vals = (String[]) requestParams.get("jobName");
		String jobName = vals[0];
		processRunJobNow(jobName);
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.securityinsights.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.securityinsights.models.CodelessConnectorPollingConfigProperties;
import com.azure.resourcemanager.securityinsights.models.CodelessUiConnectorConfigProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Represents Codeless API Polling data connector. */
@Fluent
public final class ApiPollingParameters {
    /*
     * Config to describe the instructions blade
     */
    @JsonProperty(value = "connectorUiConfig")
    private CodelessUiConnectorConfigProperties connectorUiConfig;

    /*
     * Config to describe the polling instructions
     */
    @JsonProperty(value = "pollingConfig")
    private CodelessConnectorPollingConfigProperties pollingConfig;

    /**
     * Get the connectorUiConfig property: Config to describe the instructions blade.
     *
     * @return the connectorUiConfig value.
     */
    public CodelessUiConnectorConfigProperties connectorUiConfig() {
        return this.connectorUiConfig;
    }

    /**
     * Set the connectorUiConfig property: Config to describe the instructions blade.
     *
     * @param connectorUiConfig the connectorUiConfig value to set.
     * @return the ApiPollingParameters object itself.
     */
    public ApiPollingParameters withConnectorUiConfig(CodelessUiConnectorConfigProperties connectorUiConfig) {
        this.connectorUiConfig = connectorUiConfig;
        return this;
    }

    /**
     * Get the pollingConfig property: Config to describe the polling instructions.
     *
     * @return the pollingConfig value.
     */
    public CodelessConnectorPollingConfigProperties pollingConfig() {
        return this.pollingConfig;
    }

    /**
     * Set the pollingConfig property: Config to describe the polling instructions.
     *
     * @param pollingConfig the pollingConfig value to set.
     * @return the ApiPollingParameters object itself.
     */
    public ApiPollingParameters withPollingConfig(CodelessConnectorPollingConfigProperties pollingConfig) {
        this.pollingConfig = pollingConfig;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (connectorUiConfig() != null) {
            connectorUiConfig().validate();
        }
        if (pollingConfig() != null) {
            pollingConfig().validate();
        }
    }
}


text:
module.exports = function(config) {
    'use strict';

    config.set({
        basePath: '../',
        browsers: [process.env.CI ? 'PhantomJS' : 'Chrome'],
        files: [
            {pattern: 'test/bind.polyfill.js', included: true},
            {pattern: 'test/assign.polyfill.js', included: true},
            {pattern: 'dist/ex-machina.js', included: true},

            // test files
            {pattern: 'test/src/**/*.js', included: true},
        ],
        reporters: ['spec'],
        frameworks: ['jasmine'],
    });
};


text:
using EmployersSQLiteProject.Helpers;
using EmployersSQLiteProject.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace EmployersSQLiteProject.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class AddEmployee : Page
    {
        public AddEmployee()
        {
            this.InitializeComponent();
        }

        private async void AddEmployee_Click(object sender, RoutedEventArgs e)
        {
            DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Create an object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs
            //if all fields have been filled in
            if (NametxtBx.Text != "" & AgetxtBx.Text != "" & PhoneNumbertxtBx.Text != "" & EmailtxtBx.Text != "" & SalarytxtBx.Text != "")
            {
                //insert them into the database using the db Helper class
                Db_Helper.Insert(new Employees(NametxtBx.Text, AgetxtBx.Text, PhoneNumbertxtBx.Text, EmailtxtBx.Text, SalarytxtBx.Text));
                //after adding Employees bring the user to the listbox page to see their changes
                Frame.Navigate(typeof(ReadEmployeesList));
            }
            else
            {
                MessageDialog messageDialog = new MessageDialog("Please fill in all fields");//Text should not be empty
                await messageDialog.ShowAsync();
            }
        }

        //replaces abck button
        private void Home_Click(object sender, RoutedEventArgs e)
        {
            //bring user back to the main page
            Frame.Navigate(typeof(ReadEmployeesList));
        }
    }
}


text:
Imboard

Imboard is Most convenient webpage development platform