text:
import { logError, deepAccess, parseSizesInput } from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER, VIDEO} from '../src/mediaTypes.js';
import {config} from '../src/config.js';
import { Renderer } from '../src/Renderer.js';
import { INSTREAM, OUTSTREAM } from '../src/video.js';

const ENDPOINT = `https://d.vidoomy.com/api/rtbserver/prebid/`;
const BIDDER_CODE = 'vidoomy';
const GVLID = 380;

const COOKIE_SYNC_FALLBACK_URLS = [
  'https://x.bidswitch.net/sync?ssp=vidoomy',
  'https://ib.adnxs.com/getuid?https%3A%2F%2Fa-prebid.vidoomy.com%2Fsetuid%3Fbidder%3Dadnxs%26gdpr%3D{{GDPR}}%26gdpr_consent%3D{{GDPR_CONSENT}}%26uid%3D%24UID',
  'https://pixel-sync.sitescout.com/dmp/pixelSync?nid=120&redir=https%3A%2F%2Fa.vidoomy.com%2Fapi%2Frtbserver%2Fcookie%3Fi%3DCEN%26uid%3D%7BuserId%7D',
  'https://sync.1rx.io/usersync2/vidoomy?redir=https%3A%2F%2Fa.vidoomy.com%2Fapi%2Frtbserver%2Fcookie%3Fi%3DUN%26uid%3D%5BRX_UUID%5D',
  'https://rtb.openx.net/sync/prebid?gdpr={{GDPR}}&gdpr_consent={{GDPR_CONSENT}}&r=https%3A%2F%2Fa-prebid.vidoomy.com%2Fsetuid%3Fbidder%3Dopenx%26uid%3D$%7BUID%7D',
  'https://ads.pubmatic.com/AdServer/js/user_sync.html?gdpr={{GDPR}}&gdpr_consent={{GDPR_CONSENT}}&us_privacy=&predirect=https%3A%2F%2Fa-prebid.vidoomy.com%2Fsetuid%3Fbidder%3Dpubmatic%26gdpr%3D{{GDPR}}%26gdpr_consent%3D{{GDPR_CONSENT}}%26uid%3D',
  'https://cm.adform.net/cookie?redirect_url=https%3A%2F%2Fa-prebid.vidoomy.com%2Fsetuid%3Fbidder%3Dadf%26gdpr%3D{{GDPR}}%26gdpr_consent%3D{{GDPR_CONSENT}}%26uid%3D%24UID',
  'https://ups.analytics.yahoo.com/ups/58531/occ?gdpr={{GDPR}}&gdpr_consent={{GDPR_CONSENT}}',
  'https://ap.lijit.com/pixel?redir=https%3A%2F%2Fa-prebid.vidoomy.com%2Fsetuid%3Fbidder%3Dsovrn%26gdpr%3D{{GDPR}}%26gdpr_consent%3D{{GDPR_CONSENT}}%26uid%3D%24UID'
];

const isBidRequestValid = bid => {
  if (!bid.params) {
    logError(BIDDER_CODE + ': bid.params should be non-empty');
    return false;
  }

  if (!+bid.params.pid) {
    logError(BIDDER_CODE + ': bid.params.pid should be non-empty Number');
    return false;
  }

  if (!+bid.params.id) {
    logError(BIDDER_CODE + ': bid.params.id should be non-empty Number');
    return false;
  }

  if (bid.params && bid.params.mediaTypes && bid.params.mediaTypes.video && bid.params.mediaTypes.video.context === INSTREAM && !bid.params.mediaTypes.video.playerSize) {
    logError(BIDDER_CODE + ': bid.params.mediaType.video should have a playerSize property to tell player size when is INSTREAM');
    return false;
  }

  if (bid.params.bidfloor && (isNaN(bid.params.bidfloor) || bid.params.bidfloor < 0)) {
    logError(BIDDER_CODE + ': bid.params.bidfloor should be a number equal or greater than zero');
    return false;
  }

  return true;
};

const isBidResponseValid = bid => {
  if (!bid || !bid.requestId || !bid.cpm || !bid.ttl || !bid.currency) {
    return false;
  }
  switch (bid.mediaType) {
    case BANNER:
      return Boolean(bid.width && bid.height && bid.ad);
    case VIDEO:
      return Boolean(bid.vastUrl || bid.vastXml);
    default:
      return false;
  }
}

const buildRequests = (validBidRequests, bidderRequest) => {
  const serverRequests = validBidRequests.map(bid => {
    let adType = BANNER;
    let sizes;
    if (bid.mediaTypes && bid.mediaTypes[BANNER] && bid.mediaTypes[BANNER].sizes) {
      sizes = bid.mediaTypes[BANNER].sizes;
      adType = BANNER;
    } else if (bid.mediaTypes && bid.mediaTypes[VIDEO] && bid.mediaTypes[VIDEO].playerSize) {
      sizes = bid.mediaTypes[VIDEO].playerSize;
      adType = VIDEO;
    }
    const [w, h] = (parseSizesInput(sizes)[0] || '0x0').split('x');

    const aElement = document.createElement('a');
    aElement.href = (bidderRequest.refererInfo && bidderRequest.refererInfo.referer) || top.location.href;
    const hostname = aElement.hostname

    const videoContext = deepAccess(bid, 'mediaTypes.video.context');
    const bidfloor = deepAccess(bid, `params.bidfloor`, 0);

    const queryParams = {
      id: bid.params.id,
      adtype: adType,
      auc: bid.adUnitCode,
      w,
      h,
      pos: parseInt(bid.params.position) || 1,
      ua: navigator.userAgent,
      l: navigator.language && navigator.language.indexOf('-') !== -1 ? navigator.language.split('-')[0] : '',
      dt: /Mobi/.test(navigator.userAgent) ? 2 : 1,
      pid: bid.params.pid,
      requestId: bid.bidId,
      schain: bid.schain || '',
      bidfloor,
      d: getDomainWithoutSubdomain(hostname), // 'vidoomy.com',
      sp: encodeURIComponent(aElement.href),
      usp: bidderRequest.uspConsent || '',
      coppa: !!config.getConfig('coppa'),
      videoContext: videoContext || ''
    };

    if (bidderRequest.gdprConsent) {
      queryParams.gdpr = bidderRequest.gdprConsent.gdprApplies;
      queryParams.gdprcs = bidderRequest.gdprConsent.consentString;
    }

    return {
      method: 'GET',
      url: ENDPOINT,
      data: queryParams
    }
  });
  return serverRequests;
};

const render = (bid) => {
  bid.ad = bid.vastUrl;
  var obj = {
    vastTimeout: 5000,
    maxAllowedVastTagRedirects: 3,
    allowVpaid: true,
    autoPlay: true,
    preload: true,
    mute: true,
  }
  window.outstreamPlayer(bid, bid.adUnitCode, obj);
}

const interpretResponse = (serverResponse, bidRequest) => {
  try {
    let responseBody = serverResponse.body;
    if (!responseBody) return;
    if (responseBody.mediaType === 'video') {
      responseBody.ad = responseBody.vastUrl || responseBody.vastXml;
      const videoContext = bidRequest.data.videoContext;

      if (videoContext === OUTSTREAM) {
        try {
          const renderer = Renderer.install({
            id: bidRequest.bidId,
            adunitcode: bidRequest.tagId,
            loaded: false,
            config: responseBody.mediaType,
            url: responseBody.meta.rendererUrl
          });
          renderer.setRender(render);

          responseBody.renderer = renderer;
        } catch (e) {
          responseBody.ad = responseBody.vastUrl || responseBody.vastXml;
          logError(BIDDER_CODE + ': error while installing renderer to show outstream ad');
        }
      }
    }
    const bid = {
      ad: responseBody.ad,
      renderer: responseBody.renderer,
      mediaType: responseBody.mediaType,
      requestId: responseBody.requestId,
      cpm: responseBody.cpm,
      currency: responseBody.currency,
      width: responseBody.width,
      height: responseBody.height,
      creativeId: responseBody.creativeId,
      netRevenue: responseBody.netRevenue,
      ttl: responseBody.ttl,
      meta: {
        mediaType: responseBody.meta.mediaType,
        rendererUrl: responseBody.meta.rendererUrl,
        advertiserDomains: responseBody.meta.advertiserDomains,
        advertiserId: responseBody.meta.advertiserId,
        advertiserName: responseBody.meta.advertiserName,
        agencyId: responseBody.meta.agencyId,
        agencyName: responseBody.meta.agencyName,
        brandId: responseBody.meta.brandId,
        brandName: responseBody.meta.brandName,
        dchain: responseBody.meta.dchain,
        networkId: responseBody.meta.networkId,
        networkName: responseBody.meta.networkName,
        primaryCatId: responseBody.meta.primaryCatId,
        secondaryCatIds: responseBody.meta.secondaryCatIds
      }
    };
    if (responseBody.vastUrl) {
      bid.vastUrl = responseBody.vastUrl;
    } else if (responseBody.vastXml) {
      bid.vastXml = responseBody.vastXml;
    }

    const bids = [];

    if (isBidResponseValid(bid)) {
      bids.push(bid);
    } else {
      logError(BIDDER_CODE + ': server returns invalid response');
    }

    return bids;
  } catch (e) {
    logError(BIDDER_CODE + ': error parsing server response to Prebid format');
    return [];
  }
};

function getUserSyncs (syncOptions, responses, gdprConsent, uspConsent) {
  if (syncOptions.iframeEnabled || syncOptions.pixelEnabled) {
    const pixelType = syncOptions.pixelEnabled ? 'image' : 'iframe';
    const urls = deepAccess(responses, '0.body.pixels') || COOKIE_SYNC_FALLBACK_URLS;

    return [].concat(urls).map(url => ({
      type: pixelType,
      url: url
        .replace('{{GDPR}}', gdprConsent ? (gdprConsent.gdprApplies ? '1' : '0') : '0')
        .replace('{{GDPR_CONSENT}}', gdprConsent ? encodeURIComponent(gdprConsent.consentString) : '')
        .replace('{{USP_CONSENT}}', uspConsent ? encodeURIComponent(uspConsent) : '')
    }));
  }
};

export const spec = {
  code: BIDDER_CODE,
  supportedMediaTypes: [BANNER, VIDEO],
  isBidRequestValid,
  buildRequests,
  interpretResponse,
  gvlid: GVLID,
  getUserSyncs,
};

registerBidder(spec);

