text:
---
uid: RevisionManager.IInsight.EnableDeveloperLog(System.Object)
summary:
remarks:
syntax:
    parameters:
    - id: bCreateFlag
      description: Specifies whether the developer log is written.
example: [*content]
---
[!code-vb[Main](..\snippets\RevisionManager.IInsight.EnableDeveloperLog.vb]
[!code-csharp[Main](..\snippets\RevisionManager.IInsight.EnableDeveloperLog.cs]

redpajama_set_name: RedPajamaGithub


text:
imagist-go
==========

A clone of placehold.it in Go


text:
"use strict";

const events = require("events");
const nopus = () => require("../../../deps/nopus");
const Utils = require("../../core/Utils");
const Constants = require("../../Constants");
const AudioResampler = require("../AudioResampler");

const DiscordieProfiler = require("../../core/DiscordieProfiler");

var IPC = true;

class EncoderWorker extends events.EventEmitter {
  constructor() {
    super();
    IPC = false;
  }
  kill() {
    if (this.encoder) {
      this.encoder.destroy();
      this.encoder = null;
    }
    if (this.resampler) {
      this.resampler.destroy();
      this.resampler = null;
    }
    this.audioQueue.length = 0;
    this.audioQueue = null;
  }
}

class BaseEncodingEngine {
  constructor(sampleRate, channels, application, frameDuration) {
    this.sampleRate = sampleRate;
    this.channels = channels;
    this.application = application;
    this.frameDuration = frameDuration;
  }
  static isAvailable() {}
  setBitrate(bitrate) {}
  destroy() {}
  encode(buffer) {}
  encode_float(buffer) {}
}

class NativeEncodingEngine extends BaseEncodingEngine {
  constructor(sampleRate, channels, application, frameDuration) {
    super(sampleRate, channels, application, frameDuration);
    this.encoder = new (require("node-opus").OpusEncoder)(
      sampleRate,
      channels,
      application
    );
  }
  static isAvailable() {
    try {
      require("node-opus");
      return true;
    } catch (e) {
      return false;
    }
    return false;
  }
  destroy() {}
  setBitrate(bitrate) {
    return this.encoder.setBitrate(bitrate);
  }
  encode(view) {
    let byteBuffer = new Uint8Array(view.buffer);

    const expectedFrameSize =
      this.sampleRate * (this.frameDuration / 1000) * 2 * this.channels;

    // node-opus doesn't like buffers not matching supported frame sizes
    if (byteBuffer.length < expectedFrameSize) {
      const cut = byteBuffer;
      (byteBuffer = new Uint8Array(expectedFrameSize)).set(cut);
    } else {
      byteBuffer = byteBuffer.subarray(0, expectedFrameSize);
    }

    return [this.encoder.encode(byteBuffer)];
  }
  encode_float(view) {
    if (this.float || view instanceof Float32Array) {
      // node-opus doesn't expose encode_float
      var int16View = new Int16Array(view.length);
      for (var i = 0; i < int16View.length; i++)
        int16View[i] = view[i] * 32767;
      view = int16View;
    }

    return this.encode(view);
  }
}

var coldBoot = true;
class InternalEncodingEngine extends BaseEncodingEngine {
  constructor(sampleRate, channels, application, frameDuration) {
    super(sampleRate, channels, application, frameDuration);
    this.encoder = new (nopus().OpusEncoder)(
      sampleRate,
      channels,
      application,
      frameDuration
    );

    // make V8 compile the code
    if (coldBoot) {
      const samples = this.sampleRate / 1000 * this.frameDuration;
      for (var i = 0; i < 5; i++) {
        this.encode(Utils.allocBuffer(samples * this.channels * 2));
        this.encode_float(Utils.allocBuffer(samples * this.channels * 4));
      }
      coldBoot = false;
    }
  }
  static isAvailable() { return true; }
  setBitrate(bitrate) {
    return this.encoder.set_bitrate(bitrate);
  }
  destroy() {
    return this.encoder.destroy.apply(this.encoder, arguments);
  }
  encode(buffer) {
    return this.encoder.encode.apply(this.encoder, arguments)
      .map(packet => Utils.createBuffer(packet));
  }
  encode_float(buffer) {
    return this.encoder.encode_float.apply(this.encoder, arguments)
      .map(packet => Utils.createBuffer(packet));
  }
}

class BaseResampler {
  constructor(channels, sourceRate, targetRate, bps, float) {
    this.channels = channels;
    this.sourceRate = sourceRate;
    this.targetRate = targetRate;
    this.bps = bps;
    this.float = float;
  }
  destroy() {}
  process_interleaved() {}
}

class SpeexResampler extends BaseResampler {
  constructor(channels, sourceRate, targetRate, bps, float) {
    super(channels, sourceRate, targetRate, bps, float);
    this.resampler = new (nopus().Resampler)(
      channels,
      sourceRate, targetRate,
      bps, float
    );
  }
  destroy() {
    return this.resampler.destroy.apply(this.resampler, arguments);
  }
  process_interleaved() {
    return this.resampler.process_interleaved.apply(this.resampler, arguments);
  }
}

class InternalResampler extends BaseResampler {
  constructor(channels, sourceRate, targetRate, bps, float) {
    super(channels, sourceRate, targetRate, bps, float);
    this.resampler = new AudioResampler(channels, sourceRate, targetRate);
  }
  process_interleaved(buffer) {
    let view = null;
    if (!this.float) {
      if (this.bps == 8) {
        view = new Int8Array(buffer);
      } else if (this.bps == 16) {
        view = new Int16Array(buffer);
      } else if (this.bps == 32) {
        view = new Int32Array(buffer);
      }
      // 24 bps audio nope
    } else {
      view = new Float32Array(buffer);
    }

    if (!view) throw new Error("Unsupported audio format");

    if (!this.float) {
      var floatView = new Float32Array(view.length);
      for (var i = 0; i < floatView.length; i++)
        floatView[i] = view[i] / 32767;
      view = floatView;
    }

    return this.resampler.process(view);
  }
}

const hrtime = function() {
  const t = process.hrtime();
  return t[0] * 1000 + t[1] / 1000000;
}

function initialize(_options) {
  if (this.encoder != null) {
    this.encoder.destroy();
  }
  if (this.resampler != null) {
    this.resampler.destroy();
    this.resampler = null;
  }

  const targetSampleRate = Constants.DISCORD_SAMPLE_RATE;

  _options.frameDuration = _options.frameDuration || 60;
  _options.frameDuration = Math.max(20, Math.min(_options.frameDuration, 60));
  _options.sampleRate = _options.sampleRate || targetSampleRate;
  _options.channels = _options.channels || 1;
  _options.float = _options.float || false;

  // "average", anything else will encode multichannel audio
  _options.downmix = _options.downmix;

  // "highres", anything else will just use setTimeout
  _options.timingPrecision = _options.timingPrecision || "normal";

  // "nopus", anything else will just use internal
  _options.resampler = _options.resampler || "internal";

  // "native", anything else will just use internal
  _options.engine = _options.engine || "internal";

  // proxy mode, passes packets straight to the muxer
  // packets should be opus encoded already
  // in this mode it only works as scheduler for packets
  _options.proxy = _options.proxy || false;

  // OPUS_AUTO          -1000
  // OPUS_BITRATE_MAX   -1
  _options.bitrate = _options.bitrate || null;

  this.options = _options;

  this.encodingChannels = this.options.downmix ?
    1 :
    this.options.channels;

  if (!this.options.proxy) {
    if (this.options.engine == "native") {
      const available = NativeEncodingEngine.isAvailable();
      if (!available) {
        console.warn("Unable to load native opus module (node-opus)");
        console.warn("Audio will be encoded using internal module");
        this.options.engine = "internal";
      }
    }

    const _encodingEngine =
      this.options.engine == "native" ?
        NativeEncodingEngine :
        InternalEncodingEngine;

    this.encoder = new _encodingEngine(
      targetSampleRate,
      this.encodingChannels,
      (nopus().OpusApplication).Audio,
      this.options.frameDuration
    );

    if (this.options.bitrate) {
      this.encoder.setBitrate(this.options.bitrate);
    }

    if (targetSampleRate != this.options.sampleRate) {
      const _resampler =
        this.options.resampler == "nopus" ?
          SpeexResampler :
          InternalResampler;

      this.resampler = new _resampler(this.encodingChannels,
        this.options.sampleRate, targetSampleRate,
        this.options.float ? 32 : 16, this.options.float
      );
    }
  }

  this.failedPackets = 0;
  this.startTime = hrtime();
  this.lastFrame = 0;

  this.audioQueue = [];
}

function processQueue() {
  if (this.audioQueue.length <= 0) return;

  const frameDuration = this.options.frameDuration;
  const lastTime = this.lastFrame * frameDuration + this.startTime;
  if (hrtime() - lastTime > 1000) {
    // put queue into pause mode after 1 second
    // reset scheduler when more data available
    this.startTime = hrtime();
    this.lastFrame = 0;
  }

  setImmediate(this.timerCallback.bind(this));
}

function timerCallback() {
  if (this.encoder == null && !this.options.proxy)
    return;
    //throw new Error("Encoder is not initialized");

  if (!this.audioQueue) return;

  if (this.audioQueue && this.audioQueue.length <= 0) {
    this.sendNeedBuffer();
    return;
  }

  const frameDuration = this.options.frameDuration;
  const nextTime = (this.lastFrame + 1) * frameDuration + this.startTime;

  // normal precision timing, low cpu usage
  if (this.options.timingPrecision != "highres") {
    if (hrtime() < nextTime) {
      const timeleft = Math.round(nextTime - hrtime());

      if (this.nextFrameTimer)
        clearTimeout(this.nextFrameTimer);
      this.nextFrameTimer =
        setTimeout(this.timerCallback.bind(this), Math.max(timeleft, 0));

      return;
    }

    this.lastFrame++;
    this.processAudio();
    return setImmediate(this.timerCallback.bind(this));
  }

  // high precision timing, high cpu usage

  const hiresTimerThreshold = this.options.frameDuration / 4;
  if (hrtime() < nextTime) {
    const timeleft = nextTime - hrtime();

    if (timeleft <= hiresTimerThreshold) {
      return setImmediate(this.timerCallback.bind(this));
    }

    if (this.nextFrameTimer)
      clearTimeout(this.nextFrameTimer);
    this.nextFrameTimer =
      setTimeout(this.timerCallback.bind(this), timeleft / 4);

    return;
  }

  this.lastFrame++;
  this.processAudio();
  return setImmediate(this.timerCallback.bind(this));
}

function processAudio() {
  const frame = this.audioQueue.shift();

  let frameData = frame.chunk.data;
  if (frame.chunk instanceof Buffer)
    frameData = frame.chunk;

  if (!frame.chunk || !frameData || !frame.sampleCount) return;

  if (this.options.proxy) {
    this.sendPacket(frame.chunk, frame.sampleCount);
    return;
  }

  if (frameData.length % 2 != 0 ||
    (this.options.float && frameData.length % 4 != 0))
    return console.log("check your audio payload, buffer size must be even");

  const frameBuffer = Utils.createArrayBuffer(frameData);
  const frameView = this.options.float ?
    new Float32Array(frameBuffer) : new Int16Array(frameBuffer);

  const bufferLength = this.options.downmix == "average" ?
    frameData.length / this.options.channels :
    frameData.length;

  let channel = new ArrayBuffer(bufferLength);
  let view = this.options.float ?
    new Float32Array(channel) : new Int16Array(channel);

  DiscordieProfiler.start("mix");
  // much optimize, var
  var channels = this.options.channels;
  var volume = this.options.volume / 100;
  var viewLength = view.length;

  if (this.options.downmix == "average") {
    var sum = 0;
    for (var i = 0; i < viewLength; i++) {
      sum = 0;
      for (var c = 0; c < channels; c++) {
        sum += frameView[i * channels + c];
      }
      view[i] = sum / channels;

      if (volume < 1) view[i] *= volume;
    }
  } else {
    if (volume < 1) {
      for (var i = 0; i < viewLength; i++) {
        view[i] = frameView[i] * volume;
      }
    } else {
      channel = frameBuffer;
      view = frameView;
    }
  }
  DiscordieProfiler.stop("mix");

  DiscordieProfiler.start("resample");
  if (this.resampler != null) {
    view = this.resampler.process_interleaved(channel);
  }
  DiscordieProfiler.stop("resample");

  DiscordieProfiler.start("encode");
  let encoded;
  const encode = (this.options.float || this.resampler ?
    this.encoder.encode_float : this.encoder.encode).bind(this.encoder);

  encoded = encode(view);
  DiscordieProfiler.stop("encode");

  if (!encoded.length) {
    this.failedPackets++;
    if (this.failedPackets > 3) {
      console.log(
        "failed to encode packet, buffer size might be smaller than expected"
      );
    }
  } else {
    this.failedPackets = 0;
  }

  if (process.env.PROFILEVOICE) {
    let out = "";
    let sum = 0;

    const timediff = (hrtime() - this.startTime);
    const _print = (name, v) => {
      var cpu = v / timediff * 100;
      out += `[${name}] ${v.toFixed(2)}ms ${cpu.toFixed(2)}%cpu; `;
    };

    ["mix", "resample", "encode"].map(n => {
      const v = DiscordieProfiler.get(n);
      if (!this.prof) this.prof = {};
      if (!this.prof[n]) this.prof[n] = 0;
      this.prof[n] += v;
      const vacc = this.prof[n];

      n = n.substr(0, 3).toUpperCase();
      _print(n, vacc);
      sum += vacc;
    });
    _print("TOTAL", sum);
    out += "T: " + timediff.toFixed(2);
    console.log(out);
  }

  for (let i = 0; i < encoded.length; i++) {
    this.sendPacket(
      encoded[i],
      this.resampler ?
        (view.length / this.encodingChannels) :
        frame.sampleCount
    );
  }
}

function onIPCMessage(msg) {
  if (!msg) return;
  switch (msg.op) {
  case "initialize":
    this.initialize(msg.options);
    break;
  case "enqueue":
    if (this.audioQueue) {
      this.audioQueue.push(msg.frame);
      this.processQueue();
    }
    break;
  case "enqueueMultiple":
    if (this.audioQueue) {
      this.audioQueue.push.apply(this.audioQueue, msg.frames);
      this.processQueue();
    }
    break;
  case "clearQueue":
    if (this.audioQueue) {
      this.audioQueue.length = 0;
    }
    break;
  case "set":
    this.options[msg.key] = msg.value;
    break;
  case "setBitrate":
    if (this.encoder) {
      this.options.bitrate = msg.value;
      this.encoder.setBitrate(msg.value);
    }
    break;
  }
}

function sendIPC(data) {
  if (!IPC) {
    this.emit("message", data);
    return;
  }
  process.send(data);
}
function sendPacket(packet, sampleCount) {
  this.sendIPC({
    op: "opuspacket",
    packet: packet,
    sampleCount: sampleCount
  });
}
function sendNeedBuffer() {
  this.sendIPC({op: "needbuffer"});
}

process.on("message", onIPCMessage.bind(EncoderWorker.prototype));
Object.assign(EncoderWorker.prototype, {
  send: onIPCMessage,

  initialize: initialize,
  processQueue: processQueue,
  processAudio: processAudio,
  timerCallback: timerCallback,

  sendIPC: sendIPC,
  sendPacket: sendPacket,
  sendNeedBuffer: sendNeedBuffer,
});

module.exports = EncoderWorker;


text:
using UnityEngine;
using System.Collections;

public class BallTosser : MonoBehaviour {
    private const float FORCE_MULTIPLIER = 25f;
    private const float MIN_X_SPEED = 0.5f;

    public void Initialize() {
        rigidbody.AddForce(TossForce);
    }

    private Vector3 TossForce {
        get {
            var vector = (Vector3) Random.insideUnitCircle;
            if (vector.x > 0) {
                vector.x += MIN_X_SPEED;
            } else {
                vector.x -= MIN_X_SPEED;
            }
            return vector.normalized * FORCE_MULTIPLIER;
        }
    }
}


text:
using Bars2Db.SqlQuery.QueryElements.Conditions.Interfaces;
using Bars2Db.SqlQuery.QueryElements.Enums;
using Bars2Db.SqlQuery.QueryElements.SqlElements.Interfaces;
using Bars2Db.SqlQuery.Search;

namespace Bars2Db.SqlQuery.QueryElements.Interfaces
{
    public interface IJoinedTable : ISqlExpressionWalkable, ICloneableElement, IQueryElement
    {
        EJoinType JoinType { get; set; }

        [SearchContainer]
        ITableSource Table { get; set; }

        [SearchContainer]
        ISearchCondition Condition { get; }

        bool IsWeak { get; set; }

        bool CanConvertApply { get; set; }
    }
}


text:
<?php

/**
 * Options class for ezcWorkflowDatabase.
 *
 * @property string $prefix
 *                  The database table name prefix to be used.
 *
 * @package WorkflowDatabaseTiein
 * @version 1.4
 */
class ezcWorkflowDatabaseOptions extends ezcBaseOptions
{
    /**
     * Properties.
     *
     * @var array(string=>mixed)
     */
    protected $properties = array(
        'prefix' => '',
    );

    /**
     * Property write access.
     *
     * @param string $propertyName  Name of the property.
     * @param mixed  $propertyValue The value for the property.
     *
     * @throws ezcBasePropertyNotFoundException
     *         If the the desired property is not found.
     * @ignore
     */
    public function __set( $propertyName, $propertyValue )
    {
        switch ( $propertyName )
        {
            case 'prefix':
                if ( !is_string( $propertyValue ) )
                {
                    throw new ezcBaseValueException(
                        $propertyName,
                        $propertyValue,
                        'string'
                    );
                }
                break;
            default:
                throw new ezcBasePropertyNotFoundException( $propertyName );
        }
        $this->properties[$propertyName] = $propertyValue;
    }
}
?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rosellinia millegrana var. minuta Feltgen

### Remarks
null


text:
package org.ovirt.engine.core.bll.scheduling.queries;

import javax.inject.Inject;

import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.dao.VdsGroupDao;

public class GetAttachedClustersByClusterPolicyIdQuery extends QueriesCommandBase<IdQueryParameters> {
    public GetAttachedClustersByClusterPolicyIdQuery(IdQueryParameters parameters) {
        super(parameters);
    }

    @Inject
    private VdsGroupDao vdsGroupDao;

    @Override
    protected void executeQueryCommand() {
        getQueryReturnValue().setReturnValue(
                vdsGroupDao.getClustersByClusterPolicyId(getParameters().getId()));
    }
}


text:
//-----------------------------------------------------------------------
// <copyright company="TheNucleus">
// Copyright (c) TheNucleus. All rights reserved.
// Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------

using System;

namespace Nuclei.Plugins.Discovery
{
    /// <summary>
    /// Defines the interface for objects that listen for changes in plugin files.
    /// </summary>
    public interface IPluginListener
    {
        /// <summary>
        /// Disables the uploading of packages.
        /// </summary>
        void Disable();

        /// <summary>
        /// Enables the uploading of packages.
        /// </summary>
        void Enable();
    }
}


text:
/**
 *
 */
package de.fco.web.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import de.fco.domain.Currency;
import de.fco.service.ViolationService;

/**
 * @author Ralf Hellriegel
 */
@RestController
@RequestMapping(value = "/admin/violation/currency")
public class CurrencyManagementController {

    private final ViolationService violationService;

    /**
     * @param violationService
     */
    @Autowired
    public CurrencyManagementController(final ViolationService violationService) {
        this.violationService = violationService;
    }

    /**
     * @return all existing {@link Currency}s
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Currency> findAll() {
        return violationService.findAllCurrencies();
    }

    /**
     * Create a new {@link Currency} via {@link ViolationService#createCurrency(Currency)}. The data should be provided
     * in the request payload.
     *
     * @param currency the new object to create in the database
     * @return the currency which was actually created
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.CREATED)
    public Currency createViolationCategory(@RequestBody final Currency currency) {
        return violationService.createCurrency(currency);
    }

}


text:
package org.elasticsearch.plugin.analysis.hanlp;

import org.elasticsearch.common.inject.Module;
import org.elasticsearch.index.analysis.AnalysisModule;
import org.elasticsearch.index.analysis.HanLpAnalysisBinderProcessor;
import org.elasticsearch.indices.analysis.hanlp.HanLpIndicesAnalysisModule;
import org.elasticsearch.plugins.Plugin;

import java.util.Collection;
import java.util.Collections;

/**
 * @author Alexey Zhokhov
 */
public class AnalysisHanLpPlugin extends Plugin {

    @Override
    public String name() {
        return "analysis-hanlp";
    }

    @Override
    public String description() {
        return "HanLP Chinese analysis support";
    }

    @Override
    public Collection<Module> nodeModules() {
        return Collections.<Module>singletonList(new HanLpIndicesAnalysisModule());
    }

    /**
     * Automatically called with the analysis module.
     */
    public void onModule(AnalysisModule module) {
        module.addProcessor(new HanLpAnalysisBinderProcessor());
    }

}


text:
INSERT INTO oskari_layergroup (id, locale) values (999, '{ fi:{name:"ELF"},sv:{name:"ELF"},en:{name:"ELF"}}');

-- THIS IS AN EXAMPLE FOR ADDING WMTS LAYER ;
INSERT INTO oskari_maplayer(type, name, groupId,
                            metadataId, url,
                            locale,
                            tile_matrix_set_id)
  VALUES('wmtslayer', 'elf_basemap', 999,
         '', 'http://opencache.statkart.no/gatekeeper/gk/gk.open_wmts',
         '{ fi:{name:"ELF taustakartta",subtitle:"(WMTS)"},sv:{name:"ELF Backgrundskarta",subtitle:"(WMTS)"},en:{name:"ELF Background map",subtitle:"(WMTS)"}}',
         'EPSG:3857');

-- link to inspire theme;
INSERT INTO oskari_maplayer_themes(maplayerid,
                                   themeid)
  VALUES((select max(id) from oskari_maplayer),
         (SELECT id FROM portti_inspiretheme WHERE locale LIKE '%Background maps%'));

-- setup permissions for guest user;
INSERT INTO oskari_resource(resource_type, resource_mapping) values ('maplayer', 'wmtslayer+http://opencache.statkart.no/gatekeeper/gk/gk.open_wmts+elf_basemap');

-- permissions;
-- adding permissions to roles with id 10110, 2, and 3;

-- give view_layer permission for the resource to ROLE 10110 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_LAYER', '10110');

-- give view_layer permission for the resource to ROLE 1 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_LAYER', '1');

-- give view_layer permission for the resource to ROLE 2 (user);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_LAYER', '2');

-- give publish permission for the resource to ROLE 2 (user);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'PUBLISH', '2');

-- give publish permission for the resource to ROLE 3 (admin);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'PUBLISH', '3');

-- give view_published_layer permission for the resource to ROLE 10110 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_PUBLISHED', '10110');

-- give view_published_layer permission for the resource to ROLE 10110 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_PUBLISHED', '1');

-- give view_published_layer permission for the resource to ROLE 2 (user);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_PUBLISHED', '2');


text:
var path = require('path');

var webpack = require('webpack');

var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var BellOnBundlerErrorPlugin = require('bell-on-bundler-error-plugin');
var FixDefaultImportPlugin = require('webpack-fix-default-import-plugin');

var isDevServer = process.env.NODE_ENV === 'development-server';
var isProd = process.env.NODE_ENV === 'production';
var isDev = !isProd;

var cssLoader = isDevServer
  ? ['style-loader?sourceMap', 'css-loader?sourceMap', 'postcss-loader?sourceMap'].join('!')
  : ExtractTextPlugin.extract(['css-loader?sourceMap', 'postcss-loader?sourceMap']);

var lessLoader = isDevServer
  ? ['style-loader?sourceMap', 'css-loader?sourceMap', 'postcss-loader?sourceMap', 'less-loader?sourceMap'].join('!')
  : ExtractTextPlugin.extract(['css-loader?sourceMap', 'postcss-loader?sourceMap', 'less-loader?sourceMap']);

var sassLoader = isDevServer
  ? ['style-loader?sourceMap', 'css-loader?sourceMap', 'postcss-loader?sourceMap', 'sass-loader?sourceMap'].join('!')
  : ExtractTextPlugin.extract(['css-loader?sourceMap', 'postcss-loader?sourceMap', 'sass-loader?sourceMap']);

var stylusLoader = isDevServer
  ? ['style-loader?sourceMap', 'css-loader?sourceMap', 'postcss-loader?sourceMap', 'stylus-loader?sourceMap'].join('!')
  : ExtractTextPlugin.extract(['css-loader?sourceMap', 'postcss-loader?sourceMap', 'stylus-loader?sourceMap']);

var tsLoader = isDevServer ? ['react-hot-loader/webpack', 'ts-loader'] : ['ts-loader'];

// autoprefixer configuration based on Bootstrap 3.x defaults
var autoprefixerBrowsers = require('bootstrap/grunt/configBridge.json').config.autoprefixerBrowsers;

// autoprefixer configuration based on Bootstrap 4.x defaults
// var autoprefixerBrowsers = require('bootstrap/grunt/postcss').autoprefixer.browsers;

// autoprefixer configuration based on Semantic UI 2.x defaults
// var autoprefixerBrowsers = ['last 2 versions', '> 1%', 'opera 12.1', 'bb 10', 'android 4'];

// autoprefixer configuration for Foundation is unknown
// var autoprefixerBrowsers = ['last 2 versions', '> 1%'];

var config = {
  entry: {
    app: './src/index'
  },
  output: {
    path: path.resolve('dist'),
    filename: '[name].js?[hash]',
    devtoolModuleFilenameTemplate: function (info) {
      var relPath = info.resourcePath
        .replace(/^.*(~|node_modules)/, '~')
        .replace(/^(webpack:\/\/\/)+/, '')
        .replace(/^\.\//, '')
        .replace(/^\(webpack\)-/, '(webpack)/')
        .replace(/^webpack\/bootstrap/, '(webpack)/bootstrap');
      return 'webpack:///' + relPath + '?' + info.hash;
    }
  },
  devtool: isDevServer ? 'eval' : 'source-map',
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.js', '.ts', '.tsx'],
  },
  module: {
    preLoaders: [
      {
        test: /\.tsx?$/,
        loader: 'tslint-loader',
        include: path.resolve('src')
      },
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        include: path.resolve('node_modules')
      }
    ],
    loaders: [
      {
        test: /\.tsx?$/,
        loaders: tsLoader,
        include: path.resolve('src')
      },
      {
        test: /\.js$/,
        loader: 'imports?this=>window',
        include: path.resolve('node_modules/foundation/js/foundation')
      },
      {
        test: /\.css$/,
        loader: cssLoader
      },
      {
        test: /\.less$/,
        loader: lessLoader
      },
      {
        test: /\.(scss|sass)$/,
        loader: sassLoader
      },
      {
        test: /\.styl$/,
        loader: stylusLoader
      },
      {
        test: /\.(png|jpg|woff|woff2|eot|ttf|svg)(\?.*)?$/,
        loader: 'file-loader?name=[path]/[name].[ext]?[hash]'
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(isProd ? 'production' : 'development')
      }
    }),
    new webpack.ProvidePlugin({
      'jQuery': 'jquery',         // for Bootstrap 3.x / 4.x
      'window.jQuery': 'jquery',  // for Bootstrap 3.x / 4.x
      'Tether': 'tether',         // for Bootstrap 4.x
      'window.Tether': 'tether'   // for Bootstrap 4.x
    }),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'src/index.html'
    }),
    new FixDefaultImportPlugin(),
    new BellOnBundlerErrorPlugin()
  ],
  tslint: {
    emitErrors: true,
    failOnHint: true
  },
  postcss: function () {
    return [
      require('postcss-flexbugs-fixes'),
      require('autoprefixer')({ browsers: autoprefixerBrowsers })
    ];
  }
};

if (!isDevServer) {
  var vendorChunkPlugin =
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: function (module) {
        var relPath = path.relative(__dirname, module.userRequest).replace(/\\/g, '/');
        return /^(node_modules|src\/(bootstrap4?|semantic|foundation))\//.test(relPath);
      }
    });

  var cssLibChunkPlugin =
    new webpack.optimize.CommonsChunkPlugin({
      name: 'bootstrap',  // bootstrap | semantic | foundation
      chunks: ['vendor'],
      minChunks: function(module) {
        var relPath = path.relative(__dirname, module.userRequest).replace(/\\/g, '/');
        return /^((src|node_modules)\/(bootstrap4?|semantic|foundation))\//.test(relPath);
      }
    });

  var extractTextPlugin = new ExtractTextPlugin('[name].css?[hash]');

  if (isProd) {
    config.plugins.push(
      new webpack.optimize.UglifyJsPlugin({
        compress: { warnings: false },
        output: { comments: false }
      }),
      new webpack.optimize.OccurrenceOrderPlugin(),
      new webpack.optimize.DedupePlugin(),
      vendorChunkPlugin,
      extractTextPlugin
    );
  } else {
    config.plugins.push(
      vendorChunkPlugin,
      cssLibChunkPlugin,
      extractTextPlugin
    );
  }
} else {
  config.entry = [
    'react-hot-loader/patch',
    'webpack-hot-middleware/client',
    './src/index-hot'
  ];

  config.devServer = {
    stats: {
      chunkModules: false,
      assets: false,
      colors: true
    }
  };

  config.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  );
}