function getDomainWithoutSubdomain (hostname) {
  const parts = hostname.split('.');
  const newParts = [];
  for (let i = parts.length - 1; i >= 0; i--) {
    newParts.push(parts[i]);
    if (newParts.length !== 1 && parts[i].length > 3) {
      break;
    }
  }
  return newParts.reverse().join('.');
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.Projects;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestWindow.Extensibility;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.TestAdapter;

namespace Microsoft.PythonTools.TestAdapter {
    [Export(typeof(ITestContainerDiscoverer))]
    [Export(typeof(TestContainerDiscoverer))]
    class TestContainerDiscoverer : ITestContainerDiscoverer, IDisposable {
        private readonly IServiceProvider _serviceProvider;
        private readonly SolutionEventsListener _solutionListener;
        private readonly Dictionary<PythonProject, ProjectInfo> _projectInfo;
        private bool _firstLoad, _isDisposed;
        public const string ExecutorUriString = "executor://PythonTestExecutor/v1";
        public static readonly Uri _ExecutorUri = new Uri(ExecutorUriString);

        [ImportingConstructor]
        private TestContainerDiscoverer([Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider, [Import(typeof(IOperationState))]IOperationState operationState)
            : this(serviceProvider,
                   new SolutionEventsListener(serviceProvider),
                    operationState) { }

        internal bool IsProjectKnown(IVsProject project) {
            var pyProj = project as IPythonProjectProvider;
            if (pyProj != null) {
                return _projectInfo.ContainsKey(pyProj.Project);
            }
            return false;
        }

        public TestContainerDiscoverer(IServiceProvider serviceProvider,
                                       SolutionEventsListener solutionListener,
                                       IOperationState operationState) {
            ValidateArg.NotNull(serviceProvider, "serviceProvider");
            ValidateArg.NotNull(solutionListener, "solutionListener");
            ValidateArg.NotNull(operationState, "operationState");

            _projectInfo = new Dictionary<PythonProject, ProjectInfo>();

            _serviceProvider = serviceProvider;

            _solutionListener = solutionListener;
            _solutionListener.ProjectLoaded += OnProjectLoaded;
            _solutionListener.ProjectUnloading += OnProjectUnloaded;
            _solutionListener.ProjectClosing += OnProjectUnloaded;

            _firstLoad = true;
        }

        void IDisposable.Dispose() {
            if (!_isDisposed) {
                _isDisposed = true;
                _solutionListener.Dispose();
            }
        }

        public Uri ExecutorUri {
            get {
                return _ExecutorUri;
            }
        }

        public IEnumerable<ITestContainer> TestContainers {
            get {
                if (_firstLoad) {
                    // Get current solution
                    var solution = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution));
                    // The first time through, we don't know about any loaded
                    // projects.
                    _firstLoad = false;
                    foreach (var project in EnumerateLoadedProjects(solution)) {
                        OnProjectLoaded(null, new ProjectEventArgs(project));
                    }
                    _solutionListener.StartListeningForChanges();
                }

                return _projectInfo.Values.SelectMany(x => x._containers).Select(x => x.Value);
            }
        }

        public TestContainer GetTestContainer(PythonProject project, string path) {
            ProjectInfo projectInfo;
            if (_projectInfo.TryGetValue(project, out projectInfo)) {
                TestContainer container;
                if (projectInfo._containers.TryGetValue(path, out container)) {
                    return container;
                }
            }

            return null;
        }

        private static IEnumerable<IVsProject> EnumerateLoadedProjects(IVsSolution solution) {
            var guid = new Guid(PythonConstants.ProjectFactoryGuid);
            IEnumHierarchies hierarchies;
            ErrorHandler.ThrowOnFailure((solution.GetProjectEnum(
                (uint)(__VSENUMPROJFLAGS.EPF_MATCHTYPE | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION),
                ref guid,
                out hierarchies)));
            IVsHierarchy[] hierarchy = new IVsHierarchy[1];
            uint fetched;
            while (ErrorHandler.Succeeded(hierarchies.Next(1, hierarchy, out fetched)) && fetched == 1) {
                var project = hierarchy[0] as IVsProject;
                if (project != null) {
                    yield return project;
                }
            }
        }

        public event EventHandler TestContainersUpdated;

        private void OnProjectLoaded(object sender, ProjectEventArgs e) {
            if (e.Project != null) {
                var provider = e.Project as IPythonProjectProvider;
                if (provider != null) {
                    var analyzer = provider.Project.Analyzer;
                    var projectInfo = new ProjectInfo(this, provider.Project);
                    _projectInfo[provider.Project] = projectInfo;

                    foreach (var file in analyzer.Files) {
                        projectInfo.AnalysisComplete(this, new AnalysisCompleteEventArgs(file));
                    }
                }
            }

            TestContainersUpdated?.Invoke(this, EventArgs.Empty);
        }

        class ProjectInfo {
            private readonly PythonProject _project;
            private readonly TestContainerDiscoverer _discoverer;
            public readonly Dictionary<string, TestContainer> _containers;

            public ProjectInfo(TestContainerDiscoverer discoverer, PythonProject project) {
                _project = project;
                _discoverer = discoverer;
                _containers = new Dictionary<string, TestContainer>(StringComparer.OrdinalIgnoreCase);

                project.ProjectAnalyzerChanged += ProjectAnalyzerChanged;
                RegisterWithAnalyzer();
            }

            private void RegisterWithAnalyzer() {
                _project.Analyzer.RegisterExtension(typeof(TestAnalyzer).Assembly.CodeBase);
                _project.Analyzer.AnalysisComplete += AnalysisComplete;
            }

            public async void AnalysisComplete(object sender, AnalysisCompleteEventArgs e) {
                var testCaseData = await _project.Analyzer.SendExtensionCommandAsync(
                    TestAnalyzer.Name,
                    TestAnalyzer.GetTestCasesCommand,
                    e.Path
                );

                if (testCaseData == null) {
                    return;
                }
                var testCases = TestAnalyzer.GetTestCases(testCaseData);

                if (testCases.Length != 0) {
                    TestContainer existing;
                    bool changed = true;
                    if (_containers.TryGetValue(e.Path, out existing)) {
                        // we have an existing entry, let's see if any of the tests actually changed.
                        if (existing.TestCases.Length == testCases.Length) {
                            changed = false;

                            for (int i = 0; i < existing.TestCases.Length; i++) {
                                if (!existing.TestCases[i].Equals(testCases[i])) {
                                    changed = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (changed) {
                        // we have a new entry or some of the tests changed
                        int version = (existing?.Version ?? 0) + 1;
                        _containers[e.Path] = new TestContainer(
                            _discoverer,
                            e.Path,
                            _project,
                            version,
                            Architecture,
                            testCases
                        );

                        ContainersChanged();
                    }
                } else if (_containers.Remove(e.Path)) {
                    // Raise containers changed event...
                    ContainersChanged();
                }
            }

            private Architecture Architecture {
                get {
                    return Architecture.X86;
                }
            }

            private void ContainersChanged() {
                _discoverer.TestContainersUpdated?.Invoke(_discoverer, EventArgs.Empty);
            }

            public void ProjectAnalyzerChanged(object sender, EventArgs e) {
                RegisterWithAnalyzer();
            }
        }

        private void OnProjectUnloaded(object sender, ProjectEventArgs e) {
            if (e.Project != null) {
                var provider = e.Project as IPythonProjectProvider;
                ProjectInfo events;
                if (provider != null && _projectInfo.TryGetValue(provider.Project, out events)) {
                    var analyzer = provider.Project.Analyzer;

                    provider.Project.ProjectAnalyzerChanged -= events.ProjectAnalyzerChanged;
                    analyzer.AnalysisComplete -= events.AnalysisComplete;

                    _projectInfo.Remove(provider.Project);
                }
            }

            TestContainersUpdated?.Invoke(this, EventArgs.Empty);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
The Learntris Challenge
=======================

This repository contains a series of automated tests that
will guide you through implementing your own version of
a famous falling blocks game.

The game is a fairly small project suitable for beginners
who understand the basic concepts of programming, or for
veteran developers looking to pick up a new language.

Along the way, it will expose you to some common software
engineering tools and practices that might not be familiar
to new developers.

 * version control with git
 * process automation
 * coding to an interface
 * inter-process communication
 * test-driven/behavior-driven development
 * creating a simple domain-specific language

**Note:** *This is not a tutorial.*

While the tests are "about" a video game, the real purpose
of this exercise is to force you to "fend for yourself" on
a project, without relying on tutorial-style guidance.

Instead, the tests present a series of problems that you
will need to solve in order to implement the game.

*It is entirely up to you how to write the code.*

The tests themselves are written in python, but you are free
to implement your game in any language you like.

**Getting Started**

The first step is to clone or fork this repo and run `testris.py`.
You will need a recent version of python, preferably python3.2 or later.
(Python is *only* for the test runner. You can use any language you want to
write your implementation.)

The output of `testris.py` will tell you what needs to be done at every
step alonge the way. Just keep running it, and do what it tells you to do.

The wiki here has a couple pages on [Getting Set Up](https://github.com/LearnProgramming/learntris/wiki/Getting-Set-Up) and [Understanding the Test Results](https://github.com/LearnProgramming/learntris/wiki/Understanding-the-Test-results).

If you get stuck, please come join us in #learnprogramming on irc.freenode.net, or
post a question to [/r/lpmc](http://reddit.com/r/lpmc/) at reddit, and we'll
try to help you sort it out.


text:
package org.apache.hyracks.storage.am.lsm.invertedindex.search;

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

import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.ErrorCode;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.primitive.ShortPointable;
import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder;
import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleReference;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.api.IIndexOperationContext;
import org.apache.hyracks.storage.am.common.tuples.ConcatenatingTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInPlaceInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexSearchModifier;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IPartitionedInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.InvertedListCursor;
import org.apache.hyracks.storage.common.IIndexCursor;

/**
 * Conducts T-Occurrence searches on inverted lists in one or more partition.
 */
public class PartitionedTOccurrenceSearcher extends AbstractTOccurrenceSearcher {

    protected final ArrayTupleBuilder lowerBoundTupleBuilder = new ArrayTupleBuilder(1);
    protected final ArrayTupleReference lowerBoundTuple = new ArrayTupleReference();
    protected final ArrayTupleBuilder upperBoundTupleBuilder = new ArrayTupleBuilder(1);
    protected final ArrayTupleReference upperBoundTuple = new ArrayTupleReference();
    protected final ConcatenatingTupleReference fullLowSearchKey = new ConcatenatingTupleReference(2);
    protected final ConcatenatingTupleReference fullHighSearchKey = new ConcatenatingTupleReference(2);
    protected final InvertedListPartitions partitions = new InvertedListPartitions();

    // To keep the current state of this search
    protected int curPartIdx;
    protected int endPartIdx;
    protected int numPrefixLists;
    protected boolean isFinalPartIdx;
    protected boolean needToReadNewPart;
    List<InvertedListCursor>[] partitionCursors;
    IInvertedIndexSearchModifier searchModifier;

    public PartitionedTOccurrenceSearcher(IInPlaceInvertedIndex invIndex, IHyracksTaskContext ctx)
            throws HyracksDataException {
        super(invIndex, ctx);
        initHelperTuples();
        curPartIdx = 0;
        endPartIdx = 0;
        isFinalPartIdx = false;
        isFinishedSearch = false;
        needToReadNewPart = true;
    }

    private void initHelperTuples() {
        try {
            lowerBoundTupleBuilder.reset();
            // Write dummy value.
            lowerBoundTupleBuilder.getDataOutput().writeShort(Short.MIN_VALUE);
            lowerBoundTupleBuilder.addFieldEndOffset();
            lowerBoundTuple.reset(lowerBoundTupleBuilder.getFieldEndOffsets(), lowerBoundTupleBuilder.getByteArray());
            // Only needed for setting the number of fields in searchKey.
            searchKey.reset(queryTokenAppender, 0);
            fullLowSearchKey.reset();
            fullLowSearchKey.addTuple(searchKey);
            fullLowSearchKey.addTuple(lowerBoundTuple);

            upperBoundTupleBuilder.reset();
            // Write dummy value.
            upperBoundTupleBuilder.getDataOutput().writeShort(Short.MAX_VALUE);
            upperBoundTupleBuilder.addFieldEndOffset();
            upperBoundTuple.reset(upperBoundTupleBuilder.getFieldEndOffsets(), upperBoundTupleBuilder.getByteArray());
            // Only needed for setting the number of fields in searchKey.
            searchKey.reset(queryTokenAppender, 0);
            fullHighSearchKey.reset();
            fullHighSearchKey.addTuple(searchKey);
            fullHighSearchKey.addTuple(upperBoundTuple);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void search(IIndexCursor resultCursor, InvertedIndexSearchPredicate searchPred, IIndexOperationContext ictx)
            throws HyracksDataException {
        prepareSearch();
        IPartitionedInvertedIndex partInvIndex = (IPartitionedInvertedIndex) invIndex;
        finalSearchResult.reset();
        if (partInvIndex.isEmpty()) {
            isFinishedSearch = true;
            resultCursor.open(null, searchPred);
            return;
        }
        tokenizeQuery(searchPred);
        short numQueryTokens = (short) queryTokenAppender.getTupleCount();

        searchModifier = searchPred.getSearchModifier();
        short numTokensLowerBound = searchModifier.getNumTokensLowerBound(numQueryTokens);
        short numTokensUpperBound = searchModifier.getNumTokensUpperBound(numQueryTokens);
        occurrenceThreshold = searchModifier.getOccurrenceThreshold(numQueryTokens);
        if (occurrenceThreshold <= 0) {
            throw HyracksDataException.create(ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION);
        }

        short maxCountPossible = numQueryTokens;
        invListCursorCache.reset();
        partitions.reset(numTokensLowerBound, numTokensUpperBound);
        for (int i = 0; i < numQueryTokens; i++) {
            searchKey.reset(queryTokenAppender, i);
            if (!partInvIndex.openInvertedListPartitionCursors(this, ictx, numTokensLowerBound, numTokensUpperBound,
                    partitions)) {
                maxCountPossible--;
                // No results possible.
                if (maxCountPossible < occurrenceThreshold) {
                    // Closes all opened cursors.
                    closeCursorsInPartitions(partitions);
                    isFinishedSearch = true;
                    resultCursor.open(null, searchPred);
                    return;
                }
            }
        }

        partitionCursors = partitions.getPartitions();
        short start = partitions.getMinValidPartitionIndex();
        short end = partitions.getMaxValidPartitionIndex();

        // Process the partitions one-by-one.
        endPartIdx = end;
        for (int i = start; i <= end; i++) {
            // Prune partition because no element in it can satisfy the occurrence threshold.
            if (partitionCursors[i] == null) {
                continue;
            }
            // Prune partition because no element in it can satisfy the occurrence threshold.
            // An opened cursor should be closed.
            if (partitionCursors[i].size() < occurrenceThreshold) {
                for (InvertedListCursor cursor : partitionCursors[i]) {
                    cursor.close();
                }
                continue;
            }
            // Merge inverted lists of current partition.
            numPrefixLists = searchModifier.getNumPrefixLists(occurrenceThreshold, partitionCursors[i].size());
            invListMerger.reset();
            curPartIdx = i;
            isFinalPartIdx = i == end ? true : false;

            // If the number of inverted list cursor is one, then we don't need to go through the merge process
            // for this partition.
            if (partitionCursors[i].size() == 1) {
                singleInvListCursor = partitionCursors[i].get(0);
                singleInvListCursor.prepareLoadPages();
                singleInvListCursor.loadPages();
                isSingleInvertedList = true;
                needToReadNewPart = true;
            } else {
                singleInvListCursor = null;
                isSingleInvertedList = false;
                needToReadNewPart = invListMerger.merge(partitionCursors[i], occurrenceThreshold, numPrefixLists,
                        finalSearchResult);
                searchResultBuffer = finalSearchResult.getNextFrame();
                searchResultTupleIndex = 0;
                searchResultFta.reset(searchResultBuffer);
            }

            // By now, some output was generated by the merger or only one cursor in this partition is associated.
            // So, we open the cursor that will fetch these result. If it's the final partition, the outside of
            // this for loop will handle opening of the result cursor for a single inverted list cursor case.
            if (needToReadNewPart && isFinalPartIdx) {
                invListMerger.close();
                finalSearchResult.finalizeWrite();
                isFinishedSearch = true;
            }
            resultCursor.open(null, searchPred);
            return;
        }

        // The control reaches here if the above loop doesn't have any valid cursor.
        isFinishedSearch = true;
        needToReadNewPart = true;
        resultCursor.open(null, searchPred);
        return;
    }

    /**
     * Continues a search process in case of the following two cases:
     * #1. If it was paused because the output buffer of the final result was full.
     * #2. All tuples from a single inverted list has been read.
     *
     * @return true only if all processing for the final list for the final partition is done.
     *         false otherwise.
     * @throws HyracksDataException
     */
    @Override
    public boolean continueSearch() throws HyracksDataException {
        if (isFinishedSearch) {
            return true;
        }

        // Case #1 only - output buffer was full
        if (!needToReadNewPart) {
            needToReadNewPart = invListMerger.continueMerge();
            searchResultBuffer = finalSearchResult.getNextFrame();
            searchResultTupleIndex = 0;
            searchResultFta.reset(searchResultBuffer);
            // Final calculation done?
            if (needToReadNewPart && isFinalPartIdx) {
                isFinishedSearch = true;
                invListMerger.close();
                finalSearchResult.finalizeWrite();
                return true;
            }
            return false;
        }

        // Finished one partition for the both cases #1 and #2. So, moves to the next partition.
        curPartIdx++;
        if (curPartIdx <= endPartIdx) {
            boolean suitablePartFound = false;
            for (int i = curPartIdx; i <= endPartIdx; i++) {
                // Prune partition because no element in it can satisfy the occurrence threshold.
                if (partitionCursors[i] == null) {
                    continue;
                }
                // Prune partition because no element in it can satisfy the occurrence threshold.
                // An opened cursor should be closed.
                if (partitionCursors[i].size() < occurrenceThreshold) {
                    for (InvertedListCursor cursor : partitionCursors[i]) {
                        cursor.close();
                    }
                    continue;
                }
                suitablePartFound = true;
                curPartIdx = i;
                break;
            }

            // If no partition is availble to explore, we stop here.
            if (!suitablePartFound) {
                isFinishedSearch = true;
                invListMerger.close();
                finalSearchResult.finalizeWrite();
                return true;
            }

            // Merge inverted lists of current partition.
            numPrefixLists = searchModifier.getNumPrefixLists(occurrenceThreshold, partitionCursors[curPartIdx].size());
            invListMerger.reset();
            finalSearchResult.resetBuffer();
            isFinalPartIdx = curPartIdx == endPartIdx ? true : false;

            // If the number of inverted list cursor is one, then we don't need to go through the merge process.
            if (partitionCursors[curPartIdx].size() == 1) {
                singleInvListCursor = partitionCursors[curPartIdx].get(0);
                singleInvListCursor.prepareLoadPages();
                singleInvListCursor.loadPages();
                isSingleInvertedList = true;
                needToReadNewPart = true;
            } else {
                singleInvListCursor = null;
                isSingleInvertedList = false;
                needToReadNewPart = invListMerger.merge(partitionCursors[curPartIdx], occurrenceThreshold,
                        numPrefixLists, finalSearchResult);
                searchResultBuffer = finalSearchResult.getNextFrame();
                searchResultTupleIndex = 0;
                searchResultFta.reset(searchResultBuffer);
            }

            // Finished processing one partition
            if (needToReadNewPart && isFinalPartIdx) {
                invListMerger.close();
                finalSearchResult.finalizeWrite();
                isFinishedSearch = true;
                return true;
            }

        } else {
            isFinishedSearch = true;
        }

        return false;
    }

    private void closeCursorsInPartitions(InvertedListPartitions parts) throws HyracksDataException {
        List<InvertedListCursor>[] partCursors = parts.getPartitions();
        short start = parts.getMinValidPartitionIndex();
        short end = parts.getMaxValidPartitionIndex();
        for (int i = start; i <= end; i++) {
            if (partCursors[i] == null) {
                continue;
            }
            for (InvertedListCursor cursor : partCursors[i]) {
                cursor.close();
            }
        }
    }

    public void setNumTokensBoundsInSearchKeys(short numTokensLowerBound, short numTokensUpperBound) {
        ShortPointable.setShort(lowerBoundTuple.getFieldData(0), lowerBoundTuple.getFieldStart(0), numTokensLowerBound);
        ShortPointable.setShort(upperBoundTuple.getFieldData(0), upperBoundTuple.getFieldStart(0), numTokensUpperBound);
    }

    public ITupleReference getPrefixSearchKey() {
        return searchKey;
    }

    public ITupleReference getFullLowSearchKey() {
        return fullLowSearchKey;
    }

    public ITupleReference getFullHighSearchKey() {
        return fullHighSearchKey;
    }

    public InvertedListCursor getCachedInvertedListCursor() throws HyracksDataException {
        return invListCursorCache.getNext();
    }

}


text:
package org.unbescape.csv;

import org.junit.Test;

import static org.unbescape.csv.CsvEscapeTestUtil.testEscape;
import static org.unbescape.csv.CsvEscapeTestUtil.testUnescape;

/**
 *
 * @author Daniel Fernández
 *
 * @since 1.0
 *
 */
public class CsvEscape02Test {

    private static final String TEXT_UNESC =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789";
    private static final String TEXT_ESC =
            "\"ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789\"";

    @Test
    public void test() throws Exception {

        testEscape(TEXT_UNESC, TEXT_ESC);
        testUnescape(TEXT_ESC, TEXT_UNESC);

    }

    public CsvEscape02Test() {
        super();
    }

}


text:
package com.dropbox.core.v1;

import com.dropbox.core.json.JsonArrayReader;
import com.dropbox.core.json.JsonReadException;
import com.dropbox.core.json.JsonReader;
import com.dropbox.core.util.Dumpable;
import com.dropbox.core.util.DumpWriter;
import static com.dropbox.core.util.StringUtil.jq;

import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

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

/*>>> import checkers.nullness.quals.Nullable; */

/**
 * Represents a single "page" of results from a delta-style API call.
 *
 * @param <MD>
 *     The type of metadata being returned in the delta results.  For example, in the
 *     {@link DbxClientV1#getDelta}, this has type {@link DbxEntry}.
 */
public final class DbxDelta<MD extends Dumpable> extends Dumpable
{
    /**
     * If {@code true}, then you should reset your local state to be an empty
     * folder before processing the list of delta entries.
     *
     *

     * This is always {@code true} for the first delta result, but for subsequent results
     * it is true only in {@code true} rare situations.  For example, if Dropbox
     * changes their cursor format, or if a user asks Dropbox to completely reset his/her
     * account, then the next time you call a delta API it may send down a reset and
     * start you from scratch.
     *

     */
    public final boolean reset;

    /**
     * Apply these entries to your local state to catch up with the Dropbox server's state.
     */
    public final List<Entry<MD>> entries;

    /**
     * A string that is used by the server to keep track of which entries have already been
     * returned to you.  This is what you pass in to the next API call to continue where you
     * left off.
     *
     *

     * This cursor is valid for a long time.  You'd typically store this somewhere persistent
     * (such as a database) so you can resume continue you left off.
     *

     */
    public final String cursor;

    /**
     * If {@code true}, then there are more entries available.  You can retrieve
     * them immediately by making the call again (passing in {@link #cursor}).
     * If {@code false}, then wait at least 5 minutes before checking again.
     */
    public final boolean hasMore;

    /**
     * @param reset {@link #reset}
     * @param entries {@link #entries}
     * @param cursor {@link #cursor}
     * @param hasMore {@link #hasMore}
     */
    public DbxDelta(boolean reset, List<Entry<MD>> entries, String cursor, boolean hasMore)
    {
        this.reset = reset;
        this.entries = entries;
        this.cursor = cursor;
        this.hasMore = hasMore;
    }

    protected void dumpFields(DumpWriter out)
    {
        out.f("reset").v(reset);
        out.f("hasMore").v(hasMore);
        out.f("cursor").v(cursor);
        out.f("entries").v(entries);
    }

    /**
     * For JSON parsing.
     */
    public static final class Reader<MD extends Dumpable> extends JsonReader<DbxDelta<MD>>
    {
        public final JsonReader<MD> metadataReader;

        public Reader(JsonReader<MD> metadataReader)
        {
            this.metadataReader = metadataReader;
        }

        public DbxDelta<MD> read(JsonParser parser) throws IOException, JsonReadException
        {
            return read(parser, metadataReader);
        }

        public static <MD extends Dumpable> DbxDelta<MD> read(JsonParser parser, JsonReader<MD> metadataReader)
            throws IOException, JsonReadException
        {
            JsonLocation top = JsonReader.expectObjectStart(parser);

            Boolean reset = null;
            List<Entry<MD>> entries = null;
            String cursor = null;
            Boolean has_more = null;

            while (parser.getCurrentToken() == JsonToken.FIELD_NAME) {
                String fieldName = parser.getCurrentName();
                JsonReader.nextToken(parser);

                int fi = FM.get(fieldName);
                try {
                    if (fi == -1) {
                        // Unknown field.  Skip over it.
                        JsonReader.skipValue(parser);
                        continue;
                    }
                    switch (fi) {
                        case FM_reset: reset = JsonReader.BooleanReader.readField(parser, fieldName, reset); break;
                        case FM_entries:
                            JsonReader<Entry<MD>> entryReader = new Entry.Reader<MD>(metadataReader);
                            entries = JsonArrayReader.mk(entryReader).readField(parser, fieldName, entries);
                            break;
                        case FM_cursor: cursor = JsonReader.StringReader.readField(parser, fieldName, cursor); break;
                        case FM_has_more: has_more = JsonReader.BooleanReader.readField(parser, fieldName, has_more); break;
                        default:
                            throw new AssertionError("bad index: " + fi + ", field = \"" + fieldName + "\"");
                    }
                }
                catch (JsonReadException ex) {
                    throw ex.addFieldContext(fieldName);
                }
            }

            JsonReader.expectObjectEnd(parser);

            if (reset == null) throw new JsonReadException("missing field \"path\"", top);
            if (entries == null) throw new JsonReadException("missing field \"entries\"", top);
            if (cursor == null) throw new JsonReadException("missing field \"cursor\"", top);
            if (has_more == null) throw new JsonReadException("missing field \"has_more\"", top);

            return new DbxDelta<MD>(reset, entries, cursor, has_more);
        }

        private static final int FM_reset = 0;
        private static final int FM_entries = 1;
        private static final int FM_cursor = 2;
        private static final int FM_has_more = 3;
        private static final JsonReader.FieldMapping FM;

        static {
            JsonReader.FieldMapping.Builder b = new JsonReader.FieldMapping.Builder();
            b.add("reset", FM_reset);
            b.add("entries", FM_entries);
            b.add("cursor", FM_cursor);
            b.add("has_more", FM_has_more);
            FM = b.build();
        }
    }

    /**
     * A single "delta entry" in a {@link DbxDelta} page.
     *
     * @param <MD>
     *     The type of metadata being returned in the delta results.
     */
    public static final class Entry<MD extends Dumpable> extends Dumpable
    {
        /**
         * The lower-cased path of the entry.  Dropbox compares file paths in a
         * case-insensitive manner.  For example, an entry for {@code "/readme.txt"}
         * should overwrite the entry for {@code "/ReadMe.TXT"}.
         *
         *

         * To get the original case-preserved path, look in the {@link #metadata} field.
         *

         */
        public final String lcPath;

        /**
         * If this is {@code null}, it means that this path doesn't exist on
         * on Dropbox's copy of the file system.  To update your local state to
         * match, delete whatever is at that path, including any children.
         * If your local state doesn't have anything at this path, ignore this entry.
         *
         *

         * If this is not {@code null}, it means that Dropbox has a file/folder
         * at this path with the given metadata.  To update your local state to match,
         * add the entry to your local state as well.
         *

         *

         *

         *     If the path refers to parent folders that don't exist yet in your local
         *     state, create those parent folders in your local state.
         *

         *

         *     If the metadata is for a file, replace whatever your local state has at
         *     that path with the new entry.
         *

         *

         *     If the metadata is for a folder, check what your local state has at the
         *     path.  If it's a file, replace it with the new entry.  If it's a folder,
         *     apply the new metadata to the folder, but do not modify the folder's
         *     children.
         *

         *

         */
        public final /*@Nullable*/MD metadata;

        /**
         * @param lcPath {@link #lcPath}
         * @param metadata {@link #metadata}
         */
        public Entry(String lcPath, /*@Nullable*/MD metadata)
        {
            this.lcPath = lcPath;
            this.metadata = metadata;
        }

        protected void dumpFields(DumpWriter out)
        {
            out.f("lcPath").v(lcPath);
            out.f("metadata").v(metadata);
        }

        /**
         * For JSON parsing.
         */
        public static final class Reader<MD extends Dumpable> extends JsonReader<Entry<MD>>
        {
            public final JsonReader<MD> metadataReader;

            public Reader(JsonReader<MD> metadataReader)
            {
                this.metadataReader = metadataReader;
            }

            public Entry<MD> read(JsonParser parser) throws IOException, JsonReadException
            {
                return read(parser, metadataReader);
            }

            public static <MD extends Dumpable> Entry<MD> read(JsonParser parser, JsonReader<MD> metadataReader)
                throws IOException, JsonReadException
            {
                JsonLocation arrayStart = JsonReader.expectArrayStart(parser);

                if (JsonReader.isArrayEnd(parser)) {
                    throw new JsonReadException("expecting a two-element array of [path, metadata], found a zero-element array", arrayStart);
                }

                String lcPath;
                try {
                    lcPath = JsonReader.StringReader.read(parser);
                }
                catch (JsonReadException ex) {
                    throw ex.addArrayContext(0);
                }

                if (JsonReader.isArrayEnd(parser)) {
                    throw new JsonReadException("expecting a two-element array of [path, metadata], found a one-element array: " + jq(lcPath), arrayStart);
                }

                /*@Nullable*/MD metadata;
                try {
                    metadata = metadataReader.readOptional(parser);
                }
                catch (JsonReadException ex) {
                    throw ex.addArrayContext(1);
                }

                if (!JsonReader.isArrayEnd(parser)) {
                    throw new JsonReadException("expecting a two-element array of [path, metadata], found non \"]\" token after the two elements: " + parser.getCurrentToken(), arrayStart);
                }

                parser.nextToken();

                return new Entry<MD>(lcPath, metadata);
            }
        }
    }
}


text:
package scala.meta.tests
package compat

import org.scalatest._
import scala.tools.nsc.Settings
import scala.tools.nsc.interpreter._

class ReplSuite extends FunSuite {
  private def repl(code: String): String = {
    val s = new Settings
    s.Xnojline.value = true
    s.usejavacp.value = false
    s.classpath.value = sys.props("sbt.paths.scalahost.classes")
    val lines = ILoop.runForTranscript(code, s).lines.toList
    lines.drop(3).map(_.replaceAll("\\s+$","")).mkString("\n").trim.stripSuffix("scala>").trim
  }

  test("semantic APIs") {
    assert(repl("""
      |import scala.meta._
      |import scala.meta.dialects.Scala211
      |implicit val mirror = Mirror(Artifact(sys.props("sbt.paths.scalalibrary.classes")))
      |t"List[Int]" <:< t"List[Any]"
    """.stripMargin.trim)
    .replace(sys.props("sbt.paths.scalalibrary.classes"), "<path/to/scala-library.jar>")
    === """
      |scala> import scala.meta._
      |import scala.meta._
      |
      |scala> import scala.meta.dialects.Scala211
      |import scala.meta.dialects.Scala211
      |
      |scala> implicit val mirror = Mirror(Artifact(sys.props("sbt.paths.scalalibrary.classes")))
      |mirror: scala.meta.Mirror = Mirror(Artifact("<path/to/scala-library.jar>", "", Scala211))
      |
      |scala> t"List[Int]" <:< t"List[Any]"
      |res0: Boolean = true
      |
      |scala> :quit
    """.stripMargin.trim)
  }
}


text:
/*
 *  hy_stm32.h
 *
 *  Author: Kestutis Bivainis
 */

#ifndef _HY_STM32_H_
#define _HY_STM32_H_

typedef enum {
  LED1 = 0,
  LED2 = 1,
  LED3 = 2,
  LED4 = 3
} Led_TypeDef;

typedef enum {
  BUTTON1 = 0,
  BUTTON2 = 1,
  BUTTON3 = 2,
  BUTTON4 = 3,
} Button_TypeDef;

typedef enum {
  BUTTON_MODE_GPIO = 0,
  BUTTON_MODE_EXTI = 1
} ButtonMode_TypeDef;

#define LEDn 4

#define LED1_PIN  GPIO_Pin_6
#define LED1_PORT GPIOC
#define LED1_BUS  RCC_APB2Periph_GPIOC

#define LED2_PIN  GPIO_Pin_7
#define LED2_PORT GPIOC
#define LED2_BUS  RCC_APB2Periph_GPIOC

#define LED3_PIN  GPIO_Pin_13
#define LED3_PORT GPIOD
#define LED3_BUS  RCC_APB2Periph_GPIOD

#define LED4_PIN  GPIO_Pin_6
#define LED4_PORT GPIOD
#define LED4_BUS  RCC_APB2Periph_GPIOD

#define BUTTONn 4

#define BUTTON1_PIN        GPIO_Pin_5
#define BUTTON1_PORT       GPIOE
#define BUTTON1_BUS        RCC_APB2Periph_GPIOE
#define BUTTON1_AFIO_BUS   RCC_APB2Periph_AFIO
#define BUTTON1_PORTSOURCE GPIO_PortSourceGPIOE
#define BUTTON1_PINSOURCE  GPIO_PinSource5
#define BUTTON1_EXTI_LINE  EXTI_Line5
#define BUTTON1_EXTI_IRQN  EXTI9_5_IRQn

#define BUTTON2_PIN        GPIO_Pin_4
#define BUTTON2_PORT       GPIOE
#define BUTTON2_BUS        RCC_APB2Periph_GPIOE
#define BUTTON2_AFIO_BUS   RCC_APB2Periph_AFIO
#define BUTTON2_PORTSOURCE GPIO_PortSourceGPIOE
#define BUTTON2_PINSOURCE  GPIO_PinSource4
#define BUTTON2_EXTI_LINE  EXTI_Line4
#define BUTTON2_EXTI_IRQN  EXTI4_IRQn

#define BUTTON3_PIN        GPIO_Pin_3
#define BUTTON3_PORT       GPIOE
#define BUTTON3_BUS        RCC_APB2Periph_GPIOE
#define BUTTON3_AFIO_BUS   RCC_APB2Periph_AFIO
#define BUTTON3_PORTSOURCE GPIO_PortSourceGPIOE
#define BUTTON3_PINSOURCE  GPIO_PinSource3
#define BUTTON3_EXTI_LINE  EXTI_Line3
#define BUTTON3_EXTI_IRQN  EXTI3_IRQn

#define BUTTON4_PIN        GPIO_Pin_2
#define BUTTON4_PORT       GPIOE
#define BUTTON4_BUS        RCC_APB2Periph_GPIOE
#define BUTTON4_AFIO_BUS   RCC_APB2Periph_AFIO
#define BUTTON4_PORTSOURCE GPIO_PortSourceGPIOE
#define BUTTON4_PINSOURCE  GPIO_PinSource2
#define BUTTON4_EXTI_LINE  EXTI_Line2
#define BUTTON4_EXTI_IRQN  EXTI2_IRQn

#define BUZZER_PIN  GPIO_Pin_0
#define BUZZER_PORT GPIOE
#define BUZZER_BUS  RCC_APB2Periph_GPIOE

void BSP_LED_Init(Led_TypeDef Led);
void BSP_LEDs_Init(void);
void BSP_LED_On(Led_TypeDef Led);
void BSP_LED_Off(Led_TypeDef Led);
void BSP_LED_Toggle(Led_TypeDef Led);

void BSP_Button_Init(Button_TypeDef Button, ButtonMode_TypeDef ButtonMode);
void BSP_Buttons_Init(ButtonMode_TypeDef ButtonMode);
uint32_t BSP_Button_GetState(Button_TypeDef Button);

void BSP_Buzzer_Init(void);
void BSP_Buzzer_On(void);
void BSP_Buzzer_Off(void);

#endif


text:
'use strict';

const mongoose = require('mongoose');
const db = require('../../../lib/db');

const Schema = mongoose.Schema;

const ReportSchema = new Schema({
    worker_id: {type: Schema.Types.ObjectId, ref: 'Worker'},
    stack: String
}, {_id: false});

const TaskSchema = exports.TaskSchema = new Schema({
    dt: Date,
    username: String,

    server_id: {type: Schema.Types.ObjectId, ref: 'Server', index: true},
    //workers: [{type: Schema.Types.ObjectId, ref: 'Worker'}],

    target_id: {type: String},

    status: {type: Number, index: true},
    module: {type: String, index: true},
    cmd: {type: String, index: true},
    params: String,

    internal_error: String,

    error: [ReportSchema],
    report: [ReportSchema]
});

TaskSchema.pre('save', function (next) {
    if (!this.isModified('dt')) {
        this.dt = new Date();
    }

    if (!this.isModified('status')) {
        this.status = -1;
    }

    let search = null;

    if (this.target_id && this.target_id[0] === 'W') {
        search = db.WorkerModel;
    } else if (this.target_id && this.target_id[0] === 'G') {
        search = db.WorkersGroupModel;
    } else if (this.target_id === 'SERVER') {
        return next();
    } else {
        return next(new Error('Unsupported target id'));
    }

    search.findOne({sys_id: this.target_id}, 'server_id', (err, item) => {
        if (err) {
            next(err);
        } else if (!item) {
            next(new Error(`Target "${this.target_id}" not found`));
        } else {
            this.server_id = item.server_id;
            next();
        }
    });
});

mongoose.model('Task', TaskSchema);


text:
using System;
using System.Runtime.InteropServices;

namespace NSspi.Credentials
{
    /// <summary>
    /// Provides authentication data in native method calls.
    /// </summary>
    /// <remarks>
    /// Implements the 'SEC_WINNT_AUTH_IDENTITY' structure. See:
    ///
    /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa380131(v=vs.85).aspx
    /// </remarks>
    [StructLayout( LayoutKind.Sequential )]
    internal struct NativeAuthData
    {
        public NativeAuthData( string domain, string username, string password, NativeAuthDataFlag flag )
        {
            this.Domain = domain;
            this.DomainLength = domain.Length;

            this.User = username;
            this.UserLength = username.Length;

            this.Password = password;
            this.PasswordLength = password.Length;

            this.Flags = flag;
        }

        [MarshalAs( UnmanagedType.LPWStr )]
        public string User;

        public int UserLength;

        [MarshalAs( UnmanagedType.LPWStr )]
        public string Domain;

        public int DomainLength;

        [MarshalAs( UnmanagedType.LPWStr )]
        public string Password;

        public int PasswordLength;

        public NativeAuthDataFlag Flags;
    }

    internal enum NativeAuthDataFlag : int
    {
        Ansi = 1,

        Unicode = 2
    }
}


text:
function output = SPDToLinSPD(input,B)
% output = SPDToLinSPD(input,B)
%
% Find the best fitting spectrum within a linear model.
%
% output - spectrum within the linear model
%  (n-wavelengths by number-of-lights)
% input - source spectral power distribution
%  (n-wavelengths by number-of-lights)
% B - linear model for spectral power distributions
%  (number-of-wavelengths by n-dimension)
%
% History:
% 30/11/07  Change call to non-existent SPDToLinWgts.m into call to
%           FindModelWeights.m, as suggested by Mickey Rowe.         (MK)

% Just expand the weights, which we find
% in function FindModelWeights
output = B*FindModelWeights(input,B);


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NUnit Engine")]
[assembly: AssemblyDescription("Provides a common interface for loading, exploring and running NUnit tests")]
[assembly: AssemblyCulture("")]

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

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5796938b-03c9-4b75-8b43-89a8adc4acd0")]


text:
FROM ubuntu:22.04

ENV DEBIAN_FRONTEND noninteractive
ENV PATH /home/builder/.cargo/bin:$PATH

RUN apt-get update \
    && apt-get upgrade --assume-yes \
    && apt install --assume-yes --no-install-recommends ca-certificates wget gnupg2

ARG cxx_package=g++-12

RUN apt-get update \
    && apt-get install --assume-yes --no-install-recommends \
        build-essential $cxx_package libsqlite3-dev libcurl4-openssl-dev libssl-dev \
        libxml2-dev libstfl-dev libjson-c-dev libncursesw5-dev gettext git \
        pkg-config zlib1g-dev asciidoctor \
    && apt-get autoremove \
    && apt-get clean

RUN addgroup --gid 1000 builder \
    && adduser --home /home/builder --uid 1000 --ingroup builder \
        --disabled-password --shell /bin/bash builder \
    && mkdir -p /home/builder/src \
    && chown -R builder:builder /home/builder

RUN apt-get install locales \
    && echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen \
    && echo 'ru_RU.KOI8-R KOI8-R' >> /etc/locale.gen \
    && echo 'ru_RU.CP1251 CP1251' >> /etc/locale.gen \
    && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8

USER builder
WORKDIR /home/builder/src

ARG rust_version=1.65.0

RUN wget -O $HOME/rustup.sh --secure-protocol=TLSv1_2 https://sh.rustup.rs \
    && chmod +x $HOME/rustup.sh \
    && $HOME/rustup.sh -y \
        --default-host x86_64-unknown-linux-gnu \
        --default-toolchain $rust_version \
    && chmod a+w $HOME/.cargo

ENV HOME /home/builder

ARG cc=gcc-12
ARG cxx=g++-12

ENV CC=$cc
ENV CXX=$cxx


text:
<video controls></video>

Test that QuickTime file with unsupported track types only generates an error.


text:
title: "Seuraavalle tunnille"
tags: läksyt rub3.2 rub3.3
---

Lue ja suomenna teksti 2 ja tee siihen liittyv sisältöharjoitus 1 s. 37.


text:
<!DOCTYPE HTML>

  <title>Lokesh Soni | Index</title>
  <meta charset="utf-8"/>
  <meta name="description" content="Lokesh Soni Personal Website. I'm a nerd/introvert who loves to play with code and create something awesome.">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css?family=Karla|Open+Sans:400,600,700" rel="stylesheet">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <link rel="stylesheet" href="assests/index.css" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

            </button>

Lokesh Soni

Home

About Me

Skills

Career

Contact Me

Blog

Lokesh Soni

20, Student

  "Most People Die at 25,And are not buried Till 75"

About Me

Hi, I'm Lokesh Soni

Currently freshman student from India with major in Information Technology. I lover to code and talk about the fascinating ideas.

Currently i'm involved with 2 startup as the cofounder. I love to travel and meet people with Ideas.

To Know More About Me Click Here

At Glance

Education

Jecrc,Jaipur
Information Technology 2015-19

From

Jaipur
Rajasthan

Experience

Open Source Projects
Startups

        BLOGS

        My braincandy

Medium

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Start Reading

Recode

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Start Reading

Techcrunch

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Start Reading

Hacker News

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Start Reading

Google Developer

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Start Reading

Muzli

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Start Reading

        Tools

Atom

Atom is a text editor that's modern, approachable, yet hackable to the core.

Visual Studio

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Xcode

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Android Studio

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Google Suite

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Github

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Photoshop

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Slack

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

Unity

Invision's blog has been my best buddy in learning about product & design. 'Inside Design' is the coolest section that they have with global Design Teams.

At Glance

"12 Hours,3 Cups Of Coffee & 3 Sleep Nap"

was used to create this site

Made With Love


text: Scala + Play + Akka + ScalaJS + React + React.Native


text:
package com.icss.hit.bean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.icss.hit.bean.interfaces.meetingLaunchDao;
import com.icss.hit.hibernate.HibernateSessionFactory;
import com.icss.hit.hibernate.vo.Meeting;
import com.icss.hit.hibernate.vo.MeetingAttend;
import com.icss.hit.hibernate.vo.Message;
import com.icss.hit.hibernate.vo.ReceiverInfo;
import com.icss.hit.hibernate.vo.Room;
import com.icss.hit.hibernate.vo.SysDept;
import com.icss.hit.hibernate.vo.SysUser;

/**
 * @author ÕÔÓ±Éê
 * ÓÃÓÚ·¢Æð»áÒéʹÓõÄ
 */
public class MeetingLaunchBean implements meetingLaunchDao {

	public int getConflict(String beginTime, String endTime,long uid, String meetingRoom) {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		long rid = Long.parseLong(meetingRoom);
		int timeOut=0;
		String hql1 = "select count(rr.rrId) from RoomReg rr inner join rr.sysUser s inner join rr.room r where s.suId=? and r.RId=? and rr.rrBegintime<=to_date(?,'yyyy-mm-dd hh24:mi:ss') and rr.rrEndtime>=to_date(?,'yyyy-mm-dd hh24:mi:ss')";

		try {
			tx = sess.beginTransaction();
			// ¼ÆËã³öÏÔʾҳÆð'±àºÅ
			Query query = sess.createQuery(hql1).setLong(0, uid).setLong(1, rid).setString(2, beginTime).setString(3, endTime);
			Object obj1 = query.uniqueResult();
			timeOut = Integer.parseInt(obj1.toString());

			tx.commit();
			if( timeOut>0 )
			{
				return 0;     //ûÓгåÍ»
			}
			else return 1;    //ÓгåÍ»
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return -1;        //ÓдíÎó
		} finally {
			sess.close();
		}
	}

	public long saveMeetingUsers(MeetingAttend meetingAttend) {
		// TODO Auto-generated method stub
		String mesID = null;
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();

			 sess.save(meetingAttend);

			tx.commit();
			return meetingAttend.getMaId();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return -1;
		} finally {
			sess.close();
		}
	}

	public long saveMeetingMessage(Meeting meeting) {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();

			sess.save(meeting);

			tx.commit();
			return meeting.getMtId();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return -1;
		} finally {
			sess.close();
		}
	}

	public long getAccess(long uid){
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx=null;
		String hql="select count(rr.rrId) from RoomReg rr inner join rr.sysUser s where s.suId=? and rr.rrPass='1'";
		try {
			tx = sess.beginTransaction();
			Query query = sess.createQuery(hql).setLong(0, uid);
			tx.commit();
			Object o = query.uniqueResult();
			return Long.parseLong(o.toString());
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return -1;
		} finally {
			sess.close();
		}
	}

	public List<Room> getRooms(long uid)
	{
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx=null;
		List<Room> rooms= new ArrayList<Room>();
		String hql="select r.RId from RoomReg rr inner join rr.sysUser s inner join rr.room r where s.suId=? and rr.rrPass='1'";
		String hql1 = "from Room r where r.RId=?";
		try {
			tx = sess.beginTransaction();
			Query query = sess.createQuery(hql).setLong(0, uid);
			List l = query.list();
			Iterator it = l.iterator();
			while (it.hasNext()) {
				Object obj = (Object) it.next();
				long rid = (Long)obj;
				System.out.println(rid);
				Room room = new Room();
				Query query1 = sess.createQuery(hql1).setLong(0, rid);
				Object o=  query1.uniqueResult();
				room=(Room)o;
				System.out.println(room);
				rooms.add(room);
			}
			tx.commit();
			return rooms;
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return null;
		} finally {
			sess.close();
		}
	}

	public int timeConflict(String beginTime, String endTime,long uid, String meetingRoom) {
		// TODO Auto-generated method stub
		Session sess = HibernateSessionFactory.getSession();
		Transaction tx = null;
		long rid = Long.parseLong(meetingRoom);
		int timeOut=0;
		int sum=0;
		String hqlNull ="select count(rr.rrId) from RoomReg rr inner join rr.sysUser s inner join rr.room r " +
				"where r.RId=? and rr.rrPass = '1'";
		String hql1 = "select count(rr.rrId) from RoomReg rr inner join rr.sysUser s inner join" +
				" rr.room r where r.RId=? and rr.rrPass = '1' and (rr.rrBegintime>=to_date(?,'yyyy-mm-dd hh24:mi:ss')" +
				" or rr.rrEndtime<=to_date(?,'yyyy-mm-dd hh24:mi:ss'))";

		try {
			tx = sess.beginTransaction();
			Query query1 = sess.createQuery(hqlNull).setLong(0, rid);
			Object obj2 = query1.uniqueResult();
			sum = Integer.parseInt(obj2.toString());
			// ¼ÆËã³öÏÔʾҳÆð'±àºÅ
			Query query = sess.createQuery(hql1).setLong(0, rid).setString(1, endTime).setString(2, beginTime);
			Object obj1 = query.uniqueResult();
			timeOut = Integer.parseInt(obj1.toString());
				System.out.println(sum +"----------"+timeOut);
			tx.commit();
			if( timeOut==sum )
			{
				return 0;     //ûÓгåÍ»
			}
			else return 1;    //ÓгåÍ»

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return -1;        //ÓдíÎó
		} finally {
			sess.close();
		}
	}
}


text:
Developer Documentation
=====================================

This page describes how to setup a working development environment that can be used in developing stackube on Ubuntu or
CentOS. These instructions assume you're already installed git, golang and python on your host.

=========
Design Tips
=========

The Stackube project is very simple. The main part of it is a ``stackube-controller``, which use Kubernetes ``Customized Resource Definition (CRD, previous TPR)`` to:

1. Manage tenants based on namespace change in k8s
2. Manage RBAC based on namespace change in k8s
3. Manage networks based on tenants change in k8s

The tenant is a CRD which maps to Keystone tenant, the network is a CRD which maps to Neutron network. We also have a ``kubestack`` binary which is the CNI plug-in for Neutron.

Also, Stackube has it's own ``stackube-proxy`` to replace ``kube-proxy`` because network in Stackube is L2 isolated, so we need a multi-tenant version ``kube-proxy`` here.

We also replaced ``kube-dns`` in k8s for the same reason: we need to have a ``kube-dns`` running in every namespace instead of a global DNS server because namespaces are isolated.

You can see that:

::

Stackube cluster = upstream Kubernetes + several our own add-ons + standalone OpenStack components.

Please note: Cinder RBD based block device as volume is implemented in https://github.com/kubernetes/frakti, you need to contribute there if you have any idea and build a new stackube/flex-volume Docker image for Stackube to use.

=========
Build
=========

Build binary:

::

  make

The binary will be placed at:

::

  _output/kubestack
  _output/stackube-controller
  _output/stackube-proxy

Build docker images:

::

  make docker

Three docker images will be built:

::

  stackube/stackube-proxy:v1.0beta
  stackube/stackube-controller:v1.0beta
  stackube/kubestack:v1.0beta

===========================
(Optional) Configure Stackube
===========================

If you deployed Stackube by following official guide, you can skip this part.

But if not, these steps below are needed to make sure your Stackube cluster work.

Please note the following parts suppose you have already deployed an environment of OpenStack and Kubernetes on same baremetal host. And don't forget to setup ``--experimental-keystone-url`` for ``kube-apiserver``, e.g.

::

    kube-apiserver --experimental-keystone-url=https://192.168.128.66:5000/v2.0 ...

Remove ``kube-dns`` deployment and ``kube-proxy`` daemonset if you have already running them.

::

  kubectl -n kube-system delete deployment kube-dns
  kubectl -n kube-system delete daemonset kube-proxy

If you have also configured a CNI network plugin, you should also remove it together with CNI network config.

::

  # Remove CNI network components, e.g. deployments or daemonsets first.
  # Then remove CNI network config.
  rm -f /etc/cni/net.d/*

Then create external network in Neutron if there is no one.

::

  # Create an external network if there is no one.
  # Please replace 10.123.0.x with your own external network
  # and remember the id of your created external network
  neutron net-create br-ex --router:external=True --shared
  neutron subnet-create --ip_version 4 --gateway 10.123.0.1 br-ex 10.123.0.0/16 --allocation-pool start=10.123.0.2,end=10.123.0.200 --name public-subnet

And create configure file for Stackube.

::

  # Remember to replace them with your own ones.
  cat >stackube-configmap.yaml <<EOF
  kind: ConfigMap
  apiVersion: v1
  metadata:
    name: stackube-config
    namespace: kube-system
  data:
    auth-url: "https://192.168.128.66/identity_admin/v2.0"
    username: "admin"
    password: "admin"
    tenant-name: "admin"
    region: "RegionOne"
    ext-net-id: "550370a3-4fc2-4494-919d-cae33f5b3de8"
    plugin-name: "ovs"
    integration-bridge: "br-int"
    user-cidr: "10.244.0.0/16"
    user-gateway: "10.244.0.1"
    kubernetes-host: "192.168.0.33"
    kubernetes-port: "6443"
    keyring: "AQBZU5lZ/Z7lEBAAJuC17RYjjqIUANs2QVn7pw=="
  EOF

Then deploy stackube components:

::

  kubectl create -f stackube-configmap.yaml
  kubectl create -f deployment/stackube-proxy.yaml
  kubectl create -f deployment/stackube.yaml
  kubectl create -f deployment/flexvolume/flexvolume-ds.yaml

Now, you are ready to try Stackube features.


text:
<?php

namespace Database\Factories;

use App\Models\ContactInformation;
use App\Models\Student;
use Illuminate\Database\Eloquent\Factories\Factory;

class ContactInformationFactory extends Factory
{
    protected $model = ContactInformation::class;

    public function definition(): array
    {
        $studentNids = Student::pluck('nid')->toArray();
        $option = $this->faker->numberBetween(1, 15);

        return [
            'student_nid' => $this->faker->randomElement($studentNids),
            'phone'       => $option & 1 ? $this->faker->phoneNumber : null,
            'email'       => $option & 2 ? $this->faker->email : null,
            'facebook'    => $option & 4 ? $this->faker->url : null,
            'line'        => $option & 8 ? $this->faker->userName : null,
        ];
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Danske Agaricaceer 2: (1911)

#### Original name
Crepidotus mollis var. tomentosus S. Petersen

### Remarks
null


text:
{-# LANGUAGE FlexibleInstances #-}

{- |
Module      : Language.Egison.PrettyMath.AST
Licence     : MIT
-}

module Language.Egison.PrettyMath.AST
  ( MathExpr(..)
  , MathIndex(..)
  , ToMathExpr(..)
  , isSub
  , parseExpr
  ) where

import           Data.Foldable                 (toList)
import           Text.ParserCombinators.Parsec hiding (spaces)

import qualified Language.Egison.Data          as E
import qualified Language.Egison.IExpr         as E
import qualified Language.Egison.Math.Expr     as E

data MathExpr
  = Atom String [MathIndex]
  | NegativeAtom String
  | Plus [MathExpr]
  | Multiply [MathExpr]
  | Div MathExpr MathExpr
  | Power MathExpr MathExpr
  | Func MathExpr [MathExpr]
  | Tensor [MathExpr] [MathIndex]
  | Tuple [MathExpr]
  | Collection [MathExpr]
  | Quote MathExpr
  | Partial MathExpr [MathExpr]
  deriving (Eq, Show)

data MathIndex
  = Super MathExpr
  | Sub MathExpr
  deriving (Eq, Show)

isSub :: MathIndex -> Bool
isSub (Sub _) = True
isSub _       = False

class ToMathExpr a where
  toMathExpr :: a -> MathExpr

instance ToMathExpr E.EgisonValue where
  toMathExpr (E.ScalarData s)  = toMathExpr s
  toMathExpr (E.Tuple es)      = Tuple (map toMathExpr es)
  toMathExpr (E.Collection es) = Collection (map toMathExpr (toList es))
  toMathExpr (E.TensorData t)  = toMathExpr t
  toMathExpr e                 = Atom (show e) []

instance ToMathExpr a => ToMathExpr (E.Tensor a) where
  toMathExpr (E.Scalar _)       = undefined
  toMathExpr (E.Tensor [_] xs js) = Tensor (map toMathExpr (toList xs)) (map toMathIndex js)
  toMathExpr (E.Tensor [_, n] xs js) = Tensor (f (fromIntegral n) (map toMathExpr (toList xs))) (map toMathIndex js)
    where
      f _ [] = []
      f n xs = Tensor (take n xs) [] : f n (drop n xs)
  toMathExpr (E.Tensor _ _ _) = undefined

instance ToMathExpr E.ScalarData where
  toMathExpr (E.Div p (E.Plus [E.Term 1 []])) = toMathExpr p
  toMathExpr (E.Div p1 p2)                    = Div (toMathExpr p1) (toMathExpr p2)

instance ToMathExpr E.PolyExpr where
  toMathExpr (E.Plus [])  = Atom "0" []
  toMathExpr (E.Plus [x]) = toMathExpr x
  toMathExpr (E.Plus xs)  = Plus (map toMathExpr xs)

instance ToMathExpr E.TermExpr where
  toMathExpr (E.Term n [])  = toMathExpr n
  toMathExpr (E.Term 1 [x]) = toMathExpr x
  toMathExpr (E.Term 1 xs)  = Multiply (map toMathExpr xs)
  toMathExpr (E.Term n xs)  = Multiply (toMathExpr n : map toMathExpr xs)

instance ToMathExpr Integer where
  toMathExpr n | n < 0 = NegativeAtom (show (-n))
  toMathExpr n         = Atom (show n) []

instance {-# OVERLAPPING #-} ToMathExpr (E.SymbolExpr, Integer) where
  toMathExpr (x, 1) = toMathExpr x
  toMathExpr (x, n) = Power (toMathExpr x) (toMathExpr n)

instance ToMathExpr E.SymbolExpr where
  toMathExpr (E.Symbol _ (':':':':':':_) []) = Atom "#" []
  toMathExpr (E.Symbol _ s js) = toMathExpr' js (Atom s [])
    where
      toMathExpr' [] acc = acc
      toMathExpr' (E.User x:js) (Partial e ps) =
        toMathExpr' js (Partial e (ps ++ [toMathExpr x]))
      toMathExpr' (E.User x:js) e@Atom{} =
        toMathExpr' js (Partial e [toMathExpr x])
      toMathExpr' (j:js) (Atom e is) =
        toMathExpr' js (Atom e (is ++ [toMathIndex j]))
      toMathExpr' _ _ = undefined -- TODO

  toMathExpr (E.Apply fn mExprs) =
    case (toMathExpr fn, mExprs) of
      (Atom "^" [], [x, y]) -> Power (toMathExpr x) (toMathExpr y)
      _                     -> Func (toMathExpr fn) (map toMathExpr mExprs)
  toMathExpr (E.Quote mExpr) = Quote (toMathExpr mExpr)
  toMathExpr (E.FunctionData (E.SingleTerm 1 [(E.Symbol _ s js, 1)]) _ _) = toMathExpr' js (Atom s [])
    where
      toMathExpr' [] acc = acc
      toMathExpr' (E.User x:js) (Partial e ps) =
        toMathExpr' js (Partial e (ps ++ [toMathExpr x]))
      toMathExpr' (E.User x:js) e@Atom{} =
        toMathExpr' js (Partial e [toMathExpr x])
      toMathExpr' (j:js) (Atom e is) =
        toMathExpr' js (Atom e (is ++ [toMathIndex j]))
      toMathExpr' _ _ = undefined -- TODO

toMathIndex :: ToMathExpr a => E.Index a -> MathIndex
toMathIndex (E.Sub x) = Sub (toMathExpr x)
toMathIndex (E.Sup x) = Super (toMathExpr x)
toMathIndex _         = undefined -- TODO

--
-- Parser
--

spaces :: Parser ()
spaces = skipMany1 space

spaces0 :: Parser ()
spaces0 = skipMany space

symbol :: Parser Char
symbol = oneOf "!$%&*+-/:<=>?@#"

parseAtom :: Parser MathExpr
parseAtom = Atom <$> ((:) <$> (letter <|> symbol <|> digit) <*> many (letter <|> digit <|> symbol)) <*> many parseScript

parseAtom' :: Parser MathExpr
parseAtom' = flip Atom [] <$> ((:) <$> (letter <|> symbol <|> digit) <*> many (letter <|> digit <|> symbol))

parsePartial :: Parser MathExpr
parsePartial = Partial <$> parseAtom <*> many1 (char '|' >> parseAtom)

parseNegativeAtom :: Parser MathExpr
parseNegativeAtom = char '-' >> NegativeAtom <$> ((:) <$> (letter <|> symbol <|> digit) <*> many (letter <|> digit <|> symbol))

parseList :: Parser [MathExpr]
parseList = sepEndBy parseExpr spaces

parseScript :: Parser MathIndex
parseScript = Sub <$> (char '_' >> parseAtom')
              <|> Super <$> (char '~' >> parseAtom')

parsePlus :: Parser MathExpr
parsePlus = try (string "(+") >> spaces >> Plus <$> parseList <* char ')'

parseMultiply :: Parser MathExpr
parseMultiply = try (string "(*") >> spaces >> Multiply <$> parseList <* char ')'

parseDiv :: Parser MathExpr
parseDiv = try (string "(/") >> spaces >> Div <$> parseExpr <*> (spaces >> parseExpr) <* char ')'

parseFunction :: Parser MathExpr
parseFunction = char '(' >> Func <$> parseAtom <* spaces <*> parseList <* char ')'

parseTensor :: Parser MathExpr
parseTensor = string "[|" >> spaces0 >> Tensor <$> parseList <* spaces0 <* string "|]" <*> many parseScript

parseTuple :: Parser MathExpr
parseTuple = char '[' >> Tuple <$> parseList <* char ']'

parseCollection :: Parser MathExpr
parseCollection = char '{' >> Collection <$> parseList <* char '}'

parseQuote :: Parser MathExpr
parseQuote = char '\'' >> Quote <$> parseExpr'

parseExpr' :: Parser MathExpr
parseExpr' = parseNegativeAtom
         <|> try parsePartial
         <|> parseAtom
         <|> parseQuote
         <|> parsePlus
         <|> parseMultiply
         <|> parseDiv
         <|> try parseFunction
         <|> try parseTensor
         <|> try parseTuple
         <|> try parseCollection

parseExpr :: Parser MathExpr
parseExpr = do
  x <- parseExpr'
  option x $ Power x <$> try (char '^' >> parseExpr')


text:
import subprocess, json

# TODO: can't guarantee the output is valid JSON, so need to do error checks
output = subprocess.check_output(['./GetContacts.applescript'], stderr=subprocess.STDOUT)

print 'Content-Type: application/json'
print ''
# TODO: make 'ok' actually contingent on quality of output
print json.dumps({'ok': True, 'body': output})


text:
import '../index.less'
import { generatorSubRouter } from '@common/router'

export default ({ routes }) => {
  return generatorSubRouter(routes, '第一章')
}


text:
package com.greenpepper.server.database.hibernate;

import java.net.URL;

import com.greenpepper.server.GreenPepperServerException;
import com.greenpepper.server.configuration.ServerConfiguration;
import com.greenpepper.server.database.hibernate.hsqldb.AbstractDBUnitHibernateMemoryTest;
import com.greenpepper.server.domain.SystemInfo;
import com.greenpepper.server.domain.dao.SystemInfoDao;
import com.greenpepper.server.domain.dao.hibernate.HibernateSystemInfoDao;

public class BootstrapDataTest extends AbstractDBUnitHibernateMemoryTest
{
    private URL configURL = BootstrapDataTest.class.getResource("configuration-test.xml");
    private BootstrapData boot;
    private SystemInfoDao systemDao;

    protected void setUp() throws Exception
    {
        super.setUp();

        ServerConfiguration config = ServerConfiguration.load(configURL);
        config.getProperties().setProperty("baseUrl", "no directories");

        boot = new BootstrapData(this, config.getProperties());
        systemDao = new HibernateSystemInfoDao(this);
    }

    public void tearDown()
    {
    }

    public void testWhileUpgradingIfAnErrorOccuresTheBootstrapProcessWillAbortAndProvoqueARollBack() throws Exception
    {
    	try
    	{
			setupSystemInfo("VERSION.THAT.WILL.CAUSE.A.FAILURE");
			boot.execute();
			fail();
		}
    	catch (GreenPepperServerException e)
    	{
			assertEquals("Boostrap Failure", e.getMessage());
		}

        assertNull(systemDao.getSystemInfo());
    }

    public void testWhileRegistratingTheRunnersIfAnErrorOccuresTheBootstrapProcessWillContinue() throws Exception
    {
    	boot.execute();
    	assertNotNull(systemDao.getSystemInfo());
    }

	private void setupSystemInfo(String gpVersion)
	{
		SystemInfo sysForServerOfCurrentVersion = new SystemInfo();
		sysForServerOfCurrentVersion.setVersion(0);
		sysForServerOfCurrentVersion.setGpVersion(gpVersion);
		systemDao.store(sysForServerOfCurrentVersion);
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package AppDAOs;

import AppServices.DownloadThread;
import AppServices.Lock;
import AppServices.Streamer;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author lukasgreiner
 */
public class DownloadStreamer {
    private DownloadThread dt = null;
    private ArrayList<Streamer> strem = new ArrayList<>();

    public DownloadStreamer(ArrayList<String> streamerString) {
        Lock lock = new Lock();
        for (String url : streamerString) {
            dt = new DownloadThread(url, lock,strem);
            dt.start();
        }
        while (lock.getRunningThreadsNumber() > 0) {
            Lock lock2 = lock;
            synchronized (lock2) {
                try {
                    lock.wait();
                } catch (InterruptedException ex) {
                    Logger.getLogger(DownloadStreamer.class.getName()).log(Level.SEVERE, null, ex);
                }
                continue;
            }

        }
    }

    public ArrayList<Streamer> getStreamer() {
        return strem;
    }

}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('tenancy', '0001_initial'),
        ('ipam', '0005_auto_20160725_1842'),
    ]

    operations = [
        migrations.AddField(
            model_name='vlan',
            name='tenant',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='vlans', to='tenancy.Tenant'),
        ),
        migrations.AddField(
            model_name='vrf',
            name='tenant',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='vrfs', to='tenancy.Tenant'),
        ),
    ]


text:
(function () { return this; })().dojoConfig = {
	// Since we are loading the Dojo 1 AMD loader to emulate the normal environment of our modules more closely,
	// we need to disable actions within the loader that will cause requests to occur before the loader is reconfigured;
	// if `async` is not set, the loader will immediately try to synchronously load all of `dojo/main`
	async: true,
	// has-configuration gets shared between Intern and Dojo 1, which currently causes some problems in Intern code
	// if the `config-deferredInstrumentation` has rule is true (it is by default), so force it off
	deferredInstrumentation: false
};

// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// A fully qualified URL to the Intern proxy
	proxyUrl: 'http://localhost:9000/',

	// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
	// specified browser environments in the `environments` array below as well. See
	// https://code.google.com/p/selenium/wiki/DesiredCapabilities for standard Selenium capabilities and
	// https://saucelabs.com/docs/additional-config#desired-capabilities for Sauce Labs capabilities.
	capabilities: {
		'selenium-version': '2.42.2'
	},

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		{ browserName: 'internet explorer', version: '11', platform: 'Windows 8.1' },
		{ browserName: 'internet explorer', version: '10', platform: 'Windows 8' },
		{ browserName: 'internet explorer', version: '9', platform: 'Windows 7' },
		{ browserName: 'firefox', version: '28', platform: [ 'OS X 10.9', 'Windows 7', 'Linux' ] },
		{ browserName: 'chrome', version: '34', platform: [ 'OS X 10.9', 'Windows 7', 'Linux' ] },
		{ browserName: 'safari', version: '6', platform: 'OS X 10.8' },
		{ browserName: 'safari', version: '7', platform: 'OS X 10.9' }
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: Infinity,

	// Name of the tunnel class to use for WebDriver tests
	tunnel: 'SauceLabsTunnel',

	// The desired AMD loader to use when running unit tests (client.html). Here we are using the Dojo loader that
	// our app actually uses to ensure that things are as similar as possible between the test environment and the
	// actual end-user environment
	useLoader: {
		'host-browser': '../../src/dojo/dojo.js'
	},

	// Configuration options for the module loader; any AMD configuration options supported by the specified AMD loader
	// can be used here
	loader: {
		// Packages that should be registered with the loader in each testing environment;
		// to test a built version of the application, `src` can be changed to `dist`
		packages: [
			{ name: 'app', location: 'src/app' },
			{ name: 'dgrid', location: 'src/dgrid' },
			{ name: 'dijit', location: 'src/dijit' },
			{ name: 'dojo', location: 'src/dojo' },
			{ name: 'dojox', location: 'src/dojox' },
			{ name: 'put-selector', location: 'src/put-selector' },
			{ name: 'xstyle', location: 'src/xstyle' },
			{ name: 'tests', location: 'tests' }
		]
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ 'tests/unit/Dialog' ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ 'tests/functional/index' ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	// In the case of the boilerplate, we only want to know about stuff from `app`
	excludeInstrumentation: /^(?:tests|node_modules|src\/(?:dgrid|dijit|dojo|dojox|put-selector|xstyle))\//
});


text:
<?php

abstract class KirbytextAbstract {

  static public $tags = array();
  static public $pre  = array();
  static public $post = array();

  public $field;

  public function __construct($field, $page = null) {

    if(is_a($field, 'Field')) {
      $this->field = $field;
    } else if(is_array($field)) {
      throw new Exception('Kirbytext cannot handle arrays');
    } else if(empty($field) or is_string($field)) {
      if(!$page) $page = page();
      $this->field = new Field($page, null, $field);
    }

  }

  public function field() {
    return $this->field;
  }

  public function parse() {

    if(!$this->field) return '';

    $text = $this->field->value;

    // pre filters
    foreach(static::$pre as $filter) {
      $text = call_user_func_array($filter, array($this, $text));
    }

    // tagsify
    $text = preg_replace_callback('!(?=[^\]])\([a-z0-9_-]+:.*?\)!is', array($this, 'tag'), $text);

    // markdownify
    $text = kirby::instance()->component('markdown')->parse($text, $this->field);

    // smartypantsify
    $text = kirby::instance()->component('smartypants')->parse($text, false, $this->field);

    // post filters
    foreach(static::$post as $filter) {
      $text = call_user_func_array($filter, array($this, $text));
    }

    return $text;

  }

  public function tag($input) {

    // remove the brackets
    $tag  = trim(rtrim(ltrim($input[0], '('), ')'));
    $name = trim(substr($tag, 0, strpos($tag, ':')));

    // if the tag is not installed return the entire string
    if(!isset(static::$tags[$name])) return $input[0];

    try {
      $tag = new Kirbytag($this, $name, $tag);
      return $tag->html();
    } catch(Exception $e) {
      // broken tags will be ignored
      return $input[0];
    }

  }

  static public function install($root) {

    if(!is_dir($root)) return false;

    foreach(scandir($root) as $file) {
      if(pathinfo($file, PATHINFO_EXTENSION) == 'php') {
        $name = pathinfo($file, PATHINFO_FILENAME);
        $tag  = include($root . DS . $file);
        if(is_array($tag)) Kirbytext::$tags[$name] = $tag;
      }
    }

  }

  public function __toString() {
    try {
      return $this->parse();
    } catch(Exception $e) {
      // on massive render bugs the entire text will be returned
      return $this->field->value;
    }
  }

}


text:
<?php
/**
 * Organizer metabox
 */

// Don't load directly
if ( ! defined( 'ABSPATH' ) ) {
	die( '-1' );
}

?>
<?php
/**
 * Fires above the organizer meta box in both the event editor and the single organizer editor in the admin
 * HTML outputted here should be wrapped in a table row (
) that contains 2 cells (s)
 *
 * @param WP_Post $post if editing an event, the event currently being edited;
 *                      if editing an organizer, the organizer currently being edited
 */
do_action( 'tribe_events_organizer_before_metabox', $post );
?>
<?php if ( empty( $hide_organizer_title ) ): ?>

		<?php printf( esc_html__( '%s Name:', 'the-events-calendar' ), tribe_get_organizer_label_singular() ); ?>

			<input tabindex="<?php tribe_events_tab_index(); ?>" type='text' name='organizer[Organizer]' size='25' value='<?php echo isset( $organizer_title ) ? esc_attr( $organizer_title ) : ''; ?>' />

<?php endif; ?>

	<?php esc_html_e( 'Phone:', 'the-events-calendar' ); ?>

		<input tabindex="<?php tribe_events_tab_index(); ?>" type='text' id='OrganizerPhone' name='organizer[Phone]' size='25' value='<?php echo isset( $_OrganizerPhone ) ? esc_attr( $_OrganizerPhone ) : ''; ?>' />

	<?php esc_html_e( 'Website:', 'the-events-calendar' ); ?>

		<input tabindex="<?php tribe_events_tab_index(); ?>" type='text' id='OrganizerWebsite' name='organizer[Website]' size='25' value='<?php echo isset( $_OrganizerWebsite ) ? esc_attr( $_OrganizerWebsite ) : ''; ?>' />

	<?php esc_html_e( 'Email:', 'the-events-calendar' ); ?>

	<?php esc_html_e( 'The e-mail address will be obfuscated on your site to avoid it getting harvested by spammers.', 'the-events-calendar' ); ?>

		<input tabindex="<?php tribe_events_tab_index(); ?>" type='text' id='OrganizerEmail' name='organizer[Email]' size='25' value='<?php echo isset( $_OrganizerEmail ) ? esc_attr( $_OrganizerEmail ) : ''; ?>' />

<?php
/**
 * Fires below the organizer meta box in both the event editor and the single organizer editor in the admin
 * HTML outputted here should be wrapped in a table row (
) that contains 2 cells (s)
 *
 * @param WP_Post $post if editing an event, the event currently being edited;
 *                      if editing an organizer, the organizer currently being edited
 */
do_action( 'tribe_events_organizer_after_metabox', $post );
?>


text:
package com.spotify.apollo;

import com.google.auto.value.AutoValue;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import javax.annotation.Nullable;

/**
 * An immutable response. Each invocation of a 'withXXX' method returns a new instance,
 * making it safe to share instances between threads, at the cost of some efficiency.
 */
@AutoValue
abstract class ResponseImpl<T> implements Response<T> {

  static final Response<?> OK = createInternal(Status.OK, Optional.empty());

  @Override
  public Response<T> withHeader(String header, String value) {
    LinkedHashMap<String, String> newHeaders = new LinkedHashMap<>(headers().asMap());

    newHeaders.put(header, value);

    return createInternal(status(), Headers.of(newHeaders), payload());
  }

  @Override
  public Response<T> withHeaders(Map<String, String> headers) {
    LinkedHashMap<String, String> newHeaders = new LinkedHashMap<>(headers().asMap());

    newHeaders.putAll(headers);

    return createInternal(status(), Headers.of(newHeaders), payload());
  }

  @Override
  public <P> Response<P> withPayload(@Nullable P newPayload) {
    return createInternal(status(), headers(), Optional.ofNullable(newPayload));
  }

  static <T> Response<T> create(StatusType statusCode) {
    Objects.requireNonNull(statusCode);

    //noinspection unchecked
    return statusCode == Status.OK
        ? (Response<T>) OK
        : createInternal(statusCode, Optional.<T>empty());
  }

  static <T> Response<T> create(StatusType statusCode, T payload) {
    Objects.requireNonNull(statusCode);
    return createInternal(statusCode, Optional.of(payload));
  }

  static <T> Response<T> create(T payload) {
    return createInternal(Status.OK, Optional.of(payload));
  }

  private static <T> Response<T> createInternal(StatusType statusCode, Optional<T> payload) {
    return createInternal(
        statusCode,
        Headers.EMPTY,
        payload);
  }

  private static <T> Response<T> createInternal(
      StatusType statusCode,
      Headers headers,
      Optional<T> payload) {
    return new AutoValue_ResponseImpl<>(
        statusCode,
        headers,
        payload);
  }
}


text:
[![Build Status](https://travis-ci.org/iamn00b/reacthirafi.svg?branch=master)](https://travis-ci.org/iamn00b/reacthirafi)
[![codecov.io](https://codecov.io/github/iamn00b/reacthirafi/coverage.svg?branch=master)](https://codecov.io/github/iamn00b/reacthirafi?branch=master)
[![GitHub license](https://img.shields.io/badge/license-BSD--2-blue.svg)](https://raw.githubusercontent.com/iamn00b/alternative-react-boilerplate/master/LICENSE)

## Todo :
- [Redux](https://github.com/reactjs/redux)
- [Flow and ESLint integration](https://www.npmjs.com/package/eslint-plugin-flowtype)


text:
/**
 * \file
 *
 * \brief ATxmega128A1U on STK600 board configuration template
 *
 */
 /**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_BOARD_H
#define CONF_BOARD_H

// Enable on-board AT45DBX interface (SPI)
#define CONF_BOARD_AT45DBX

// Enable UART Communication Port interface (UART)
#define CONF_BOARD_ENABLE_USARTC0
#define CONF_BOARD_ENABLE_USARTC1
#define CONF_BOARD_ENABLE_USARTD0
#define CONF_BOARD_ENABLE_USARTD1
#define CONF_BOARD_ENABLE_USARTE0
#define CONF_BOARD_ENABLE_USARTE1
#define CONF_BOARD_ENABLE_USARTF0
#define CONF_BOARD_ENABLE_USARTF1

#endif // CONF_BOARD_H