module.exports = config;


text:
package api

import (
	"context"
	"net/http"
	"strings"
	"time"

	"github.com/go-chi/chi"
	"github.com/imba3r/grabber/core/scheduler"
)

// AddSchedulerRoutes adds routes for scheduler related tasks.
func (r *Router) AddSchedulerRoutes(service *scheduler.Service) {
	rs := schedulerResource{service}
	r.addRouter("/scheduler", rs.router())
}

type schedulerResource struct {
	service *scheduler.Service
}

func (rs *schedulerResource) router() *chi.Mux {
	r := chi.NewRouter()
	r.Get("/", rs.jobs)
	r.Route("/{job}", func(r chi.Router) {
		r.Use(rs.jobCtx)
		r.Post("/run", rs.run)
		r.Post("/pause", rs.pause)
		r.Post("/resume", rs.resume)
	})
	return r
}

type job struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	Interval   string `json:"interval"`
	NextRun    string `json:"nextRun"`
	LastRun    string `json:"lastRun"`
	State      string `json:"state"`
	InProgress bool   `json:"inProgress"`
}

// TODO persist job interval time
func (rs *schedulerResource) jobs(w http.ResponseWriter, r *http.Request) {
	var jobs []job
	for _, j := range rs.service.Jobs() {
		jobs = append(jobs, job{
			ID:         j.ID(),
			Name:       j.Name(),
			Interval:   j.CurrentInterval().String(),
			NextRun:    j.NextRun().Format(time.RFC3339),
			LastRun:    j.LastRun().Format(time.RFC3339),
			State:      j.State().String(),
			InProgress: j.InProgress(),
		})
	}
	writeJSON(w, jobs)
}

func (rs *schedulerResource) jobCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		jobName := chi.URLParam(r, "job")
		var job *scheduler.Job
		for _, j := range rs.service.Jobs() {
			if strings.ToLower(j.Name()) == strings.ToLower(jobName) {
				job = j
				break
			}
		}
		if job == nil {
			http.Error(w, "Unknown job: "+jobName, http.StatusBadRequest)
			return
		}
		ctx := context.WithValue(r.Context(), keyJob, job)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

func (rs *schedulerResource) run(w http.ResponseWriter, r *http.Request) {
	job := r.Context().Value(keyJob).(*scheduler.Job)
	job.RunNow()
	w.WriteHeader(http.StatusNoContent)
}

func (rs *schedulerResource) pause(w http.ResponseWriter, r *http.Request) {
	job := r.Context().Value(keyJob).(*scheduler.Job)
	job.Pause()
	w.WriteHeader(http.StatusNoContent)
}

func (rs *schedulerResource) resume(w http.ResponseWriter, r *http.Request) {
	job := r.Context().Value(keyJob).(*scheduler.Job)
	job.Resume()
	w.WriteHeader(http.StatusNoContent)
}


text:
title: Apache Mesos - Release Guide
layout: documentation
---

# Release Guide

This guide describes the process of doing an official release of Mesos.

## Prerequisites

1. Ensure that you have a GPG key or generate a new one, e.g., using `gpg --gen-key`.

2. Add your GPG public key to the Apache Mesos dist repository in the KEYS file.

   * Fetch the svn repository:

          $ svn co https://dist.apache.org/repos/dist/release/mesos

   * Append your public key using one of methods described in KEYS, e.g.:

          $ (gpg --list-sigs <your name> && gpg --armor --export <your name>) >> KEYS

   * Push the commit:

          $ svn ci

3. Submit your GPG public key to a keyserver, e.g.,
   [MIT PGP Public Key Server](https://pgp.mit.edu).

4. Add your GPG fingerprint (`gpg --fingerprint <your name>`) to your
   [Apache account](https://id.apache.org/).

5. Create a Maven settings file (`~/.m2/settings.xml`) for the Apache
   servers where you must copy your encrypted Apache password which
   you can get from running `mvn --encrypt-password`.

   **NOTE:** You may need to first generate a
   [master password](http://maven.apache.org/guides/mini/guide-encryption.html).

        <settings>
          <servers>
            <server>
              <id>apache.snapshots.https</id>
              <username>APACHE USERNAME</username>
              <password>APACHE ENCRYPTED PASSWORD</password>
            </server>
            <server>
              <id>apache.releases.https</id>
              <username>APACHE USERNAME</username>
              <password>APACHE ENCRYPTED PASSWORD</password>
            </server>
          </servers>
        </settings>

6. Use `gpg-agent` to avoid typing your passphrase repeatedly:

        $ export GPG_TTY="$(tty)" && eval $(gpg-agent --daemon)

## Preparation

1. Go to [Apache JIRA](https://issues.apache.org/jira/browse/MESOS) and make
   sure that the `CHANGELOG` for the release version is up to date.

   **NOTE:** You should move all **Unresolved** tickets marked with `Fix Version`
   or `Target Version` as the release version to the next release version.

   **PROTIP:** Use a JIRA dashboard
   [(example)](https://issues.apache.org/jira/secure/Dashboard.jspa?selectPageId=12329720)
   to track the progress of targeted issues as the release date approaches. This
   JIRA filter may be useful (`<X.Y.Z>` is the release version):
   `project = MESOS AND "Target Version/s" = <X.Y.Z> AND (fixVersion != <X.Y.Z> OR fixVersion = EMPTY)`

   **PROTIP:** Use `bulk edit` option in JIRA to move the tickets and make sure
   to **uncheck** the option that emails everyone about the move to avoid
   spamming.

2. Checkout the correct branch for the release. For regular releases this is the
   "master" branch. For patch releases this would be the corresponding release
   branch (e.g., 1.0.x).

3. Update and commit the `CHANGELOG` for the release.

   For regular releases:

   * Make sure all new API changes, deprecations, major features, and features
     graduating from experimental to stable are called out at the top of the
     `CHANGELOG`. This JIRA query may be helpful in identifying some of these
     (`<X.Y.Z>` is the release version):
     `project = MESOS AND "Target Version/s" = <X.Y.Z> AND type = Epic`

   * Ensure that the "Unresolved Critical Issues" section is populated
     correctly. This JIRA query may be helpful:
     `project = Mesos AND type = bug AND status != Resolved AND priority IN (blocker, critical)`

   * Prepare a full list of experimental features. The easiest way to do this
     is to take the list from the previous minor release, remove features that
     have been declared stable, and those, that declared experimental in the
     current release. Do not forget to mention features transitioning from
     experimental to stable in this release at the top of the `CHANGELOG`.

   **NOTE:** You should use JIRA to generate the major portion of the
   `CHANGELOG` for you. Click on the release version in
   [JIRA](https://issues.apache.org/jira/browse/MESOS#selectedTab=com.atlassian.jira.plugin.system.project%3Aversions-panel)
   and click on the `Release Notes`. Make sure to configure the release notes
   in text format.

   **NOTE:** The JIRA Release Notes will list only tickets with `Fix Version`
   set to that version. You should check for any Resolved tickets that have
   `Target Version` set but not `Fix Version`. Also check for any Unresolved
   or `Duplicate`/`Invalid` tickets that incorrectly set the `Fix Version`.

   For patch releases update the `CHANGELOG` on master branch and then cherry
   pick onto the release branch.

4. Ensure version in `configure.ac` and `CMakeLists.txt` is correctly set for
   the release. Do not forget to remove "(WIP)" suffix from the release notes'
   title.

5. Run `make && support/generate-endpoint-help.py` and commit any resulting
   changes.

6. Update and commit `docs/configuration.md` to reflect the current state of
   the master, agent, and configure flags. If this is a patch release, update
   it on master branch and then cherry pick onto the release branch.

7. If this is a regular release, update and commit `docs/upgrades.md` with
   instructions about how to upgrade a live cluster from the previous release
   version to this release version.

8. If this is a regular release, please ensure that user documentation has been
   added for any new features.

9. Make sure that for any updates of the API, specifically the scheduler API,
   the public mesos protobuf definitions are part of both, `include/mesos` as
   well as `include/mesos/v1`.

   **NOTE:** This might actually demand code updates if any omissions were
   identified.

## Tagging the Release Candidate

1. Ensure that you can build and pass all the tests.

        $ sudo make -j<cores> distcheck

2. Run the benchmarks and compare with the previous release for any performance
   regressions:

        $ make bench -j<cores> GTEST_FILTER="*BENCHMARK*"

3. First tag the required SHA locally.

        $ git tag <X.Y.Z-rcR>

   **NOTE:** `X.Y.Z` is based on [semantic versioning](http://semver.org/)
   scheme. `R` is release candidate version that starts with 1.

4. Tag the release externally and deploy the corresponding JAR to the
   [Apache maven repository](https://repository.apache.org). It is recommended
   to use the `support/tag.sh` script to accomplish this.

        $ ./support/tag.sh X.Y.Z R

   **NOTE:** This script assumes that you have the requisite permissions to
   deploy the JAR. For instructions on how to set it up, please refer to
   `src/java/MESOS-MAVEN-README`.

   **NOTE:** gnu-sed (Linux) requires `-i''` instead of the `-i ''`
   (space-separated) that default OSX uses. You may need to modify your local
   copy of `tag.sh` for it to complete successfully.

5. If this is a regular release, create a new release branch (<major>.<minor>.x)
   from this tag.

        $ git checkout -b X.Y.x

   Now, update master branch to the *next*  minor version in `configure.ac`:
   change `AC_INIT([mesos], [X.Y.Z]))`, as well as in `CMakeLists.txt`:
   change `set(MESOS_MAJOR_VERSION X)`, `set(MESOS_MINOR_VERSION Y)`,
   `set(MESOS_PATCH_VERSION Z)` and then commit.

## Voting the Release Candidate

1. Once a release candidate is deemed worthy to be officially released you
   should call a vote on the `dev@mesos.apache.org` (and optionally
   `user@mesos.apache.org`) mailing list.

2. It is recommended to use the `support/vote.sh` script to vote the release
   candidate.

        $ ./support/vote.sh X.Y.Z R

3. The release script also spits out an email template that you could use to
   send the vote email.

   **NOTE:** The `date -v+3d` command does not work on some platforms (e.g.
   Ubuntu), so you may need to fill in the vote end date manually. The vote
   should last for 3 business days instead of 3 calendar days anyway. Sometimes
   we allow a longer vote, to allow more time for integration testing.

## Preparing a New Release Candidate

1. If the vote does not pass (any -1s or showstopper bugs), track the issues
   as new JIRAs for the release.

2. When all known issues are resolved, update the `CHANGELOG` with the newly
   fixed JIRAs.

3. Once all patches are committed to master, cherry-pick them on to the
   corresponding release branch. This is the same process used for patch
   releases (e.g., 1.0.2) as well.

        $ git checkout X.Y.x
        $ git cherry-pick abcdefgh...

4. Now go back up to the "Tagging the Release Candidate" section and repeat.

## Releasing the Release Candidate

1. You should only release an official version if the vote passes with at
   least **3 +1 binding votes and no -1 votes**. For more information, please
   refer to [Apache release guidelines](http://www.apache.org/dev/release.html).

2. It is recommended to use `support/release.sh` script to release the candidate.

        $ ./support/release.sh X.Y.Z R

3. The release script also spits out an email template that you could use to
   notify the mailing lists about the result of the vote and the release.

   **NOTE:** Make sure you fill the email template with the names of binding
   and non-binding voters.

4. Update the version in `configure.ac` and `CMakeLists.txt` in the **release**
   branch to the **next** patch version.

## Updating the Website

1. After a successful release, add the information associated with the release
   in `site/data/releases.yml`. It is used to generate the release information
   on the website.

2. Update the [Getting Started](getting-started.md) guide to use the latest
   release link.

3. Check out the website from svn.

        $ svn co https://svn.apache.org/repos/asf/mesos/site mesos-site

   See our [website README](https://github.com/apache/mesos/blob/master/site/README.md/)
   for details on how to build the website. See the general
   [Apache project website guide](https://www.apache.org/dev/project-site.html)
   for details on how to publish the website.

4. Write a blog post announcing the new release and its features and major bug
   fixes. Include a link to the updated website.

   * This command may be helpful to gather the list of all contributors between
     two tags:
     `git log --pretty=format:%an <tagX>..<tagY> | sort | uniq | awk '{print}' ORS=', '`

   * Mention the blog post in `site/data/releases.yml`.

## Removing Old Releases from svn

Per the guidelines [when to archive](http://www.apache.org/dev/release.html#when-to-archive),
we should only keep the latest release in each version under development.

1. Checkout the mesos distribution folder:

        $ svn co https://dist.apache.org/repos/dist/release/mesos

2. Remove all minor versions that are no longer under development and commit
   the change.

## Releasing the Version on JIRA

Find the released Mesos version
[here](https://issues.apache.org/jira/plugins/servlet/project-config/MESOS/versions),
and "release" it with the correct release date by clicking on
"settings" → "Release". Also, make sure to add the names of the
release managers in "Description" section.

## Updating External Tooling

Upload the mesos.interface package to PyPi.

1. Create/use a PyPi account with access to the
   [mesos.interface submit form](https://pypi.python.org/pypi?name=mesos.interface&:action=submit_form).
   You may need to ask a current package owner to add you as an owner/maintainer.

2. Setup your [`~/.pypirc`](https://docs.python.org/2/distutils/packageindex.html#pypirc)
   with your PyPi username and password.

3. After a successful Mesos `make` (any architecture), cd to
   `build/src/python/interface`.

4. Run `python setup.py register` to register this package.

5. Run `python setup.py sdist bdist_egg upload` to upload the source
   distribution and egg for this package.

Update the Mesos Homebrew package.

1. Update the [Homebrew formula for Mesos](https://github.com/Homebrew/homebrew-core/blob/master/Formula/mesos.rb)
   and test.

2. Submit a PR to the [Homebrew repo](https://github.com/Homebrew/homebrew-core).

3. Once accepted, verify that `brew install mesos` works.


text:
/**
 *
 * Emerald (kbi/elude @2014-2015)
 *
 */
#ifndef PLUGIN_PACK_H
#define PLUGIN_PACK_H

#include "system/system_types.h"

/** TODO */
PUBLIC void AddFileToFinalBlob(system_hashed_ansi_string filename);

/** TODO */
PUBLIC void DeinitPackData();

/** TODO */
PUBLIC void InitPackData();

/** TODO */
PUBLIC void SaveFinalBlob(system_hashed_ansi_string packed_scene_filename);

#endif /* PLUGIN_PACK_H */


text:
POST https://api.recurly.com/v2/subscriptions/123456789012345678901234567890ab/add_ons/marketing_emails/usage HTTP/1.1
X-Api-Version: {api-version}
Accept: application/xml
Authorization: Basic YXBpa2V5Og==
User-Agent: {user-agent}
Content-Type: application/xml; charset=utf-8

<?xml version="1.0" encoding="UTF-8"?>
<usage>
  <amount type="integer">100</amount>
  <merchant_tag>Recording 100 emails used by customer</merchant_tag>
  <recording_timestamp type="datetime">2016-12-12T12:00:00Z</recording_timestamp>
  <usage_timestamp type="datetime">2016-12-12T12:00:00Z</usage_timestamp>
</usage>

HTTP/1.1 201 Created
Content-Type: application/xml; charset=utf-8
Location: https://api.recurly.com/v2/subscriptions/123456789012345678901234567890ab/add_ons/marketing_emails/usage/12345678

<?xml version="1.0" encoding="UTF-8"?>
<usage href="https://api.recurly.com/v2/subscriptions/123456789012345678901234567890ab/add_ons/marketing_emails/usage/12345678">
  <id type="integer">12345678</id>
  <measured_unit href="https://api.recurly.com/v2/measured_units/123456"/>
  <amount type="integer">100</amount>
  <merchant_tag>Recording 100 emails used by customer</merchant_tag>
  <recording_timestamp type="datetime">2016-12-12T12:00:00Z</recording_timestamp>
  <usage_timestamp type="datetime">2016-12-12T12:00:00Z</usage_timestamp>
  <created_at type="date">2016-12-12T00:00:00+00:00</created_at>
  <updated_at nil="nil"></updated_at>
  <billed_at nil="nil"></billed_at>
  <usage_type>AMOUNT</usage_type>
  <unit_amount_in_cents nil="nil">40</unit_amount_in_cents>
</usage>


text:
require 'fileutils'
require_relative '../../gwr_utilities/argument_parser.rb'
require_relative '../../gwr_utilities/file-order.rb'
require_relative '../../gwr_utilities/parse.rb'

class Incremental_Rename

  def initialize

    @pwd = Dir.pwd

    if ARGV[0] == 'c'
      (0..15).each do |n|
        FileUtils.touch( File.join(@pwd, "#{n}.jpg" ) )
      end
      exit(0)
    end

    process_arguments()
    validate_arguments()
    get_files()
    determine_sort_type()
    rename_files()

  end

  def process_arguments()

    @args = Argument_parser.new(ARGV)
    @args.argument_prefix = '-'
    @args.throw_exception = true

    @args.valid_arguments = [
      [ 'n', nil,  'Optional: Force sorting by normal conventions' ],
      [ 'w', nil,  'Optional: Force sorting by the Windows convention' ],
      [ 'p', nil, 'Optional: Add image/video type prefix markers' ],
      [ 'h', nil, 'Optional: Displays help'],
    ]

    @args.process_arguments

  end

  def validate_arguments()

    if @args.has_argument?('n') && @args.has_argument?('w')
      puts 'ERROR: Cannot force both normal and windows sorting.'; exit(1)
    end

    if @args.has_argument?('h')
      @args.print_arguments
      exit(0)
    end

  end

  def get_files()

    @files = Array.new
    Dir.entries(@pwd).each do |item|

      if !['.', '..'].include?(item) && filetype?( item, true, true )
        @files << item
      end
    end

    puts "#{@files.size} file#{Parse.plural(@files.size)} found."

    if !@args.has_argument?('w')
      @files_normal = @files.sort{ |x,y| x <=> y }
    end

    if !@args.has_argument?('n')
      @files_windows = File_order.windows_sort(@files)
    end

  end

  def determine_sort_type()

    sort = 'n' if @args.has_argument?('n')
    sort = 'w' if @args.has_argument?('w')

    if !sort

      different = false
      (0..@files.size-1).each do |i|
        different = true if !different && @files_normal[i] != @files_windows[i]
      end

      if !different
        sort = 'n'
      else

        puts "This directory orders differently when sorted by normal / windows methods"
        message = "Type 'n' or 'w' to choose the sort method, or 'open' to show the directory:"

        begin
          puts message
          input = gets.chomp

          if ['n', 'w'].include?(input)
            sort = input
          elsif input == 'open'
            `start #{@pwd}`
          elsif ['', 'exit'].include?(input)
            exit(0)
          end

        end while sort == nil

      end
    end

    @files = Array.new
    case sort
      when 'n'; @files = @files_normal
      when 'w'; @files = @files_windows
    end

  end

  def rename_files()

    # Interim rename
    count = 0
    @files.each do |file|

      count += 1
      extension = file.split('.')[-1]

      new_name = "GWR-%03d.%s" % [ count, extension ]

      File.rename( File.join(@pwd, file), File.join(@pwd, new_name) )
    end

    # Final rename
    # File.rename( File.join(@pwd, item), File.join(@pwd, item[4..-1]) )
    count = 0
    count_image = 0
    count_video = 0

    Dir.entries(@pwd).each do |item|
      if item[0..3] == 'GWR-'

        # Prefixed
        if @args.has_argument?('p')

          # Image
          if filetype?( item, true, false )

            count_image += 1
            new_name = "P-%03d.%s" % [ count_image, item.split('.')[-1] ]
            File.rename( File.join(@pwd, item), File.join(@pwd, new_name) )

          # Video
          else

            count_video += 1
            new_name = "A-%03d.%s" % [ count_video, item.split('.')[-1] ]
            File.rename( File.join(@pwd, item), File.join(@pwd, new_name) )
          end

        # Normal
        else

          count += 1
          new_name = "%03d.%s" % [ count, item.split('.')[-1] ]
          File.rename( File.join(@pwd, item), File.join(@pwd, new_name) )
        end

      end
    end

  end

  def filetype?( file, image, video )

    extensions = Array.new
    extensions << [ 'gif', 'jpg', 'jpeg', 'png' ] if image
    extensions << [ 'avi', 'flv', 'mp4', 'mpeg', 'mpg', 'wmv' ] if video
    extensions.flatten!

    return extensions.include?( file.split('.')[-1].downcase )
  end

end

if __FILE__ == $PROGRAM_NAME
  go = Incremental_Rename.new
  exit(0)
end


text:
from concurrent.futures import Future

from gremlin_python.driver import client, serializer
from gremlin_python.driver.remote_connection import (
    RemoteConnection, RemoteTraversal)

__author__ = 'David M. Brown (davebshow@gmail.com)'

class DriverRemoteConnection(RemoteConnection):

    def __init__(self, url, traversal_source, protocol_factory=None,
                 transport_factory=None, pool_size=None, max_workers=None,
                 username="", password="", message_serializer=None,
                 graphson_reader=None, graphson_writer=None,
                 headers=None):
        if message_serializer is None:
            message_serializer = serializer.GraphSONMessageSerializer(
                reader=graphson_reader,
                writer=graphson_writer)
        self._client = client.Client(url, traversal_source,
                                     protocol_factory=protocol_factory,
                                     transport_factory=transport_factory,
                                     pool_size=pool_size,
                                     max_workers=max_workers,
                                     message_serializer=message_serializer,
                                     username=username,
                                     password=password,
                                     headers=headers)
        self._url = self._client._url
        self._traversal_source = self._client._traversal_source

    def close(self):
        self._client.close()

    def submit(self, bytecode):
        result_set = self._client.submit(bytecode)
        results = result_set.all().result()
        return RemoteTraversal(iter(results))

    def submitAsync(self, bytecode):
        future = Future()
        future_result_set = self._client.submitAsync(bytecode)

        def cb(f):
            try:
                result_set = f.result()
                results = result_set.all().result()
                future.set_result(RemoteTraversal(iter(results)))
            except Exception as e:
                future.set_exception(e)

        future_result_set.add_done_callback(cb)
        return future


text:
package org.ciwise.blackhole.service.dto;

import java.io.Serializable;
import java.util.Objects;

public class SnapshotAccount implements Serializable {

	/**
	 * unique serial identifier
	 */
	private static final long serialVersionUID = -1432490132110037987L;

	private Long id;

    private String name;

    private String type;

    private String dc;

    private String cno;

    private String balance;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getDc() {
		return dc;
	}

	public void setDc(String dc) {
		this.dc = dc;
	}

	public String getCno() {
		return cno;
	}

	public void setCno(String cno) {
		this.cno = cno;
	}

	public String getBalance() {
		return balance;
	}

	public void setBalance(String balance) {
		this.balance = balance;
	}

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SnapshotAccount snapAccount = (SnapshotAccount) o;
        if(snapAccount.id == null || id == null) {
            return false;
        }
        return Objects.equals(id, snapAccount.id);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }

    @Override
    public String toString() {
        return "SnapshotAccount{" +
            "id=" + id +
            ", name='" + name + "'" +
            ", type='" + type + "'" +
            ", dc='" + dc + "'" +
            ", cno='" + cno + "'" +
            ", balance='" + balance + "'" +
            '}';
    }

}


text:
/* eslint-disable max-len */
var outputToObservable = require('../conversion/outputToObservable');
var noteToJsongOrPV = require('../conversion/noteToJsongOrPV');
var spreadPaths = require('./../../support/spreadPaths');
var getValue = require('./../../cache/getValue');
var jsongMerge = require('./../../cache/jsongMerge');
var optimizePathSets = require('./../../cache/optimizePathSets');
var hasIntersection = require('./../../operations/matcher/intersection/hasIntersection');
var pathValueMerge = require('./../../cache/pathValueMerge');
var Observable = require('rx').Observable;
/* eslint-enable max-len */

module.exports = function outerRunSetAction(routerInstance, modelContext,
                                            jsongCache) {
    return function innerRunSetAction(matchAndPath) {
        return runSetAction(routerInstance, modelContext,
                            matchAndPath, jsongCache);
    };
};

function runSetAction(routerInstance, jsongMessage, matchAndPath, jsongCache) {
    var match = matchAndPath.match;
    var out;
    var arg = matchAndPath.path;

    // We are at out destination.  Its time to get out
    // the pathValues from the
    if (match.isSet) {
        var paths = spreadPaths(jsongMessage.paths);

        // We have to ensure that the paths maps in order
        // to the optimized paths array.
        var optimizedPathsAndPaths =
            paths.
                // Optimizes each path.
                map(function(path) {
                    return [optimizePathSets(
                        jsongCache, [path], routerInstance.maxRefFollow)[0],
                        path];
                }).
                // only includes the paths from the set that intersect
                // the virtual path
                filter(function(optimizedAndPath) {
                    return optimizedAndPath[0] &&
                        hasIntersection(optimizedAndPath[0], match.virtual);
                });
        var optimizedPaths = optimizedPathsAndPaths.map(function(opp) {
            return opp[0];
        });
        var subSetPaths = optimizedPathsAndPaths.map(function(opp) {
            return opp[1];
        });
        var tmpJsonGraph = subSetPaths.
            reduce(function(json, path, i) {
                pathValueMerge(json, {
                    path: optimizedPaths[i],
                    value: getValue(jsongMessage.jsonGraph, path)
                });
                return json;
            }, {});

        // Takes the temporary JSONGraph, attaches only the matched paths
        // then creates the subset json and assigns it to the argument to
        // the set function.
        var subJsonGraphEnv = {
            jsonGraph: tmpJsonGraph,
            paths: [match.requested]
        };
        arg = {};
        jsongMerge(arg, subJsonGraphEnv);
    }
    try {
        out = match.action.call(routerInstance, arg);
        out = outputToObservable(out);
    } catch (e) {
        out = Observable.throw(e);
    }

    return out.
        materialize().
        filter(function(note) {
            return note.kind !== 'C';
        }).
        map(noteToJsongOrPV(matchAndPath));
}


text:
package mesosphere.marathon
package core.launchqueue.impl

import akka.NotUsed
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.instance.update.{InstanceChangeOrSnapshot, InstanceUpdated, InstancesSnapshot}
import mesosphere.marathon.core.instance.{Instance, TestInstanceBuilder}
import mesosphere.marathon.core.launchqueue.impl.ReviveOffersStreamLogic.{DelayedStatus, IssueRevive, RoleDirective, UpdateFramework}
import mesosphere.marathon.state.{AbsolutePathId, AppDefinition}
import org.scalatest.Inside

import scala.concurrent.Future
import scala.concurrent.duration._

class ReviveOffersStreamLogicTest extends AkkaUnitTest with Inside {

  import ReviveOffersStreamLogic.{Delayed, NotDelayed}

  val webApp = AppDefinition(id = AbsolutePathId("/test"), role = "web")
  val monitoringApp = AppDefinition(id = AbsolutePathId("/test2"), role = "monitoring")

  val inputSourceQueue = Source.queue[Either[InstanceChangeOrSnapshot, DelayedStatus]](16, OverflowStrategy.fail)
  val outputSinkQueue = Sink.queue[RoleDirective]()
  val launchedInstance = TestInstanceBuilder.newBuilderForRunSpec(webApp).addTaskLaunched().instance

  "Suppress and revive" should {
    "combine 3 revive-worth events received within the throttle window in to a two throttle events" in {
      val instance1 = Instance.scheduled(webApp)
      val instance2 = Instance.scheduled(webApp)
      val instance3 = Instance.scheduled(webApp)

      Given("A suppress/revive flow with suppression enabled and 200 millis revive interval")
      val suppressReviveFlow =
        ReviveOffersStreamLogic.suppressAndReviveFlow(minReviveOffersInterval = 200.millis, enableSuppress = true, defaultRole = "web")

      val (input, output) = inputSourceQueue.via(suppressReviveFlow).toMat(outputSinkQueue)(Keep.both).run

      When("An initial snapshot with a launched instance is offered")
      input.offer(Left(InstancesSnapshot(List(launchedInstance)))).futureValue

      Then("An update framework event is issued with the role suppressed in response to the snapshot")
      inside(output.pull().futureValue) {
        case Some(UpdateFramework(roleState, newlyRevived, newlySuppressed)) =>
          roleState shouldBe Map("web" -> OffersNotWanted)
          newlyRevived shouldBe Set.empty
          newlySuppressed shouldBe Set.empty
      }

      And("3 instance updates are sent for the role 'web'")
      Future
        .sequence(Seq(instance1, instance2, instance3).map { i =>
          input.offer(Left(InstanceUpdated(i, None, Nil)))
        })
        .futureValue

      Then("The revives from the instances get combined in to a single update framework call")
      inside(output.pull().futureValue) {
        case Some(UpdateFramework(roleState, newlyRevived, newlySuppressed)) =>
          roleState shouldBe Map("web" -> OffersWanted)
          newlyRevived shouldBe Set("web")
          newlySuppressed shouldBe Set.empty
      }

      And("the revive is eventually repeated")
      inside(output.pull().futureValue) {
        case Some(IssueRevive(roles)) =>
          roles shouldBe Set("web")
      }

      When("the stream is closed")
      input.complete()

      Then("no further events are emitted")
      output.pull().futureValue shouldBe None // should be EOS
    }

    "does not send suppress if enableSuppress is disabled" in {
      val suppressReviveFlow =
        ReviveOffersStreamLogic.suppressAndReviveFlow(minReviveOffersInterval = 200.millis, enableSuppress = false, defaultRole = "web")

      val result = Source(List(Left(InstancesSnapshot(List(launchedInstance)))))
        .via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue

      inside(result) {
        case Seq(UpdateFramework(roleState, newlyRevived, newlySuppressed)) =>
          roleState shouldBe Map("web" -> OffersWanted)
          newlyRevived shouldBe Set("web")
          newlySuppressed shouldBe Set.empty
      }
    }
  }

  "ReviveRepeaterLogic" should {
    "send a repeat after the second tick for roles newly revived by UpdateFramework" in {
      val logic = new ReviveOffersStreamLogic.ReviveRepeaterLogic

      logic.processRoleDirective(UpdateFramework(Map("role" -> OffersWanted), Set("role"), Set.empty))

      logic.handleTick() shouldBe Nil
      logic.handleTick() shouldBe List(IssueRevive(Set("role")))
    }

    "does not repeat revives for roles that become suppressed" in {
      val logic = new ReviveOffersStreamLogic.ReviveRepeaterLogic

      logic.processRoleDirective(UpdateFramework(Map("role" -> OffersWanted), Set("role"), Set.empty))
      logic.handleTick() shouldBe Nil

      logic.processRoleDirective(UpdateFramework(Map("role" -> OffersNotWanted), Set.empty, Set("role")))

      logic.handleTick() shouldBe Nil
      logic.handleTick() shouldBe Nil

    }

    "send a repeat revive once after the second tick" in {
      val logic = new ReviveOffersStreamLogic.ReviveRepeaterLogic

      logic.processRoleDirective(UpdateFramework(Map("role" -> OffersWanted), Set("role"), Set.empty))
      logic.handleTick() shouldBe Nil

      // First repeat for update framework
      logic.handleTick() shouldBe List(IssueRevive(Set("role")))

      // Revive was triggered
      logic.processRoleDirective(IssueRevive(Set("role")))
      logic.handleTick() shouldBe Nil

      // Second repeat for newly triggered revive
      logic.handleTick() shouldBe List(IssueRevive(Set("role")))
      logic.handleTick() shouldBe Nil
    }
  }

  "Suppress and revive without throttling" should {
    // Many of these components are more easily tested without throttling logic
    val suppressReviveFlow: Flow[Either[InstanceChangeOrSnapshot, ReviveOffersStreamLogic.DelayedStatus], RoleDirective, NotUsed] =
      ReviveOffersStreamLogic
        .reviveStateFromInstancesAndDelays("web")
        .map(_.roleReviveVersions)
        .via(ReviveOffersStreamLogic.reviveDirectiveFlow(enableSuppress = true))

    "issues a suppress for the default role in response to an empty snapshot" in {
      val results = Source(List(Left(InstancesSnapshot(Nil))))
        .via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue

      inside(results) {
        case Seq(UpdateFramework(roleState, newlyRevived, newlySuppressed)) =>
          roleState shouldBe Map("web" -> OffersNotWanted)
          newlyRevived shouldBe Set.empty
          newlySuppressed shouldBe Set.empty
      }
    }

    "emit a single revive for a snapshot with multiple instances to launch" in {
      val instance1 = Instance.scheduled(webApp)
      val instance2 = Instance.scheduled(webApp)

      val results = Source(List(Left(InstancesSnapshot(Seq(instance1, instance2)))))
        .via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue
      inside(results) {
        case Seq(UpdateFramework(roleState, newlyRevived, newlySuppressed)) =>
          roleState shouldBe Map("web" -> OffersWanted)
          newlyRevived shouldBe Set("web")
          newlySuppressed shouldBe Set.empty
      }
    }

    "emit a revive for each new scheduled instance added" in {
      val instance1 = Instance.scheduled(webApp)
      val instance2 = Instance.scheduled(webApp)

      val results = Source(
        List(
          Left(InstancesSnapshot(List(launchedInstance))),
          Left(InstanceUpdated(instance1, None, Nil)),
          Left(InstanceUpdated(instance2, None, Nil))
        )
      ).via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue

      inside(results) {
        case Seq(updateFramework: UpdateFramework, updateToReviveForFirstInstance: UpdateFramework, reviveForSecondInstance: IssueRevive) =>
          updateFramework.roleState shouldBe Map("web" -> OffersNotWanted)

          updateToReviveForFirstInstance.roleState shouldBe Map("web" -> OffersWanted)
          updateToReviveForFirstInstance.newlyRevived shouldBe Set("web")

          reviveForSecondInstance.roles shouldBe Set("web")
      }
    }

    "does not emit a new revive for updates to existing scheduled instances" in {
      val instance1 = Instance.scheduled(webApp)

      val results = Source(
        List(
          Left(InstancesSnapshot(List(launchedInstance))),
          Left(InstanceUpdated(instance1, None, Nil)),
          Left(InstanceUpdated(instance1, None, Nil))
        )
      ).via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue

      inside(results) {
        case Seq(updateFramework: UpdateFramework, updateToReviveForFirstInstance: UpdateFramework) =>
          updateFramework.roleState shouldBe Map("web" -> OffersNotWanted)

          updateToReviveForFirstInstance.roleState shouldBe Map("web" -> OffersWanted)
          updateToReviveForFirstInstance.newlyRevived shouldBe Set("web")
      }
    }

    "does not revive if an instance is backed off" in {
      val instance1 = Instance.scheduled(webApp)

      val results =
        Source(List(Left(InstancesSnapshot(Nil)), Right(Delayed(webApp.configRef)), Left(InstanceUpdated(instance1, None, Nil))))
          .via(suppressReviveFlow)
          .runWith(Sink.seq)
          .futureValue

      inside(results) {
        case Seq(UpdateFramework(roleState, newlyRevived, newlySuppressed)) =>
          roleState shouldBe Map("web" -> OffersNotWanted)
      }
    }

    "suppresses if an instance becomes backed off, and re-revives when it is available again" in {
      val instance1 = Instance.scheduled(webApp)

      val results = Source(
        List(
          Left(InstancesSnapshot(Nil)),
          Left(InstanceUpdated(instance1, None, Nil)),
          Right(Delayed(webApp.configRef)),
          Right(NotDelayed(webApp.configRef))
        )
      ).via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue

      inside(results) {
        case Seq(initialUpdate: UpdateFramework, update1: UpdateFramework, update2: UpdateFramework, update3: UpdateFramework) =>
          initialUpdate.roleState("web") shouldBe OffersNotWanted
          update1.roleState("web") shouldBe OffersWanted
          update2.roleState("web") shouldBe OffersNotWanted
          update3.roleState("web") shouldBe OffersWanted
      }
    }

    "does not suppress if a backoff occurs for one instance, but there is still a scheduled instance" in {
      val webInstance = Instance.scheduled(webApp)
      val monitoringInstance = Instance.scheduled(monitoringApp)

      val results = Source(List(Left(InstancesSnapshot(Seq(webInstance, monitoringInstance))), Right(Delayed(webApp.configRef))))
        .via(suppressReviveFlow)
        .runWith(Sink.seq)
        .futureValue

      inside(results) {
        case Seq(update1: UpdateFramework, update2: UpdateFramework) =>
          update1.roleState shouldBe Map("monitoring" -> OffersWanted, "web" -> OffersWanted)

          update2.roleState shouldBe Map("monitoring" -> OffersWanted, "web" -> OffersNotWanted)
      }
    }
  }
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/containers/storage/pkg/mflag"
	"github.com/containers/storage/storage"
)

func version(flags *mflag.FlagSet, action string, m storage.Store, args []string) int {
	version, err := m.Version()
	if err != nil {
		fmt.Fprintf(os.Stderr, "version: %v\n", err)
		return 1
	}
	if jsonOutput {
		json.NewEncoder(os.Stdout).Encode(version)
	} else {
		for _, pair := range version {
			fmt.Fprintf(os.Stderr, "%s: %s\n", pair[0], pair[1])
		}
	}
	return 0
}

func init() {
	commands = append(commands, command{
		names:   []string{"version"},
		usage:   "Return oci-storage version information",
		minArgs: 0,
		action:  version,
		addFlags: func(flags *mflag.FlagSet, cmd *command) {
			flags.BoolVar(&jsonOutput, []string{"-json", "j"}, jsonOutput, "Prefer JSON output")
		},
	})
}


text:
module Validatable
  class ValidatesLengthOf < ValidationBase #:nodoc:
    option :minimum, :maximum, :is, :within

    def message(instance)
      super || "is invalid"
    end

    def valid?(instance)
      valid = true
      value = instance.send(self.attribute)

      if value.nil?
        return true if allow_nil
        value = ''
      end

      if value.blank?
        return true if allow_blank
        value = ''
      end

      valid &&= value.length <= maximum unless maximum.nil?
      valid &&= value.length >= minimum unless minimum.nil?
      valid &&= value.length == is unless is.nil?
      valid &&= within.include?(value.length) unless within.nil?
      valid
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace CrudMaster
{
    class DAO
    {
        //Listas de acesso públicas
        public static List<Pessoa> pessoaLista = new List<Pessoa>();
        public static List<Produto> produtoLista = new List<Produto>();
        public static List<Funcionario> funcionarioLista = new List<Funcionario>();

        //Handlers de arquivo para leitura e escrita
        public static StreamReader clienteFile;
        public static StreamReader produtoFile;
        public static StreamReader funcionarioFile;

        //Variáveis miscelâneas
        public static string path = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
        public static string userLogado { get; set; } = "";

        //Funções
        public static void cadastrar_cliente(Pessoa p)
        {
            pessoaLista.Add(p);
            Debug.WriteLine("[DAO] Added new Pessoa to list.");
            Debug.WriteLine("[DAO] Info: " + p.ToString());
            File.AppendAllText((path + @"\Clientes.txt"), p.ToString()+ '\r' + '\n');
            Debug.WriteLine("[DAO] Appended new Pessoa to persistent file.");
        }

        public static void cadastrar_produto(Produto prod)
        {
            produtoLista.Add(prod);
            File.AppendAllText((path + @"\Produtos.txt"), prod.ToString() + Environment.NewLine);
        }

        public static void edita_produto(Produto antigo, Produto novo)
        {
            string text = File.ReadAllText(path + @"\Produtos.txt");
            text = text.Replace(antigo.nome + "/" + antigo.quantidade + "/" + antigo.preco + "/" + antigo.fabricante, novo.nome + "/" + novo.quantidade + "/" + novo.preco + "/" + novo.fabricante);
            File.WriteAllText((path + @"\Produtos.txt"), text);
        }

        public static void excluir_produto(Produto p)
        {
            string[] lines = System.IO.File.ReadAllLines(path + @"\Produtos.txt");

            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(path + @"\Produtos.txt"))
            {
                foreach (string line in lines)
                {
                    if (!line.Contains(p.nome + "/" + p.quantidade + "/" + p.preco + "/" + p.fabricante))
                    {
                        writer.WriteLine(line);
                    }
                }
            }
        }

        public static void inicializar_dados()
        {
            string line;
            pessoaLista.Clear();
            funcionarioLista.Clear();
            produtoLista.Clear();

            Debug.WriteLine("[DAO] Preparing to read file: " + path + @"\Clientes.txt!");
            if (File.Exists(path+ @"\Clientes.txt") == false)
            {
                try
                {
                    //Cria o arquivo no primeiro run
                    Debug.WriteLine("[DAO] Generating new txt file...");
                    File.WriteAllText(path + @"\Clientes.txt", "");
                }
                catch (Exception e)
                {
                    MessageBox.Show("Could not create file handler! Try running as administrator!\n" +
                        "Exception: "+e.ToString());
                    throw;
                }
            }
            else
            {
                Debug.WriteLine("[DAO] File exists, loading from disk...");
            }
            clienteFile = new System.IO.StreamReader(path + @"\Clientes.txt");
            while((clienteFile.BaseStream.Length != 0) && !clienteFile.EndOfStream)
            {
                //Nome:Endereço:Telefone:CPF:Email%Descricao1:10/11/2017#Descricao2:10/11/2017
                List<Servico> servicosRead = new List<Servico>();
                line = clienteFile.ReadLine();
                if (line.Length > 3)
                {
                    var splitPessoaServico = line.Split('%');
                    var pessoaSubs = splitPessoaServico[0].Split(':');
                    if (splitPessoaServico.Length == 2)
                    {
                        var servicosSubs = splitPessoaServico[1].Split('#');
                        foreach (string s in servicosSubs)
                        {
                            var newservico = new Servico(s);
                            servicosRead.Add(newservico);
                        }
                    }
                    Pessoa p = new Pessoa(pessoaSubs[0], pessoaSubs[2], pessoaSubs[3], pessoaSubs[1], pessoaSubs[4], servicosRead);
                    pessoaLista.Add(p);
                }
            }
            clienteFile.Close();

            Debug.WriteLine("[DAO] Preparing to read file: " + path + @"\Produtos.txt!");
            if (File.Exists(path + @"\Produtos.txt") == false)
            {
                try
                {
                    //Cria o arquivo no primeiro run
                    Debug.WriteLine("[DAO] Generating new txt file...");
                    File.WriteAllText(path + @"\Produtos.txt", "");
                }
                catch (Exception e)
                {
                    MessageBox.Show("Could not create file handler! Try running as administrator!\n" +
                        "Exception: " + e.ToString());
                    throw;
                }
            }
            else
            {
                Debug.WriteLine("[DAO] File exists, loading from disk...");
            }
            produtoFile = new System.IO.StreamReader(path + @"\Produtos.txt");
            produtoFile.Close();

            //Funcionario
            Debug.WriteLine("[DAO] Preparing to read file: " + path + @"\Funcionarios.txt!");
            if (File.Exists(path + @"\Funcionarios.txt") == false)
            {
                try
                {
                    //Cria o arquivo no primeiro run
                    Debug.WriteLine("[DAO] Generating new txt file...");
                    File.WriteAllText(path + @"\Funcionarios.txt", "");
                }
                catch (Exception e)
                {
                    MessageBox.Show("Could not create file handler! Try running as administrator!\n" +
                        "Exception: " + e.ToString());
                    throw;
                }
            }
            else
            {
                Debug.WriteLine("[DAO] File exists, loading from disk...");
            }
            funcionarioFile = new System.IO.StreamReader(path + @"\Funcionarios.txt");
            while ((funcionarioFile.BaseStream.Length != 0) && !funcionarioFile.EndOfStream)
            {
                //nome:senha:username
                List<Servico> servicosRead = new List<Servico>();
                line = funcionarioFile.ReadLine();
                if (line.Length > 3)
                {
                    var split = line.Split(':');
                    var s = new Funcionario(split[0], split[1], split[2]);
                    funcionarioLista.Add(s);
                }
            }
            funcionarioFile.Close();
        }

        public static void edita_cliente(Pessoa p, int index)
        {
            pessoaLista.ElementAt(index).nome = p.nome;
            pessoaLista.ElementAt(index).endereço = p.endereço;
            pessoaLista.ElementAt(index).cpf = p.cpf;
            pessoaLista.ElementAt(index).email = p.email;
            pessoaLista.ElementAt(index).telefone = p.telefone;
            pessoaLista.ElementAt(index).servicos = p.servicos;

            string text = File.ReadAllText(path + @"\Clientes.txt");
            var textSplit = text.Split('\n');
            textSplit[index] = pessoaLista.ElementAt(index).ToString() + '\r';
            text = "";
            foreach (string t in textSplit)
            {
                text = text + t + '\n';
            }
            File.WriteAllText(path + @"\Clientes.txt", text);
        }

        public static void cadastrar_funcionario(Funcionario p)
        {
            funcionarioLista.Add(p);
            File.AppendAllText((path + @"\Funcionarios.txt"), p.ToString() + '\r' + '\n');
            Debug.WriteLine("[DAO] Wrote '" + p.ToString() + "' to the file.");
        }

        public static void excluir_funcionario(Funcionario removido)
        {
            //Remove funcionario da lista de funcionarios
            foreach (Funcionario item in funcionarioLista)
            {
                if (String.Equals(removido.nome, item.nome))
                {
                    funcionarioLista.Remove(item);
                    break;
                }
            }

            //Grava a lista inteira no arquivo denovo
            string result = "";
            foreach (Funcionario item in funcionarioLista)
            {
                result = result + item.ToString() + '\r' + '\n';
            }
            File.WriteAllText((path + @"\Funcionarios.txt"), result);
        }
    }
}


text:
<?php

namespace olivestudio\olivemenus\controllers;

use olivestudio\olivemenus\assetbundles\olivemenus\OlivemenuItemsAsset;
use olivestudio\olivemenus\models\OlivemenusItemsModel;
use olivestudio\olivemenus\Olivemenus;

use Craft;
use craft\web\Controller;

/**
 * MenuItems Controller
 *
 * Generally speaking, controllers are the middlemen between the front end of
 * the CP/website and your plugin's services. They contain action methods which
 * handle individual tasks.
 *
 * A common pattern used throughout Craft involves a controller action gathering
 * post data, saving it on a model, passing the model off to a service, and then
 * responding to the request appropriately depending on the service method's response.
 *
 * Action methods begin with the prefix "action", followed by a description of what
 * the method does (for example, actionSaveIngredient()).
 *
 * https://craftcms.com/docs/plugins/controllers
 *
 * @author    Olivestudio
 * @package   Olivemenus
 * @since     1.0.0
 */
class MenuItemsController extends Controller
{

    // Protected Properties
    // =========================================================================

    /**
     * @var    bool|array Allows anonymous access to this controller's actions.
     *         The actions must be in 'kebab-case'
     * @access protected
     */
    protected array|bool|int $allowAnonymous = ['edit', 'save-menu-items'];

    // Public Methods
    // =========================================================================

    /**
     * Handle a request going to our plugin's edit action URL,
     * e.g.: actions/olivemenus/menu-items
     *
     * @return mixed
     */
    public function actionEdit(int $menuId = null): mixed
    {
        $this->view->registerAssetBundle(OlivemenuItemsAsset::class);
        $menu = Olivemenus::$plugin->olivemenus->getMenuById($menuId);
        $data['menu'] = $menu;
        $data['sections'] = Olivemenus::$plugin->olivemenuItems->getSectionsWithEntries($menu->site_id);
        $data['menuItemsMarkup'] = Olivemenus::$plugin->olivemenuItems->getMenuItemsAdminMarkup($menuId);
        $data['categories'] = Craft::$app
                                   ->categories
                                   ->getAllGroups();

        $objSite = Craft::$app->getSites()->getSiteById($menu->site_id);
        if (!$objSite) {
            $siteHandle = Craft::$app->getSites()->getPrimarySite()->handle;
            $objSite = Craft::$app->getSites()->getSiteByHandle($siteHandle);
        }
        $data['objSite'] = $objSite;
        return $this->renderTemplate('olivemenus/_menu-items', $data);
    }

    /**
     * Handle a request going to our plugin's actionSave URL,
     * e.g.: actions/olivemenus/menu-items/save-menu-items
     *
     * @return void
     */
    public function actionSaveMenuItems(): void
    {
        $this->requirePostRequest();
        $intMenuId = Craft::$app->request->getBodyParams()['menu-id'];
        $strMenuItems = Craft::$app->request->getBodyParams()['menu-items-serialized'];

        $arrMenuItems = json_decode($strMenuItems, true);

        if (!empty($arrMenuItems)) {
            foreach($arrMenuItems as $order=> $menuItem) {
                $parent_id = 0;

                if (isset($menuItem['parent-id'])){
                    $parent_id = $menuItem['parent-id'];

                    foreach ($arrMenuItems as $element) {
                        if (isset($element['item-id']['html']) && $element['item-id']['html'] == $parent_id) {
                            $parent_id = $element['menu-item-db-id'];
                            $arrMenuItems[$order]['parent-id'] = $parent_id;
                            break;
                        }
                    }
                }

                if ($menuItem['item-id']['db'] != null) {
                    $menuItemModel = Olivemenus::$plugin->olivemenuItems->getMenuItem($menuItem['item-id']['db']);
                } else {
                    $menuItemModel = new OlivemenusItemsModel();
                }
                $arrData['id']= $menuItem['item-id']['db'];
                $arrData['menu_id']= $intMenuId;
                $arrData['parent_id']= $parent_id;
                $arrData['item_order']= $order;
                $arrData['name']= $menuItem['name'];
                $arrData['entry_id']= (isset($menuItem['entry-id']) ? $menuItem['entry-id'] : '');
                $arrData['custom_url']= (isset($menuItem['custom-url']) ? $menuItem['custom-url'] : '');
                $arrData['class']= (isset($menuItem['class']) ? $menuItem['class'] : '');
                $arrData['class_parent']= (isset($menuItem['class-parent']) ? $menuItem['class-parent'] : '');
                $arrData['data_json']= (isset($menuItem['data-json']) ? $menuItem['data-json'] : '');
                $arrData['target']= (isset($menuItem['target']) ? $menuItem['target'] : '');

                $menuItemModel->setAttributes($arrData);

                if ($menuItemModel->validate()) {
                    $menuItemDbId = Olivemenus::$plugin->olivemenuItems->saveMenuItem($menuItemModel);
                    if (is_numeric($menuItemDbId)) $arrMenuItems[$order]['menu-item-db-id'] = $menuItemDbId;
                }
            }
        }

        $menuItemsDeleted = Craft::$app->request->getBodyParams()['menu-items-deleted'];
        if (!empty($menuItemsDeleted)) {
            $arrItems = explode(',', $menuItemsDeleted);
            if (!empty($arrItems)) {
                foreach ($arrItems as $intVal) {
                    Olivemenus::$plugin->olivemenuItems->deleteMenuItem($intVal);
                }
            }
        }
        Craft::$app->getSession()->setNotice(Craft::t('olivemenus', 'Menu items saved successfully.'));
    }
}


text:
package se.toxbee.fimpl;

import java.util.Iterator;

/**
 * IterableWrapper wraps an {@link java.util.Iterator}.
 *
 * @param <E> the type of the Iterator.
 */
public class IterableWrapper<E> implements Iterable<E> {
	protected final Iterator<E> backend;

	/**
	 * Constructs the wrapper given an iterator.
	 *
	 * @param backend the backend iterator.
	 */
	public IterableWrapper( Iterator<E> backend ) {
		this.backend = backend;
	}

	@Override
	public Iterator<E> iterator() {
		return backend;
	}
}


text:
package brooklyn.entity.nosql.mongodb;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Iterator;

import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import org.bson.types.BasicBSONList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Optional;
import com.google.common.net.HostAndPort;

/**
 * Simplifies the creation of configuration objects for Mongo DB replica sets.
 *

 * A configuration object is structured like this:
 *

 * {
 *	"_id" : "replica-set-name",
 * 	"version" : 3,
 *	"members" : [
 *		{ "_id" : 0, "host" : "Sams.local:27017" },
 *		{ "_id" : 1, "host" : "Sams.local:27018" },
 *		{ "_id" : 2, "host" : "Sams.local:27019" }
 *	]
 * }
 *

 * To add or remove servers to a replica set you must redefine this configuration
 * (run replSetReconfig on the primary) with the new members
 * list and the version updated.
 */
public class ReplicaSetConfig {

    private static final Logger LOG = LoggerFactory.getLogger(ReplicaSetConfig.class);
    static final int MAXIMUM_REPLICA_SET_SIZE = 12;
    static final int MAXIMUM_VOTING_MEMBERS = 7;

    private Optional<HostAndPort> primary = Optional.absent();

    private String name;
    private Integer version;
    BasicBSONList members;

    public ReplicaSetConfig(String name) {
        this(name, new BasicBSONList());
    }

    public ReplicaSetConfig(String name, BasicBSONList existingMembers) {
        this.name = name;
        this.members = existingMembers;
        this.version = 1;
    }

    /**
     * Creates a configuration with the given name.
     */
    public static ReplicaSetConfig builder(String name) {
        return new ReplicaSetConfig(name);
    }

    /**
     * Creates a configuration from an existing configuration.
     *

     * Automatically increments the replica set's version number.
     */
    public static ReplicaSetConfig fromExistingConfig(BSONObject config) {
        checkNotNull(config);
        checkArgument(config.containsField("_id"), "_id missing from replica set config");
        checkArgument(config.containsField("version"), "version missing from replica set config");
        checkArgument(config.containsField("members"), "members missing from replica set config");

        String name = (String) config.get("_id");
        Integer version = (Integer) config.get("version");
        BasicBSONList members = (BasicBSONList) config.get("members");

        return new ReplicaSetConfig(name, members).version(++version);
    }

    /**
     * Sets the version of the configuration. The version number must increase as the replica set changes.
     */
    public ReplicaSetConfig version(Integer version) {
        this.version = version;
        return this;
    }

    /**
     * Notes the primary member of the replica. Primary members will always be voting members.
     */
    public ReplicaSetConfig primary(HostAndPort primary) {
        this.primary = Optional.of(primary);
        return this;
    }

    /**
     * Adds a new member to the replica set config using {@link MongoDBServer#HOSTNAME} and {@link MongoDBServer#PORT}
     * for hostname and port. Doesn't attempt to check that the id is free.
     */
    public ReplicaSetConfig member(MongoDBServer server, Integer id) {
        return member(server.getAttribute(MongoDBServer.HOSTNAME), server.getAttribute(MongoDBServer.PORT), id);
    }

    /**
     * Adds a new member to the replica set config using the given {@link HostAndPort} for hostname and port.
     * Doesn't attempt to check that the id is free.
     */
    public ReplicaSetConfig member(HostAndPort address, Integer id) {
        return member(address.getHostText(), address.getPort(), id);
    }

    /**
     * Adds a new member to the replica set config with the given hostname, port and id. Doesn't attempt to check
     * that the id is free.
     */
    public ReplicaSetConfig member(String hostname, Integer port, Integer id) {
        if (members.size() == MAXIMUM_REPLICA_SET_SIZE) {
            throw new IllegalStateException(String.format(
                    "Replica set {} exceeds maximum size of {} with addition of member at {}:{}",
                    new Object[]{name, MAXIMUM_REPLICA_SET_SIZE, hostname, port}));
        }
        BasicBSONObject member = new BasicBSONObject();
        member.put("_id", id);
        member.put("host", String.format("%s:%s", hostname, port));
        members.add(member);
        return this;
    }

    /** Removes the first entity using {@link MongoDBServer#HOSTNAME} and {@link MongoDBServer#PORT}. */
    public ReplicaSetConfig remove(MongoDBServer server) {
        return remove(server.getAttribute(MongoDBServer.HOSTNAME), server.getAttribute(MongoDBServer.PORT));
    }

    /** Removes the first entity with host and port matching the given address. */
    public ReplicaSetConfig remove(HostAndPort address) {
        return remove(address.getHostText(), address.getPort());
    }

    /**
     * Removes the first entity with the given hostname and port from the list of members
     */
    public ReplicaSetConfig remove(String hostname, Integer port) {
        String host = String.format("%s:%s", hostname, port);
        Iterator<Object> it = this.members.iterator();
        while (it.hasNext()) {
            Object next = it.next();
            if (next instanceof BasicBSONObject) {
                BasicBSONObject basicBSONObject = (BasicBSONObject) next;
                if (host.equals(basicBSONObject.getString("host"))) {
                    it.remove();
                    break;
                }
            }
        }
        return this;
    }

    /**
     * @return A {@link BasicBSONObject} representing the configuration that is suitable for a MongoDB server.
     */
    public BasicBSONObject build() {
        setVotingMembers();
        BasicBSONObject config = new BasicBSONObject();
        config.put("_id", name);
        config.put("version", version);
        config.put("members", members);
        return config;
    }

    /**
     * Selects 1, 3, 5 or 7 members to have a vote. The primary member (as set by
     * {@link #primary(com.google.common.net.HostAndPort)}) is guaranteed a vote if
     * it is in {@link #members}.
     *

     *
     * Reconfiguring a server to be voters when they previously did not have votes generally triggers
     * a primary election. This confuses the MongoDB Java driver, which logs an error like:
     *

     * WARN  emptying DBPortPool to sams.home/192.168.1.64:27019 b/c of error
     * java.io.EOFException: null
     *	at org.bson.io.Bits.readFully(Bits.java:48) ~[mongo-java-driver-2.11.3.jar:na]
     * WARN  Command { "replSetReconfig" : ... } on sams.home/192.168.1.64:27019 failed
     * com.mongodb.MongoException$Network: Read operation to server sams.home/192.168.1.64:27019 failed on database admin
     *	at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:253) ~[mongo-java-driver-2.11.3.jar:na]
     * Caused by: java.io.EOFException: null
     *	at org.bson.io.Bits.readFully(Bits.java:48) ~[mongo-java-driver-2.11.3.jar:na]
     *

     *
     * The MongoDB documentation on
     * non-voting members says:
     *

     *     Initializes a new replica set configuration. Disconnects the shell briefly and forces a
     *     reconnection as the replica set renegotiates which member will be primary. As a result,
     *     the shell will display an error even if this command succeeds.
     *

     *
     * So the problem is more that the MongoDB Java driver does not understand why the server
     * may have disconnected and is to eager to report a problem.
     */
    private void setVotingMembers() {
        if (LOG.isDebugEnabled())
            LOG.debug("Setting voting and non-voting members of replica set: {}", name);
        boolean seenPrimary = false;
        String expectedPrimary = primary.isPresent()
                ? primary.get().getHostText() + ":" + primary.get().getPort()
                : "";

        // Ensure an odd number of voters
        int setSize = this.members.size();
        int nonPrimaryVotingMembers = Math.min(setSize % 2 == 0 ? setSize - 1 : setSize, MAXIMUM_VOTING_MEMBERS);
        if (primary.isPresent()) {
            if (LOG.isTraceEnabled())
                LOG.trace("Reserving vote for primary: " + expectedPrimary);
            nonPrimaryVotingMembers -= 1;
        }

        for (Object member : this.members) {
            if (member instanceof BasicBSONObject) {
                BasicBSONObject bsonObject = BasicBSONObject.class.cast(member);
                String host = bsonObject.getString("host");

                // is this member noted as the primary?
                if (this.primary.isPresent() && expectedPrimary.equals(host)) {
                    bsonObject.put("votes", 1);
                    seenPrimary = true;
                    if (LOG.isDebugEnabled())
                        LOG.debug("Voting member (primary) of set {}: {}", name, host);
                } else if (nonPrimaryVotingMembers-- > 0) {
                    bsonObject.put("votes", 1);
                    if (LOG.isDebugEnabled())
                        LOG.debug("Voting member of set {}: {}", name, host);
                } else {
                    bsonObject.put("votes", 0);
                    if (LOG.isDebugEnabled())
                        LOG.debug("Non-voting member of set {}: {}", name, host);
                }
            } else {
                LOG.error("Unexpected entry in replica set members list: " + member);
            }
        }

        if (primary.isPresent() && !seenPrimary) {
            LOG.warn("Cannot give replica set primary a vote in reconfigured set: " +
                    "primary was indicated as {} but no member with that host and port was seen in the set. " +
                    "The replica set now has an even number of voters.",
                    this.primary);
        }
    }

}


text:
/**
 * @file mip-anchor 组件
 * @author
 */

define(function (require) {
    var customElement = require('customElement').create();
    customElement.prototype.firstInviewCallback = function () {
        var element = this.element;
        var attr = element.getAttribute('data-to');
        element.addEventListener('click', function () {
            var divTop = document.getElementById(attr).offsetTop;
            window.scrollTo(0, divTop);
        });
    };
    return customElement;
});