text:
<?php

namespace fangface\widgets;

use backend\assets\BootstrapDateTimePickerAsset;
use fangface\widgets\InputWidget;
use fangface\helpers\Html;

/**
 * Date and Time Picker widget
 */
class DateTimePicker extends InputWidget
{

    /**
     * @var string the name of the jQuery plugin
     */
    public $pluginName = 'datetimepicker';
    /**
     * @var array default widget plugin options that user pluginOptions will be merged into
     */
    public $defaultPluginOptions = ['format' => 'yyyy-mm-dd hh:ii:ss', 'todayBtn' => true, 'autoclose' => true, 'weekStart' => 1];
    /**
     * @var array the HTML attributes for the input tag.
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
     */
    public $options = ['class' => 'form-control input-medium'];
    /**
     * @var string element id to use when calling the datepicker
     */
    public $elementId = null;

    /**
     * Renders the color picker widget
     */
    protected function renderWidget()
    {
        $this->prepareInput();
        $this->registerAssets();
        $this->prepareTemplate();
        echo $this->renderTemplate();
    }

    /**
     * Prepare the input fields for the input
     *
     * @return void
     */
    protected function prepareInput()
    {
        if ($this->hasModel()) {
            if (!isset($this->options['value']) && $this->model->{$this->attribute} == '0000-00-00 00:00:00') {
                $this->options['value'] = '';
            }
            $this->sections['input'] = Html::activeTextInput($this->model, $this->attribute, $this->options);
        } else {
            $this->sections['input'] = Html::textInput($this->name, ($this->value == '0000-00-00 00:00:00' ? '' : $this->value), $this->options);
        }
    }

    /**
     * Registers the needed client assets
     *
     * @return void
     */
    public function registerAssets()
    {
        if ($this->disabled) {
            return;
        }
        $view = $this->getView();
        BootstrapDateTimePickerAsset::register($view);
        if ($this->elementId !== null) {
            $element = "jQuery('#" . $this->elementId . "')";
        } else {
            $element = "jQuery('#" . $this->options['id'] . "')";
        }
        $this->registerPlugin($this->pluginName, $element);
    }

}


text:
#ifndef STDLIB_NDARRAY_BASE_SINGELTON_DIMENSIONS_H
#define STDLIB_NDARRAY_BASE_SINGELTON_DIMENSIONS_H

#include <stdint.h>

/*
* If C++, prevent name mangling so that the compiler emits a binary file having undecorated names, thus mirroring the behavior of a C compiler.
*/
#ifdef __cplusplus
extern "C" {
#endif

/**
* Returns the number of singleton dimensions.
*/
int64_t stdlib_ndarray_singleton_dimensions( int64_t ndims, int64_t *shape );

#ifdef __cplusplus
}
#endif

#endif // !STDLIB_NDARRAY_BASE_SINGELTON_DIMENSIONS_H

redpajama_set_name: RedPajamaGithub


text:
FROM openjdk:8-jdk-alpine

ADD target/services.jar app.jar
ENV JAVA_OPTS=""

EXPOSE 8080

ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">src/PDFBuilder.js | formiojs</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

<meta name="description" content="JavaScript powered Forms with JSON Form Builder"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="formiojs"><meta property="twitter:description" content="JavaScript powered Forms with JSON Form Builder">

  Home

  Reference
  Source

    <input class="search-input">

CEventEmitter

CForm

CFormBuilder

CFormio

CPDFBuilder

CWizardBuilder

Fembed

VGlobalFormio

addonsCFormioAddon

VeditForms

buildersCBuilders

componentsCComponents

components/_classes/componentFComponent

components/_classes/component/editFormVEditFormUtils

components/_classes/fieldCField

components/_classes/listFListComponent

components/_classes/nestedFNestedComponent

components/addressFAddress

components/buttonFButton

components/checkboxCCheckBoxComponent

FCheckbox

components/columnsFColumns

components/containerCContainerComponent

FContainer

components/contentFContent

components/currencyCCurrencyComponent

FCurrency

components/datagridFDataGrid

components/datamapFDataMap

components/datetimeCDateTimeComponent

FDateTime

components/dayFDay

components/editgridFEditGrid

components/emailCEmailComponent

FEmail

components/fieldsetCFieldsetComponent

FFieldset

components/fileFFile

components/formFForm

components/hiddenCHiddenComponent

FHidden

components/htmlCHTMLComponent

FHTML

components/numberFNumber

components/panelFPanel

components/passwordCPasswordComponent

FPassword

components/phonenumberCPhoneNumberComponent

FPhoneNumber

components/radioFRadio

components/recaptchaCReCaptchaComponent

FReCaptcha

components/resourceCResourceComponent

FResource

components/selectFSelect

components/select/fixturesVmultiSelect

VmultiSelectOptions

components/selectboxesFSelectBoxes

components/signatureFSignature

components/surveyFSurvey

components/tableCTableComponent

FTable

components/tabsCTabsComponent

FTabs

components/tagsCTagsComponent

FTags

components/textareaFTextArea

components/textfieldFTextField

components/timeCTimeComponent

FTime

components/treeCNode

FTree

components/unknownCUnknownComponent

FUnknown

components/urlCUrlComponent

FUrl

components/wellCWellComponent

FWell

contribVContrib

contrib/edittableCEditTableComponent

FEditTable

contrib/locationCLocationComponent

FLocation

contrib/modaleditCModalEditComponent

FModalEdit

contrib/stripe/checkoutCStripeCheckoutComponent

contrib/stripe/stripeCStripeComponent

displaysCDisplays

providersCProviders

providers/addressCAddressProvider

CAzureAddressProvider

CCustomAddressProvider

CNominatimAddressProvider

providers/processorFfileProcessor

providers/storageFazure

Fbase64

Fdropbox

Fgoogledrive

Findexeddb

Fs3

FgetFormioUploadAdapterPlugin

Furl

FsetXhrHeaders

VXHR

templatesCTemplates

templates/bootstrapFiconClass

utilsCChoicesWrapper

FcheckInvalidDate

FlessOrGreater

FapplyFormChanges

FeachComponent

FescapeRegExCharacters

FfindComponent

FfindComponents

FflattenComponents

FformatAsCurrency

FgenerateFormChange

FgetComponent

FgetStrings

FgetValue

FhasCondition

FisLayoutComponent

FmatchComponent

FparseFloatExt

FremoveComponent

FsearchComponents

VKEY_CODES

VEvaluator

VCALENDAR_ERROR_MESSAGES

utils/jsonlogicVlodashOperators

validatorCRules

validator/conjunctionsCConjunctions

validator/operatorsCOperators

validator/quickRulesCQuickRules

validator/transformersCTransformers

validator/valueSourcesCValueSources

widgetsCInputWidget

src/PDFBuilder.js

import _ from 'lodash';
import NativePromise from 'native-promise-only';
import { GlobalFormio as Formio } from './Formio';

import WebformBuilder from './WebformBuilder';
import { fastCloneDeep, getElementRect } from './utils/utils';
import { eachComponent } from './utils/formUtils';
import BuilderUtils from './utils/builder';
import PDF from './PDF';

export default class PDFBuilder extends WebformBuilder {
  constructor() {
    let element, options;
    if (arguments[0] instanceof HTMLElement || arguments[1]) {
      element = arguments[0];
      options = arguments[1];
    }
    else {
      options = arguments[0];
    }

    // Force superclass to skip the automatic init; we'll trigger it manually
    options.skipInit = true;
    options.display = 'pdf';

    if (element) {
      super(element, options);
    }
    else {
      super(options);
    }

    this.dragDropEnabled = false;
  }

  get defaultGroups() {
    return {
      pdf: {
        title: 'PDF Fields',
        weight: 0,
        default: true,
        components: {
          textfield: true,
          number: true,
          password: true,
          email: true,
          phoneNumber: true,
          currency: true,
          checkbox: true,
          signature: true,
          select: true,
          textarea: true,
          datetime: true,
          file: true,
          htmlelement: true,
          signrequestsignature: true
        }
      },
      basic: false,
      advanced: false,
      layout: false,
      data: false,
      premium: false,
      resource: false
    };
  }

  get hasPDF() {
    return _.has(this.webform.form, 'settings.pdf');
  }

  get projectUrl() {
    return this.options.projectUrl || Formio.getProjectUrl();
  }

  init() {
    this.options.attachMode = 'builder';
    this.webform = this.webform || this.createForm(this.options);
    this.webform.init();
  }

  render() {
    const result = this.renderTemplate('pdfBuilder', {
      sidebar: this.renderTemplate('builderSidebar', {
        scrollEnabled: this.sideBarScroll,
        groupOrder: this.groupOrder,
        groupId: `builder-sidebar-${this.id}`,
        groups: this.groupOrder.map((groupKey) => this.renderTemplate('builderSidebarGroup', {
          group: this.groups[groupKey],
          groupKey,
          groupId: `builder-sidebar-${this.id}`,
          subgroups: this.groups[groupKey].subgroups.map((group) => this.renderTemplate('builderSidebarGroup', {
            group,
            groupKey: group.key,
            groupId: `group-container-${groupKey}`,
            subgroups: []
          })),
        })),
      }),
      form: this.hasPDF ?
        this.webform.render() :
        this.renderTemplate('pdfBuilderUpload', {})
    });

    return result;
  }

  attach(element) {
    // PDF Upload
    if (!this.hasPDF) {
      this.loadRefs(element, {
        'fileDrop': 'single',
        'fileBrowse': 'single',
        'hiddenFileInputElement': 'single',
        'uploadError': 'single',
        'uploadProgress': 'single',
        'uploadProgressWrapper': 'single',
        'dragDropText': 'single'
      });
      this.addEventListener(this.refs['pdf-upload-button'], 'click', (event) => {
        event.preventDefault();
      });

      // Init the upload error.
      if (!this.projectUrl) {
        this.setUploadError('Form options.projectUrl not set. Please set the "projectUrl" property of the options for this form or use Formio.setProjectUrl(). This setting is necessary to upload a pdf background.');
      }
      else {
        this.setUploadError();
      }

      if (this.refs.fileDrop) {
        const element = this;
        this.addEventListener(this.refs.fileDrop, 'dragover', function(event) {
          this.className = 'fileSelector fileDragOver';
          event.preventDefault();
        });
        this.addEventListener(this.refs.fileDrop, 'dragleave', function(event) {
          this.className = 'fileSelector';
          event.preventDefault();
        });
        this.addEventListener(this.refs.fileDrop, 'drop', function(event) {
          this.className = 'fileSelector';
          event.preventDefault();
          element.upload(event.dataTransfer.files[0]);
          return false;
        });
      }

      if (this.refs.fileBrowse && this.refs.hiddenFileInputElement) {
        this.addEventListener(this.refs.fileBrowse, 'click', (event) => {
          event.preventDefault();
          // There is no direct way to trigger a file dialog. To work around this, create an input of type file and trigger
          // a click event on it.
          if (typeof this.refs.hiddenFileInputElement.trigger === 'function') {
            this.refs.hiddenFileInputElement.trigger('click');
          }
          else {
            this.refs.hiddenFileInputElement.click();
          }
        });
        this.addEventListener(this.refs.hiddenFileInputElement, 'change', () => {
          if (!this.refs.hiddenFileInputElement.value) {
            return;
          }

          this.upload(this.refs.hiddenFileInputElement.files[0]);
          this.refs.hiddenFileInputElement.value = '';
        });
      }

      return NativePromise.resolve();
    }

    // Normal PDF Builder
    return super.attach(element).then(() => {
      this.loadRefs(this.element, {
        iframeDropzone: 'single',
        'sidebar-container': 'multiple',
        'sidebar': 'single',
      });

      this.afterAttach();
      return this.element;
    });
  }

  afterAttach() {
    this.on('saveComponent', (component) => {
      this.webform.postMessage({ name: 'updateElement', data: component });
    });
    this.on('removeComponent', (component) => {
      this.webform.postMessage({ name: 'removeElement', data: component });
    });
    this.initIframeEvents();
    this.updateDropzoneDimensions();

    const sidebar = this.refs.sidebar;
    if (sidebar) {
      this.addClass(sidebar, 'disabled');
      this.webform.on('iframe-ready', () => {
        this.pdfLoaded = true;
        this.updateDragAndDrop();
        this.removeClass(sidebar, 'disabled');
      }, true);
    }
  }

  upload(file) {
    const formio = new Formio(this.projectUrl);
    if (this.refs.dragDropText) {
      this.refs.dragDropText.style.display = 'none';
    }
    if (this.refs.uploadProgressWrapper) {
      this.refs.uploadProgressWrapper.style.display = 'inherit';
    }
    formio.uploadFile('url', file, file, '', (event) => {
      if (this.refs.uploadProgress) {
        const progress = Math.floor((event.loaded / event.total) * 100);
        this.refs.uploadProgress.style.width = `${progress}%`;
        if (progress > 98) {
          this.refs.uploadProgress.innerHTML = this.t('Converting PDF. Please wait.');
        }
        else {
          this.refs.uploadProgress.innerHTML = `${this.t('Uploading')} ${progress}%`;
        }
      }
    }, `${this.projectUrl}/upload`, {}, 'file')
      .then((result) => {
        _.set(this.webform.form, 'settings.pdf', {
          id: result.data.file,
          src: `${result.data.filesServer}${result.data.path}`
        });
        if (this.refs.dragDropText) {
          this.refs.dragDropText.style.display = 'inherit';
        }
        if (this.refs.uploadProgressWrapper) {
          this.refs.uploadProgressWrapper.style.display = 'none';
        }
        this.emit('pdfUploaded', result.data);
        this.redraw();
      })
      .catch((err) => this.setUploadError(err));
  }

  setUploadError(message) {
    if (!this.refs.uploadError) {
      return;
    }
    this.refs.uploadError.style.display = message ? '' : 'none';
    this.refs.uploadError.innerHTML = message;
  }

  createForm(options) {
    // Instantiate the webform from the PDF class instead of Webform
    options.skipInit = false;
    options.hideLoader = true;
    this.webform = new PDF(this.element, options);
    this.webform.on('attach', () => {
      // If the dropzone exists but has been removed in a PDF rebuild, reinstate it
      if (this.refs.iframeDropzone && ![...this.refs.form.children].includes(this.refs.iframeDropzone)) {
        this.prependTo(this.refs.iframeDropzone, this.refs.form);
      }
    });
    return this.webform;
  }

  destroy(deleteFromGlobal) {
    super.destroy(deleteFromGlobal);
    this.webform.destroy(deleteFromGlobal);
  }

  // d8b 8888888888                                                                              888
  // Y8P 888                                                                                888
  //     888                                                                                888
  // 888 8888888 888d888 8888b.  88888b.d88b.   .d88b.        .d88b.  888  888  .d88b.  88888b.  888888 .d8888b
  // 888 888     888P"      "88b 888 "888 "88b d8P  Y8b      d8P  Y8b 888  888 d8P  Y8b 888 "88b 888    88K
  // 888 888     888    .d888888 888  888  888 88888888      88888888 Y88  88P 88888888 888  888 888    "Y8888b.
  // 888 888     888    888  888 888  888  888 Y8b.          Y8b.      Y8bd8P  Y8b.     888  888 Y88b.       X88
  // 888 888     888    "Y888888 888  888  888  "Y8888        "Y8888    Y88P    "Y8888  888  888  "Y888  88888P'
  getParentContainer(component) {
    let container = [];
    let originalComponent = null;
    eachComponent(this.webform._form.components, (comp, path, components) => {
      if (comp.id === component.component.id) {
        container = components;
        originalComponent = comp;
        return true;
      }
    }, true);
    return {
      formioComponent: component.parent,
      formioContainer: container,
      originalComponent
    };
  }

  initIframeEvents() {
    this.webform.off('iframe-elementUpdate');
    this.webform.off('iframe-componentUpdate');
    this.webform.off('iframe-componentClick');
    this.webform.on('iframe-elementUpdate', schema => {
      const component = this.webform.getComponentById(schema.id);
      if (component && component.component) {
        const isNew = true;
        component.component.overlay = {
          page: schema.page,
          left: schema.left,
          top: schema.top,
          height: schema.height,
          width: schema.width
        };

        if (!this.options.noNewEdit && !component.component.noNewEdit) {
          this.editComponent(component.component, this.getParentContainer(component), isNew);
        }
        this.emit('updateComponent', component.component);
      }
      return component;
    });

    this.webform.on('iframe-componentUpdate', schema => {
      const component = this.webform.getComponentById(schema.id);
      if (component && component.component) {
        component.component.overlay = {
          page: schema.overlay.page,
          left: schema.overlay.left,
          top: schema.overlay.top,
          height: schema.overlay.height,
          width: schema.overlay.width
        };
        this.emit('updateComponent', component.component);
        this.emit('change', this.form);
      }
      return component;
    });

    this.webform.on('iframe-componentClick', schema => {
      const component = this.webform.getComponentById(schema.id);
      if (component) {
        this.editComponent(component.component, this.getParentContainer(component));
      }
    }, true);
  }

  // 8888888b.                                                                   888                   d8b
  // 888  "Y88b                                                                  888                   Y8P
  // 888    888                                                                  888
  // 888    888 888d888 .d88b.  88888b. 88888888  .d88b.  88888b.   .d88b.       888  .d88b.   .d88b.  888  .d8888b
  // 888    888 888P"  d88""88b 888 "88b   d88P  d88""88b 888 "88b d8P  Y8b      888 d88""88b d88P"88b 888 d88P"
  // 888    888 888    888  888 888  888  d88P   888  888 888  888 88888888      888 888  888 888  888 888 888
  // 888  .d88P 888    Y88..88P 888 d88P d88P    Y88..88P 888  888 Y8b.          888 Y88..88P Y88b 888 888 Y88b.
  // 8888888P"  888     "Y88P"  88888P" 88888888  "Y88P"  888  888  "Y8888       888  "Y88P"   "Y88888 888  "Y8888P
  //                            888                                                                888
  //                            888                                                           Y8b d88P
  //                            888                                                            "Y88P"

  initDropzoneEvents() {
    if (!this.refs.iframeDropzone) {
      return;
    }
    // This is required per HTML spec in order for the drop event to fire
    this.removeEventListener(this.refs.iframeDropzone, 'dragover');
    this.removeEventListener(this.refs.iframeDropzone, 'drop');
    this.addEventListener(this.refs.iframeDropzone, 'dragover', (e) => {
      e.preventDefault();
      return false;
    });

    this.addEventListener(this.refs.iframeDropzone, 'drop', this.onDropzoneDrop.bind(this));
  }

  updateDragAndDrop() {
    if (!this.pdfLoaded) {
      return;
    }
    this.initDropzoneEvents();
    this.prepSidebarComponentsForDrag();
  }

  prepSidebarComponentsForDrag() {
    if (!this.refs['sidebar-container']) {
      return;
    }
    this.refs['sidebar-container'].forEach(container => {
      [...container.children].forEach(el => {
        el.draggable = true;
        el.setAttribute('draggable', true);
        this.removeEventListener(el, 'dragstart');
        this.removeEventListener(el, 'dragend');
        this.addEventListener(el, 'dragstart', this.onDragStart.bind(this), true);
        this.addEventListener(el, 'dragend', this.onDragEnd.bind(this), true);
        this.addEventListener(el, 'drag', (e) => {
          e.target.style.cursor = 'none';
        });
      });
    });
  }

  updateDropzoneDimensions() {
    if (!this.refs.iframeDropzone) {
      return;
    }

    const iframeRect = getElementRect(this.webform.refs.iframeContainer);
    this.refs.iframeDropzone.style.height = iframeRect && iframeRect.height ? `${iframeRect.height}px` : '1000px';
    this.refs.iframeDropzone.style.width = iframeRect && iframeRect.width ? `${iframeRect.width}px` : '100%';
  }

  onDragStart(e) {
    // Taking the current offset of a dragged item relative to the cursor
    const { offsetX = 0, offsetY = 0 } = e;
    this.itemOffsetX = offsetX;
    this.itemOffsetY = offsetY;

    e.dataTransfer.setData('text', '');
    this.updateDropzoneDimensions();
    this.addClass(this.refs.iframeDropzone, 'enabled');
  }

  onDropzoneDrop(e) {
    this.dropEvent = e;
    e.preventDefault();
    return false;
  }

  onDragEnd(e) {
    // IMPORTANT - must retrieve offsets BEFORE disabling the dropzone - offsets will
    // reflect absolute positioning if accessed after the target element is hidden
    const layerX = this.dropEvent ? this.dropEvent.layerX : null;
    const layerY = this.dropEvent ? this.dropEvent.layerY : null;
    const WIDTH = 100;
    const HEIGHT = 20;
    // Always disable the dropzone on drag end
    this.removeClass(this.refs.iframeDropzone, 'enabled');

    // If there hasn't been a drop event on the dropzone, we're done
    if (!this.dropEvent) {
      return;
    }

    const element = e.target;
    const type = element.getAttribute('data-type');
    const key = element.getAttribute('data-key');
    const group = element.getAttribute('data-group');
    const schema = fastCloneDeep(this.schemas[type]);

    if (key && group) {
      const info = this.getComponentInfo(key, group);
      _.merge(schema, info);
    }

    // Set a unique key for this component.
    BuilderUtils.uniquify([this.webform._form], schema);
    this.webform._form.components.push(schema);

    schema.overlay = {
      top: layerY - this.itemOffsetY + HEIGHT,
      left: layerX - this.itemOffsetX,
      width: WIDTH,
      height: HEIGHT
    };

    this.webform.addComponent(schema, {}, null, true);
    this.webform.postMessage({ name: 'addElement', data: schema });

    this.emit('addComponent', schema, this.webform, schema.key, this.webform.component.components.length, !this.options.noNewEdit && !schema.noNewEdit);

    // Delete the stored drop event now that it's been handled
    this.dropEvent = null;
    e.target.style.cursor = 'default';
  }

  highlightInvalidComponents() {
    const repeatablePaths = this.findRepeatablePaths();

    // update elements which path was duplicated if any pathes have been changed
    if (!_.isEqual(this.repeatablePaths, repeatablePaths)) {
      eachComponent(this.webform.getComponents(), (comp, path) => {
        if (this.repeatablePaths.includes(path)) {
          this.webform.postMessage({ name: 'updateElement', data: comp.component });
        }
      });

      this.repeatablePaths = repeatablePaths;
    }

    if (!repeatablePaths.length) {
      return;
    }

    eachComponent(this.webform.getComponents(), (comp, path) => {
      if (this.repeatablePaths.includes(path)) {
        this.webform.postMessage({
          name: 'showBuilderErrors',
          data: {
            compId: comp.component.id,
            errorMessage: `API Key is not unique: ${comp.key}`,
          }
        });
      }
    });
  }
}

  Generated by ESDoc(1.1.0)


text:
@implementation OrgApacheLuceneAnalysisPayloadsIdentityEncoder

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneAnalysisPayloadsIdentityEncoder_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (instancetype)initWithJavaNioCharsetCharset:(JavaNioCharsetCharset *)charset {
  OrgApacheLuceneAnalysisPayloadsIdentityEncoder_initWithJavaNioCharsetCharset_(self, charset);
  return self;
}

- (OrgApacheLuceneUtilBytesRef *)encodeWithCharArray:(IOSCharArray *)buffer
                                             withInt:(jint)offset
                                             withInt:(jint)length {
  JavaNioByteBuffer *bb = [((JavaNioCharsetCharset *) nil_chk(charset_)) encodeWithJavaNioCharBuffer:JavaNioCharBuffer_wrapWithCharArray_withInt_withInt_(buffer, offset, length)];
  if ([((JavaNioByteBuffer *) nil_chk(bb)) hasArray]) {
    return create_OrgApacheLuceneUtilBytesRef_initWithByteArray_withInt_withInt_([bb array], [bb arrayOffset] + [bb position], [bb remaining]);
  }
  else {
    IOSByteArray *b = [IOSByteArray arrayWithLength:[bb remaining]];
    [bb getWithByteArray:b];
    return create_OrgApacheLuceneUtilBytesRef_initWithByteArray_(b);
  }
}

- (void)dealloc {
  RELEASE_(charset_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, NULL, 0x1, -1, 0, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneUtilBytesRef;", 0x1, 1, 2, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(initWithJavaNioCharsetCharset:);
  methods[2].selector = @selector(encodeWithCharArray:withInt:withInt:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "charset_", "LJavaNioCharsetCharset;", .constantValue.asLong = 0, 0x4, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "LJavaNioCharsetCharset;", "encode", "[CII" };
  static const J2ObjcClassInfo _OrgApacheLuceneAnalysisPayloadsIdentityEncoder = { "IdentityEncoder", "org.apache.lucene.analysis.payloads", ptrTable, methods, fields, 7, 0x1, 3, 1, -1, -1, -1, -1, -1 };
  return &_OrgApacheLuceneAnalysisPayloadsIdentityEncoder;
}

@end

void OrgApacheLuceneAnalysisPayloadsIdentityEncoder_init(OrgApacheLuceneAnalysisPayloadsIdentityEncoder *self) {
  OrgApacheLuceneAnalysisPayloadsAbstractEncoder_init(self);
  JreStrongAssign(&self->charset_, JreLoadStatic(OrgLukhnosPortmobileCharsetStandardCharsets, UTF_8));
}

OrgApacheLuceneAnalysisPayloadsIdentityEncoder *new_OrgApacheLuceneAnalysisPayloadsIdentityEncoder_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneAnalysisPayloadsIdentityEncoder, init)
}

OrgApacheLuceneAnalysisPayloadsIdentityEncoder *create_OrgApacheLuceneAnalysisPayloadsIdentityEncoder_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneAnalysisPayloadsIdentityEncoder, init)
}

void OrgApacheLuceneAnalysisPayloadsIdentityEncoder_initWithJavaNioCharsetCharset_(OrgApacheLuceneAnalysisPayloadsIdentityEncoder *self, JavaNioCharsetCharset *charset) {
  OrgApacheLuceneAnalysisPayloadsAbstractEncoder_init(self);
  JreStrongAssign(&self->charset_, JreLoadStatic(OrgLukhnosPortmobileCharsetStandardCharsets, UTF_8));
  JreStrongAssign(&self->charset_, charset);
}

OrgApacheLuceneAnalysisPayloadsIdentityEncoder *new_OrgApacheLuceneAnalysisPayloadsIdentityEncoder_initWithJavaNioCharsetCharset_(JavaNioCharsetCharset *charset) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneAnalysisPayloadsIdentityEncoder, initWithJavaNioCharsetCharset_, charset)
}

OrgApacheLuceneAnalysisPayloadsIdentityEncoder *create_OrgApacheLuceneAnalysisPayloadsIdentityEncoder_initWithJavaNioCharsetCharset_(JavaNioCharsetCharset *charset) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneAnalysisPayloadsIdentityEncoder, initWithJavaNioCharsetCharset_, charset)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneAnalysisPayloadsIdentityEncoder)


text:
using System;
using JetBrains.Annotations;
using Reinforcement.Core;

namespace Reinforcement
{
  public class RedirectOpenGenericTypeAction : IAction
  {
    private readonly Type _redirectTo;
    private readonly object _token;
    public object AssembleStage { get { return Reinforcement.AssembleStage.Redirect; } }

    public RedirectOpenGenericTypeAction([NotNull] Type redirectTo, [CanBeNull] object token)
    {
      if (redirectTo == null) throw new ArgumentNullException("redirectTo");
      if (!redirectTo.IsGenericTypeDefinition) throw new ArgumentException("Must be open generic type", "redirectTo");
      _redirectTo = redirectTo;
      _token = token;
    }

    public void Execute(Assembler assembler)
    {
      var genericType = _redirectTo.MakeGenericType(assembler.UnitInfo.GetUnitType().GetGenericArguments());
      assembler.AssembleResult = assembler.Assemble(new UnitInfo(genericType, _token));
    }

    public void PostProcess(Assembler assembler)
    {}
  }
}


text:
package org.apache.cassandra.streaming;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;

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

import com.ning.compress.lzf.LZFOutputStream;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.metrics.StreamingMetrics;
import org.apache.cassandra.net.MessageIn;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.Pair;
import org.apache.cassandra.utils.Throttle;
import org.apache.cassandra.utils.WrappedRunnable;

public class FileStreamTask extends WrappedRunnable
{
    private static final Logger logger = LoggerFactory.getLogger(FileStreamTask.class);

    public static final int CHUNK_SIZE = 64 * 1024;
    public static final int MAX_CONNECT_ATTEMPTS = 4;

    protected final StreamHeader header;
    protected final InetAddress to;

    // communication socket
    protected Socket socket;
    // socket's output/input stream
    private OutputStream output;
    private OutputStream compressedoutput;
    private DataInputStream input;
    // allocate buffer to use for transfers only once
    private final byte[] transferBuffer = new byte[CHUNK_SIZE];
    // outbound global throughput limiter
    protected final Throttle throttle;
    private final StreamReplyVerbHandler handler = new StreamReplyVerbHandler();
    protected final StreamingMetrics metrics;

    public FileStreamTask(StreamHeader header, InetAddress to)
    {
        this.header = header;
        this.to = to;
        this.throttle = new Throttle(toString(), new Throttle.ThroughputFunction()
        {
            /** @return Instantaneous throughput target in bytes per millisecond. */
            public int targetThroughput()
            {
                if (DatabaseDescriptor.getStreamThroughputOutboundMegabitsPerSec() < 1)
                    // throttling disabled
                    return 0;
                // total throughput
                int totalBytesPerMS = DatabaseDescriptor.getStreamThroughputOutboundMegabitsPerSec() * 1024 * 1024 / 8 / 1000;
                // per stream throughput (target bytes per MS)
                return totalBytesPerMS / Math.max(1, (int)StreamingMetrics.activeStreamsOutbound.count());
            }
        });
        metrics = StreamingMetrics.get(to);
    }

    public void runMayThrow() throws IOException
    {
        try
        {
            connectAttempt();
            // successfully connected: stream.
            // (at this point, if we fail, it is the receiver's job to re-request)
            stream();

            StreamOutSession session = StreamOutSession.get(header.sessionId);
            if (session == null)
            {
                logger.info("Found no stream out session at end of file stream task - this is expected if the receiver went down");
            }
            else if (session.getFiles().size() == 0)
            {
                // we are the last of our kind, receive the final confirmation before closing
                receiveReply();
                logger.info("Finished streaming session to {}", to);
            }
        }
        catch (IOException e)
        {
            StreamOutSession session = StreamOutSession.get(header.sessionId);
            if (session != null)
                session.close(false);
            throw e;
        }
        finally
        {
            try
            {
                close();
            }
            catch (IOException e)
            {
                if (logger.isDebugEnabled())
                    logger.debug("error closing socket", e);
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Done streaming " + header.file);
    }

    /**
     * Stream file by it's sections specified by this.header
     * @throws IOException on any I/O error
     */
    protected void stream() throws IOException
    {
        ByteBuffer headerBuffer = MessagingService.instance().constructStreamHeader(header, false, MessagingService.instance().getVersion(to));
        // write header (this should not be compressed for compatibility with other messages)
        output.write(ByteBufferUtil.getArray(headerBuffer));

        if (header.file == null)
            return;

        // try to skip kernel page cache if possible
        RandomAccessReader file = RandomAccessReader.open(new File(header.file.getFilename()), true);

        // setting up data compression stream
        compressedoutput = new LZFOutputStream(output);

        StreamingMetrics.activeStreamsOutbound.inc();
        try
        {
            long totalBytesTransferred = 0;
            // stream each of the required sections of the file
            for (Pair<Long, Long> section : header.file.sections)
            {
                // seek to the beginning of the section
                file.seek(section.left);

                // length of the section to stream
                long length = section.right - section.left;
                // tracks write progress
                long bytesTransferred = 0;

                while (bytesTransferred < length)
                {
                    long lastWrite = write(file, length, bytesTransferred);
                    bytesTransferred += lastWrite;
                    totalBytesTransferred += lastWrite;
                    // store streaming progress
                    header.file.progress += lastWrite;
                }

                // make sure that current section is send
                compressedoutput.flush();

                if (logger.isDebugEnabled())
                    logger.debug("Bytes transferred " + bytesTransferred + "/" + header.file.size);
            }
            StreamingMetrics.totalOutgoingBytes.inc(totalBytesTransferred);
            metrics.outgoingBytes.inc(totalBytesTransferred);
            // receive reply confirmation
            receiveReply();
        }
        finally
        {
            StreamingMetrics.activeStreamsOutbound.dec();

            // no matter what happens close file
            FileUtils.closeQuietly(file);
        }
    }

    protected void receiveReply() throws IOException
    {
        MessagingService.validateMagic(input.readInt());
        String id = input.readUTF();
        input.readInt(); // skip timestamp
        // since we reject streaming with different version, using current_version here is fine
        MessageIn message = MessageIn.read(input, MessagingService.current_version, id);
        assert message.verb == MessagingService.Verb.STREAM_REPLY : "Non-reply message received on stream socket";
        handler.doVerb(message, id);
    }

    /**
     * Sequentially read bytes from the file and write them to the output stream
     *
     * @param reader The file reader to read from
     * @param length The full length that should be transferred
     * @param bytesTransferred Number of bytes remaining to transfer
     *
     * @return Number of bytes transferred
     *
     * @throws IOException on any I/O error
     */
    protected long write(RandomAccessReader reader, long length, long bytesTransferred) throws IOException
    {
        int toTransfer = (int) Math.min(CHUNK_SIZE, length - bytesTransferred);

        reader.readFully(transferBuffer, 0, toTransfer);
        compressedoutput.write(transferBuffer, 0, toTransfer);
        throttle.throttleDelta(toTransfer);

        return toTransfer;
    }

    /**
     * Connects to the destination, with backoff for failed attempts.
     * TODO: all nodes on a cluster must currently use the same storage port
     * @throws IOException If all attempts fail.
     */
    private void connectAttempt() throws IOException
    {
        int attempts = 0;
        while (true)
        {
            try
            {
                socket = MessagingService.instance().getConnectionPool(to).newSocket();
                socket.setSoTimeout(DatabaseDescriptor.getStreamingSocketTimeout());
                output = socket.getOutputStream();
                input = new DataInputStream(socket.getInputStream());
                break;
            }
            catch (IOException e)
            {
                if (++attempts >= MAX_CONNECT_ATTEMPTS)
                    throw e;

                long waitms = DatabaseDescriptor.getRpcTimeout() * (long)Math.pow(2, attempts);
                logger.warn("Failed attempt " + attempts + " to connect to " + to + " to stream " + header.file + ". Retrying in " + waitms + " ms. (" + e + ")");
                try
                {
                    Thread.sleep(waitms);
                }
                catch (InterruptedException wtf)
                {
                    throw new RuntimeException(wtf);
                }
            }
        }
    }

    protected void close() throws IOException
    {
        if (output != null)
            output.close();
    }

    public String toString()
    {
        return String.format("FileStreamTask(session=%s, to=%s)", header.sessionId, to);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace FonctionsUtiles.Fred.Csharp
{
  public static class Punctuation
  {
    public const string Comma = ",";
    public const string Colon = ":";
    public const string SemiColon = ";";
    public const string OneSpace = " ";
    public const string UnderScore = "_";
    public const string SignAt = "@";
    public const string Ampersand = "&";
    public const string SignSharp = "#";
    public const string Period = ".";
    public const string Backslash = "\\";
    public const string Slash = "/";
    public const string OpenParenthesis = "(";
    public const string CloseParenthesis = ")";
    public const string OpenCurlyBrace = "{";
    public const string CloseCurlyBrace = "}";
    public const string OpeningBracket = "[";
    public const string ClosingBracket = "]";
    public const string LessThan = "<";
    public const string GreaterThan = ">";
    public const string DoubleQuote = "\"";
    public const string SimpleQuote = "'";
    public const string Tilde = "~";
    public const string Pipe = "|";
    public const string Plus = "+";
    public const string Minus = "-";
    public const string Dash = "-";
    public const string Multiply = "*";
    public const string Divide = "/";
    public const string Equal = "=";
    public const string Dollar = "$";
    public const string Pound = "£";
    public const string Percent = "%";
    public const string QuestionMark = "?";
    public const string ExclamationPoint = "!";
    public const string Chapter = "§";
    public const string Micro = "µ";
    public const string Copyright = "®";
    public static string CrLf = Environment.NewLine;

    public static string Tabulate(ushort numberOfTabulation = 1)
    {
      string result = string.Empty;
      for (int number = 0; number < numberOfTabulation; number++)
      {
        result += " ";
      }

      return result;
    }

    public static string CreateSentence(params string[] listOfCharacters)
    {
      StringBuilder result = new StringBuilder();
      foreach (string character in listOfCharacters)
      {
        result.Append(character);
      }

      return result.ToString();
    }

    public static string CreateSentence(params PunctuationChar[] listOfCharacters)
    {
      StringBuilder result = new StringBuilder();
      foreach (var character in listOfCharacters)
      {
        result.Append(character);
      }

      return result.ToString();
    }

    public enum PunctuationChar
    {
      // values according to ASCII table
      Comma = 44,
      Colon = 58,
      SemiColon = 59,
      OneSpace = 32,
      UnderScore = 95,
      SignAt = 64,
      Ampersand = 38,
      SignSharp = 35,
      SignNumber = Pound,
      Period = 46,
      Backslash = 92,
      OpenParenthesis = 40,
      CloseParenthesis = 41,
      OpenCurlyBrace = 123,
      OpeningBrace = OpenCurlyBrace,
      CloseCurlyBrace = 125,
      ClosingBrace = CloseCurlyBrace,
      OpeningBracket = 91,
      ClosingBracket = 93,
      LessThan = 60,
      GreaterThan = 62,
      DoubleQuote = 34,
      SimpleQuote = 39,
      Tilde = 126,
      Caret = 94,
      Circumflex = Caret,
      Pipe = 124,
      VerticalBar = Pipe,
      Plus = 43,
      Dash = 45,
      Minus = Dash,
      Multiply = 42,
      SignMultiply = 215,
      Slash = 47,
      Divide = Slash,
      SignDivision = 247,
      Equal = 61,
      Dollar = 36,
      Pound = 163,
      SignYen = 165,
      Percent = 37,
      QuestionMark = 63,
      ExclamationPoint = 33,
      Chapter = 167,
      Section = Chapter,
      Copyright = 169,
      Micro = 181,
      LeftDoubleAngleQuotes = 171,
      RightDoubleAngleQuotes = 187,
      LeftSingleQuotationMark = 8216,
      RightSingleQuotationMark = 8217,
      LeftDoubleQuotationMark = 8220,
      RightdoubleQuotationMark = 8221,
      SignTradeMark = 8482,
      SignEuro = 8364,
      CrLf = 0,
      NewLine = CrLf
    }

    public static string GetExclamationPoint() // Andrew Hall style
    {
      return ExclamationPoint;
    }

    public static string FrenchBoolean(bool booleanValue)
    {
      return booleanValue ? "vrai" : "faux";
    }

    public static List<T> GetEnumList<T>()
    {
      T[] array = (T[])Enum.GetValues(typeof(T));
      List<T> list = new List<T>(array);
      return list;
    }
  }
}


text:
import {Mouse, Keyboard, Network, Screen} from '../Global/Global';
// import {UpdateLoop} from '../Loop/UpdateLoop';
import {resizeEvent} from './ResizeEvent.ts';

export class CanvasEvents {
	private static overlordsArray : Array<CanvasEventOverlord> = [];

	public static getLockedCanvas(canvasName: string): CanvasEventOverlord {
		return CanvasEvents.overlordsArray[canvasName];
	}

	public static lockCanvas(canvas: HTMLCanvasElement, canvasName: string): CanvasEventOverlord {
		Mouse.registerListeners(canvas, canvasName);
		Keyboard.registerListeners(canvas, canvasName);
		Screen.registerListeners(canvas, canvasName);

		let overlord = new CanvasEventOverlord(canvas, canvasName);

		CanvasEvents.overlordsArray[canvasName] = overlord;

		return CanvasEvents.overlordsArray[canvasName];
	}
}
// supporting class
export class CanvasEventOverlord {
	private canvas: HTMLCanvasElement;
	private eventArray: Array<Array<Function>>;
	private canvasName: string;

	constructor (canvas: HTMLCanvasElement, canvasName: string) {
		this.canvas = canvas;
		this.canvasName = canvasName;
		this.eventArray = [];
	}

	private updateLoop() {
		// resize handling
		resizeEvent(this, Screen);

		// if(Mouse.getLeftButton().)
	}

	private alocateIfNotExists(eventName: string, context: string, operationName: string) {
		if(typeof this.eventArray === 'undefined') {
			this.eventArray = [];
		}
		if(typeof this.eventArray[eventName] === 'undefined') {
			this.eventArray[eventName] = [];
		}
		if(typeof this.eventArray[eventName][context] === 'undefined') {
			this.eventArray[eventName][context] = [];
		}
		if(typeof this.eventArray[eventName][context][operationName] === 'undefined') {
			this.eventArray[eventName][context][operationName] = (() => {});
		}
	}

	private getEvent({eventName, context} : FireArguments): Array<Function> {
		if(typeof this.eventArray === 'undefined') {
			return [];
		}
		if(typeof this.eventArray[eventName] === 'undefined') {
			return [];
		}
		if(typeof this.eventArray[eventName][context] === 'undefined') {
			return [];
		}
		return this.eventArray[eventName][context];
	}

	private getOperation({eventName, context, operationName}: OperationArguments): Function {
		if(typeof this.eventArray === 'undefined') {
			return (() => {});
		}
		if(typeof this.eventArray[eventName] === 'undefined') {
			return (() => {});
		}
		if(typeof this.eventArray[eventName][context] === 'undefined') {
			return (() => {});
		}
		if(typeof this.eventArray[eventName][context][operationName] === 'undefined') {
			return (() => {});
		}
		return this.eventArray[eventName][context][operationName];
	}

	public registerEvent({eventName, context, callback, operationName = 'default'} : RegisterArguments): CanvasEventOverlord {
		console.log(eventName, context, operationName);

		this.alocateIfNotExists(eventName, context, operationName);
		this.eventArray[eventName][context][operationName] = callback;

		return this;
	}

	public getEventProcessor() {
		return {
			updateLoop: () => { this.updateLoop() }
		}
	}

	public fireEvent({eventName, context} : FireArguments) {
		const operations = this.getEvent({eventName, context});
		for(let operation in operations) {
			operations[operation]();
		}
	}

	public fireOperation({eventName, context, operationName}: OperationArguments) {
		this.getOperation({eventName, context, operationName})();
	}
}

// supporting interfaces
interface PassEventData {
	Mouse: any;
	Keyboard: any;
	// Network: any;
}

interface RegisterArguments {
	eventName: string;
	context: string;
	callback: (eventData : PassEventData) => any;
	operationName?: string;
}

interface FireArguments {
	eventName: string;
	context: string;
}

interface OperationArguments {
	eventName: string;
	context: string;
	operationName: string;
}


text:
package de.ids_mannheim.korap.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.exceptions.StatusCodes;
import de.ids_mannheim.korap.query.serialize.CollectionQueryProcessor;
import de.ids_mannheim.korap.response.Notifications;
import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * convenience builder class for collection query
 *
 * @author hanl, margaretha
 * @date 29/06/2017
 */
public class KoralCollectionQueryBuilder {

    public enum EQ {
        EQUAL, UNEQUAL
    }

    private boolean verbose;
    private JsonNode base;
    private StringBuilder builder;
    private String mergeOperator;

    public KoralCollectionQueryBuilder () {
        this(false);
    }

    public KoralCollectionQueryBuilder (boolean verbose) {
        this.verbose = verbose;
        this.builder = new StringBuilder();
        this.base = null;
        this.mergeOperator = null;
    }

    /**
     * raw method for field - value pair adding. Supports all
     * operators (leq, geq, contains, etc.)
     *
     * @param field
     * @param op
     * @param value
     * @return
     */
    public KoralCollectionQueryBuilder with (String field, String op,
            String value) {
        //String end = this.builder.substring(this.builder.length() - 4,
        //        this.builder.length() - 1);
        //if (this.builder.length() != 0
        //        && (!end.contains("&") | !end.contains("|")))
        //    throw new RuntimeException("no join operator given!");
        this.with(field + op + value);
        return this;
    }

    /**
     * element can be a more complex sub query like
     * (textClass=freizeit & Attributes.CORPUS_SIGLE=WPD)
     *
     * @param query
     *            will be enclosed by parenthesis in order to make sub
     *            query
     *            element
     * @return
     */
    public KoralCollectionQueryBuilder with (String query) {
        if (!query.startsWith("(") && !query.endsWith(")"))
            query = "(" + query + ")";
        this.builder.append(query);
        return this;
    }

    public KoralCollectionQueryBuilder and () {
        if (this.builder.length() != 0) this.builder.append(" & ");
        if (this.base != null && this.mergeOperator == null)
            this.mergeOperator = "AND";
        return this;
    }

    public KoralCollectionQueryBuilder or () {
        if (this.builder.length() != 0) this.builder.append(" | ");
        if (this.base != null && this.mergeOperator == null)
            this.mergeOperator = "OR";
        return this;
    }

    public JsonNode rebaseCollection () throws KustvaktException {
        if (this.builder.length() == 0 && this.base == null) return null;

        JsonNode request = null;
        if (this.builder.length() != 0) {
            CollectionQueryProcessor tree =
                    new CollectionQueryProcessor(this.verbose);
            tree.process(this.builder.toString());
            if (tree.getErrors().size() > 0) {
                // legacy support
                for (List<Object> e : tree.getErrors()) {
                    if (e.get(1) instanceof String[]) {
                        Notifications notif = new Notifications();
                        int code = (int) e.get(0);
                        notif.addError(code, (String[]) e.get(1));
                        String notificationStr = notif.toJsonString();
                        throw new KustvaktException(StatusCodes.SERIALIZATION_FAILED,
                                notificationStr, true);
                    }
                    else{
                        break;
                    }
                }
                // -- end of legacy support

                Map<String, Object> map = new HashMap<>();
                map.put("errors", tree.getErrors());
                String errors = JsonUtils.toJSON(map);
                throw new KustvaktException(StatusCodes.SERIALIZATION_FAILED,
                        errors, true);
            }
            request = JsonUtils.valueToTree(tree.getRequestMap());
        }

        if (this.base != null) {
            // check that collection non empty
            JsonNode tmp = this.base.deepCopy();
            if (request != null)
                request = mergeWith(request);
            else
                request = tmp;
        }
        return request;
    }

    public JsonNode mergeWith (JsonNode node) {
        if (this.base != null) {
            if (node != null) {
                JsonNode tobase = node.at("/collection");
                JsonNode base = this.base.deepCopy();
                JsonNode result = base.at("/collection");

                if (result.isMissingNode() && !tobase.isMissingNode())
                    result = tobase;
                else if (result.isMissingNode() && tobase.isMissingNode())
                    return base;
                else {
                    result = JsonBuilder.buildDocGroup(
                            this.mergeOperator != null
                                    ? this.mergeOperator.toLowerCase() : "and",
                            result, tobase);
                }
                ((ObjectNode) base).put("collection", result);
                return base;
            }
            return this.base;
        }
        throw new RuntimeException("no query found to merge with!");
    }

    /**
     * sets base query. All consequent queries are added to the first
     * koral:docGroup within the collection base query
     * If no group in base query, consequent queries are skipped.
     *
     * @param query
     * @throws KustvaktException
     */
    public KoralCollectionQueryBuilder setBaseQuery (String query) throws KustvaktException {
        this.base = JsonUtils.readTree(query);
        return this;
    }

    public KoralCollectionQueryBuilder setBaseQuery (JsonNode query) {
        this.base = query;
        return this;
    }

    public String toJSON () throws KustvaktException {
        return JsonUtils.toJSON(rebaseCollection());
    }

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

    private static class JsonBuilder {

        public static ObjectNode buildDoc (String key, String value) {
            ObjectNode node = JsonUtils.createObjectNode();
            node.put("@type", "koral:doc");
            // eq.equals(EQ.EQUAL) ? "match:eq" : "match:ne"
            node.put("match", "match:eq");
            node.put("key", key);
            node.put("value", value);
            return node;
        }

        public static ObjectNode buildDocGroup (String op,
                JsonNode ... groups) {
            ObjectNode node = JsonUtils.createObjectNode();
            node.put("@type", "koral:docGroup");
            node.put("operation", "operation:" + op);
            ArrayNode ops = JsonUtils.createArrayNode();
            ops.addAll(Arrays.asList(groups));
            node.put("operands", ops);
            return node;
        }

    }

}


text:
layout: default
---

{{ site.title }}

      {% if site.subtitle %}
{{ site.subtitle }}
{% endif %}


text:
import { Farmbot } from "farmbot";
import { t } from "i18next";
import axios from "axios";
import * as _ from "lodash";
import { success, warning, info, error } from "farmbot-toastr";
import { devices } from "../device";
import { Log } from "../interfaces";
import { GithubRelease, MoveRelProps } from "./interfaces";
import { Thunk, GetState } from "../redux/interfaces";
import { DeviceAccountSettings, BotState } from "../devices/interfaces";
import {
  McuParams,
  Configuration,
  BotStateTree,
  ALLOWED_CHANNEL_NAMES,
  ALLOWED_MESSAGE_TYPES,
  SyncStatus
} from "farmbot";
import { Sequence } from "../sequences/interfaces";
import { HardwareState, ControlPanelState } from "../devices/interfaces";
import { API } from "../api/index";
import { User } from "../auth/interfaces";
import { init, edit } from "../api/crud";
import { getDeviceAccountSettings } from "../resources/selectors";
import { TaggedDevice } from "../resources/tagged_resources";
import { versionOK } from "./reducer";
import { oneOf, HttpData } from "../util";
import { Actions } from "../constants";

const ON = 1, OFF = 0;
type configKey = keyof McuParams;
export const EXPECTED_MAJOR = 5;
export const EXPECTED_MINOR = 0;

function incomingStatus(statusMessage: HardwareState) {
  return { type: "BOT_CHANGE", payload: statusMessage };
}

export function isLog(x: object): x is Log {
  return _.isObject(x) && _.isString(_.get(x, "message" as keyof Log));
}
let commandErr = (noun = "Command") => (x: any) => {
  console.dir(x);
  console.info("Took longer than 6 seconds: " + noun);
};

let commandOK = (noun = "Command") => () => {
  let msg = noun + " request sent to device.";
  success(msg, t("Request sent"));
};

export function checkControllerUpdates() {
  let noun = "Check for Updates";
  devices
    .current
    .checkUpdates()
    .then(commandOK(noun), commandErr(noun));
}

export function powerOff() {
  let noun = "Power Off Bot";
  devices
    .current
    .powerOff()
    .then(commandOK(noun), commandErr(noun));
}

export function factoryReset() {
  if (!confirm(`WAIT! This will erase EVERYTHING stored on your device SD card.
  Are you sure?`)) {
    return;
  }
  devices
    .current
    .resetOS();
}

export function reboot() {
  let noun = "Reboot Bot";
  devices
    .current
    .reboot()
    .then(commandOK(noun), commandErr(noun));
}

export function emergencyLock() {
  let noun = "Emergency stop";
  devices
    .current
    .emergencyLock()
    .then(commandOK(noun), commandErr(noun));
}

export function emergencyUnlock() {
  let noun = "Emergency unlock";
  if (confirm(`Are you sure you want to unlock the device?`)) {
    devices
      .current
      .emergencyUnlock()
      .then(commandOK(noun), commandErr(noun));
  }
}

export function sync(): Thunk {
  let noun = "Sync";
  return function (dispatch, getState) {
    let IS_OK = versionOK(getState()
      .bot
      .hardware
      .informational_settings
      .controller_version, EXPECTED_MAJOR, EXPECTED_MINOR);
    if (IS_OK) {
      dispatch(setSyncStatus("syncing"));
      devices
        .current
        .sync()
        .then(() => {
          commandOK(noun);
          dispatch(setSyncStatus("synced"));
        }).catch(() => {
          commandErr(noun);
          dispatch(setSyncStatus("sync_error"));
        });
    } else {
      if (getState()
        .bot
        .hardware
        .informational_settings
        .controller_version) {
        badVersion();
      } else {
        info("FarmBot is not connected.", "Disconnected", "red");
      }
    }
  };
}

export function execSequence(sequence: Sequence) {
  const noun = "Sequence execution";
  if (sequence.id) {
    return devices
      .current
      .execSequence(sequence.id)
      .then(commandOK(noun), commandErr(noun));
  } else {
    throw new Error("Can't execute unsaved sequences");
  }
}

export let saveAccountChanges: Thunk = function (dispatch, getState) {
  return save(getDeviceAccountSettings(getState().resources.index));
};

export let fetchReleases =
  (url: string) => (dispatch: Function, getState: Function) => {
    axios
      .get(url)
      .then((resp: HttpData<GithubRelease>) => {
        let version = resp.data.tag_name;
        let versionWithoutV = version.toLowerCase().replace("v", "");
        dispatch({
          type: "FETCH_OS_UPDATE_INFO_OK",
          payload: versionWithoutV
        });
      })
      .catch((ferror) => {
        error(t("Could not download firmware update information."));
        dispatch({
          type: "FETCH_OS_UPDATE_INFO_ERROR",
          payload: ferror
        });
      });
  };

export function save(input: TaggedDevice) {
  return function (dispatch: Function, getState: GetState) {
    return axios
      .put(API.current.devicePath, input.body)
      .then((resp: HttpData<User>) => dispatch({ type: "SAVE_DEVICE_OK", payload: resp.data }))
      .catch(resp => error("Error saving device settings."));
  };
}

/**
 * Toggles visibility of individual sections in the giant controls panel
 * found on the Devices page.
 */
export function toggleControlPanel(payload: keyof ControlPanelState) {
  return { type: "TOGGLE_CONTROL_PANEL_OPTION", payload };
}

export function changeDevice(device: TaggedDevice,
  update: Partial<DeviceAccountSettings>): Thunk {
  return function (dispatch, getState) {
    dispatch(edit(device, update));
    dispatch(save(getDeviceAccountSettings(getState().resources.index)));
  };
}

export function MCUFactoryReset() {
  return devices.current.resetMCU();
}

export function botConfigChange(key: configKey, value: number) {
  let noun = "Setting toggle";

  return devices
    .current
    .updateMcu({ [key]: value })
    .then(_.noop, commandErr(noun));
}

export function settingToggle(
  name: configKey, bot: BotState, displayAlert: string | undefined
) {
  if (displayAlert) { alert(displayAlert.replace(/\s+/g, " ")); }
  let noun = "Setting toggle";
  return devices
    .current
    .updateMcu({
      [name]: ((bot.hardware.mcu_params)[name] === 0) ? ON : OFF
    })
    .then(_.noop, commandErr(noun));
}

export function moveRelative(props: MoveRelProps) {
  return devices
    .current
    .moveRelative(props)
    .then(_.noop, commandErr("Relative movement"));
}

export function moveAbs(props: MoveRelProps) {
  const noun = "Absolute movement";
  return devices
    .current
    .moveAbsolute(props)
    .then(_.noop, commandErr(noun));
}

export function pinToggle(pin_number: number) {
  const noun = "Setting toggle";
  return devices
    .current
    .togglePin({ pin_number })
    .then(_.noop, commandErr(noun));
}

export function homeAll(speed: number) {
  let noun = "'Home All' command";
  devices
    .current
    .home({ axis: "all", speed })
    .then(commandOK(noun), commandErr(noun));
}

function readStatus() {
  let noun = "'Read Status' command";
  return devices
    .current
    .readStatus()
    .then(() => { commandOK(noun); }, () => { });
}

let NEED_VERSION_CHECK = true;
// Already filtering messages in FarmBot OS and the API- this is just for
// an additional layer of safety. If sensitive data ever hits a client, it will
// be reported to ROllbar for investigation.
type ConnectDeviceReturn = {} | ((dispatch: Function) => void);
const BAD_WORDS = ["WPA", "PSK", "PASSWORD", "NERVES"];
export function connectDevice(token: string): ConnectDeviceReturn {
  return (dispatch: Function, getState: GetState) => {
    let secure = location.protocol === "https:";
    let bot = new Farmbot({ token, secure });
    bot.on("online", () => dispatch(setMqttStatus(true)));
    bot.on("offline", () => dispatch(setMqttStatus(false)));
    return bot
      .connect()
      .then(() => {
        devices.online = true;
        devices.current = bot;
        _.set(window, "current_bot", bot);
        readStatus()
          .then(() => bot.setUserEnv(
            { "LAST_CLIENT_CONNECTED": JSON.stringify(new Date()) }
          ))
          .catch(() => { });
        bot.on("logs", function (msg: Log) {
          if (isLog(msg) && !oneOf(BAD_WORDS, msg.message.toUpperCase())) {
            maybeShowLog(msg);
            dispatch(init({
              kind: "logs",
              specialStatus: undefined,
              uuid: "MUST_CHANGE",
              body: msg
            }));
          } else {
            throw new Error("Refusing to display log: " + JSON.stringify(msg));
          }
        });
        bot.on("status", _.throttle(function (msg: BotStateTree) {
          dispatch(incomingStatus(msg));
          if (NEED_VERSION_CHECK) {
            let IS_OK = versionOK(getState()
              .bot
              .hardware
              .informational_settings
              .controller_version, EXPECTED_MAJOR, EXPECTED_MINOR);
            if (!IS_OK) { badVersion(); }
            NEED_VERSION_CHECK = false;
          }

        }, 500));

        let alreadyToldYou = false;
        bot.on("malformed", function () {
          if (!alreadyToldYou) {
            warning(t(`FarmBot sent a malformed message. You may need to upgrade
            FarmBot OS. Please upgrade FarmBot OS and log back in.`));
            alreadyToldYou = true;
          }
        });
      }, (err) => dispatch(fetchDeviceErr(err)));
  };
}

function fetchDeviceErr(err: Error) {
  return {
    type: "FETCH_DEVICE_ERR",
    payload: err
  };
}

let startUpdate = (dispatch: Function) => {
  dispatch({ type: "SETTING_UPDATE_START", payload: undefined });
};

let updateOK = (dispatch: Function, noun: string) => {
  dispatch({ type: "SETTING_UPDATE_END", payload: undefined });
  commandOK(noun);
};

let updateNO = (dispatch: Function, noun: string) => {
  dispatch({ type: "SETTING_UPDATE_END", payload: undefined });
  commandErr(noun);
};

export function updateMCU(key: configKey, val: string) {
  let noun = "configuration update";
  return function (dispatch: Function) {
    startUpdate(dispatch);
    devices
      .current
      .updateMcu({ [key]: val })
      .then(() => updateOK(dispatch, noun))
      .catch(() => updateNO(dispatch, noun));
  };
}

export function updateConfig(config: Configuration) {
  let noun = "Update Config";
  return function (dispatch: Function) {
    devices
      .current
      .updateConfig(config)
      .then(() => updateOK(dispatch, noun))
      .catch(() => updateNO(dispatch, noun));
  };
}

export function changeStepSize(integer: number) {
  return {
    type: "CHANGE_STEP_SIZE",
    payload: integer
  };
}

const CHANNELS: keyof Log = "channels";
const TOAST: ALLOWED_CHANNEL_NAMES = "toast";

function maybeShowLog(log: Log) {
  let chanList = _.get(log, CHANNELS, ["ERROR FETCHING CHANNELS"]);
  let m = log.meta.type as ALLOWED_MESSAGE_TYPES;
  const TITLE = "New message from bot";
  if (chanList.includes(TOAST)) {
    switch (m) {
      case "success":
        return success(log.message, TITLE);
      case "busy":
      case "warn":
      case "error":
        return error(log.message, TITLE);
      case "fun":
      case "info":
      default:
        return info(log.message, TITLE);
    }
  }
}

export function setSyncStatus(payload: SyncStatus) {
  return { type: "SET_SYNC_STATUS", payload };
}

function badVersion() {
  info("You are running an old version of FarmBot OS.", "Please Update", "red");
}

export let setMqttStatus = (payload: boolean) => ({
  type: Actions.SET_MQTT_STATUS, payload
});


text:
/* -------------------------------------------------------------------------
@file factorial.c

@date 04/09/16 13:48:29
@author Martin Noblia
@email martin.noblia@openmailbox.org

@brief
Implementation of factorial using recursive approach
@detail

Licence:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
---------------------------------------------------------------------------*/

#include<stdio.h>
int fact(int n)
{
    // Compute the factorial of n recusively
    if(n < 0)
        return 0;
    else if(n == 0)
        return 1;
    else if(n == 1)
        return 1;
    else
        return n * fact(n - 1);
}

int main()
{
    int n      = 7;
    int result = 0;

    result = fact(n);
    printf("The factorial of: %d = %d\n", n, result);

    return 0;
}


text:
<?php

namespace Application\Admin;

class Module extends \ManaPHP\Mvc\Module
{
    public function registerServices($di)
    {
    }

    public function authorize($controller, $action)
    {
        return true;
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import math
import os
import time
from datetime import datetime

import tensorflow as tf

import yarntf

IMAGE_PIXELS = 28

def print_log(worker_num, arg):
    print("%d: " % worker_num, end=" ")
    print(arg)

def hdfs_path(relative_path):
    return os.environ["HOME_DIRECTORY"] + "/" + relative_path

def main(args):
    job_name = os.environ["JOB_NAME"]
    task_index = int(os.environ["TASK_INDEX"])
    num_workers = int(os.environ["WORKERS"])
    num_pses = int(os.environ["PSES"])
    if job_name == "worker":
        worker_num = task_index + num_pses
    else:
        worker_num = task_index

    # Delay PS nodes a bit, since workers seem to reserve GPUs more quickly/reliably (w/o conflict)
    if job_name == "ps":
        time.sleep((worker_num + 1) * 5)

    # Parameters
    hidden_units = 128
    batch_size = 100

    # Get TF cluster and server instances
    cluster, server = yarntf.createClusterServer()

    def read_csv_examples(image_dir, label_dir, batch_size=100, num_epochs=None, task_index=None, num_workers=None):
        print_log(worker_num, "num_epochs: {0}".format(num_epochs))
        # Setup queue of csv image filenames
        tf_record_pattern = os.path.join(image_dir, 'part-*')
        images = tf.gfile.Glob(tf_record_pattern)
        print_log(worker_num, "images: {0}".format(images))
        image_queue = tf.train.string_input_producer(images, shuffle=False, capacity=1000, num_epochs=num_epochs,
                                                     name="image_queue")

        # Setup queue of csv label filenames
        tf_record_pattern = os.path.join(label_dir, 'part-*')
        labels = tf.gfile.Glob(tf_record_pattern)
        print_log(worker_num, "labels: {0}".format(labels))
        label_queue = tf.train.string_input_producer(labels, shuffle=False, capacity=1000, num_epochs=num_epochs,
                                                     name="label_queue")

        # Setup reader for image queue
        img_reader = tf.TextLineReader(name="img_reader")
        _, img_csv = img_reader.read(image_queue)
        image_defaults = [[1.0] for col in range(784)]
        img = tf.pack(tf.decode_csv(img_csv, image_defaults))
        # Normalize values to [0,1]
        norm = tf.constant(255, dtype=tf.float32, shape=(784,))
        image = tf.div(img, norm)
        print_log(worker_num, "image: {0}".format(image))

        # Setup reader for label queue
        label_reader = tf.TextLineReader(name="label_reader")
        _, label_csv = label_reader.read(label_queue)
        label_defaults = [[1.0] for col in range(10)]
        label = tf.pack(tf.decode_csv(label_csv, label_defaults))
        print_log(worker_num, "label: {0}".format(label))

        # Return a batch of examples
        return tf.train.batch([image, label], batch_size, num_threads=args.readers, name="batch_csv")

    def read_tfr_examples(path, batch_size=100, num_epochs=None, task_index=None, num_workers=None):
        print_log(worker_num, "num_epochs: {0}".format(num_epochs))

        # Setup queue of TFRecord filenames
        tf_record_pattern = os.path.join(path, 'part-*')
        files = tf.gfile.Glob(tf_record_pattern)
        queue_name = "file_queue"

        # split input files across workers, if specified
        if task_index is not None and num_workers is not None:
            num_files = len(files)
            files = files[task_index:num_files:num_workers]
            queue_name = "file_queue_{0}".format(task_index)

        print_log(worker_num, "files: {0}".format(files))
        file_queue = tf.train.string_input_producer(files, shuffle=False, capacity=1000, num_epochs=num_epochs,
                                                    name=queue_name)

        # Setup reader for examples
        reader = tf.TFRecordReader(name="reader")
        _, serialized = reader.read(file_queue)
        feature_def = {'label': tf.FixedLenFeature([10], tf.int64), 'image': tf.FixedLenFeature([784], tf.int64)}
        features = tf.parse_single_example(serialized, feature_def)
        norm = tf.constant(255, dtype=tf.float32, shape=(784,))
        image = tf.div(tf.to_float(features['image']), norm)
        print_log(worker_num, "image: {0}".format(image))
        label = tf.to_float(features['label'])
        print_log(worker_num, "label: {0}".format(label))

        # Return a batch of examples
        return tf.train.batch([image, label], batch_size, num_threads=args.readers, name="batch")

    if job_name == "ps":
        server.join()
    elif job_name == "worker":
        # Assigns ops to the local worker by default.
        with tf.device(tf.train.replica_device_setter(
                worker_device="/job:worker/task:%d" % task_index,
                cluster=cluster)):

            # Variables of the hidden layer
            hid_w = tf.Variable(tf.truncated_normal([IMAGE_PIXELS * IMAGE_PIXELS, hidden_units],
                                                    stddev=1.0 / IMAGE_PIXELS), name="hid_w")
            hid_b = tf.Variable(tf.zeros([hidden_units]), name="hid_b")

            # Variables of the softmax layer
            sm_w = tf.Variable(tf.truncated_normal([hidden_units, 10],
                                                   stddev=1.0 / math.sqrt(hidden_units)), name="sm_w")
            sm_b = tf.Variable(tf.zeros([10]), name="sm_b")

            # Placeholders or QueueRunner/Readers for input data
            num_epochs = 1 if args.mode == "inference" else None if args.epochs == 0 else args.epochs
            index = task_index if args.mode == "inference" else None
            workers = num_workers if args.mode == "inference" else None

            if args.format == "csv":
                images = hdfs_path(args.images)
                labels = hdfs_path(args.labels)
                x, y_ = read_csv_examples(images, labels, 100, num_epochs, index, workers)
            elif args.format == "tfr":
                images = hdfs_path(args.images)
                x, y_ = read_tfr_examples(images, 100, num_epochs, index, workers)
            else:
                raise ("{0} format not supported for tf input mode".format(args.format))

            hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)
            hid = tf.nn.relu(hid_lin)

            y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))

            global_step = tf.Variable(0)

            loss = -tf.reduce_sum(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))
            train_op = tf.train.AdagradOptimizer(0.01).minimize(
                loss, global_step=global_step)

            # Test trained model
            label = tf.argmax(y_, 1, name="label")
            prediction = tf.argmax(y, 1, name="prediction")
            correct_prediction = tf.equal(prediction, label)
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name="accuracy")

            saver = tf.train.Saver()
            summary_op = tf.summary.merge_all()
            init_op = tf.global_variables_initializer()

        # Create a "supervisor", which oversees the training process and stores model state into HDFS
        logdir = hdfs_path(args.model)
        print("tensorflow model path: {0}".format(logdir))
        summary_writer = tf.summary.FileWriter("tensorboard_%d" % (worker_num), graph=tf.get_default_graph())

        if args.mode == "train":
            sv = tf.train.Supervisor(is_chief=(task_index == 0),
                                     logdir=logdir,
                                     init_op=init_op,
                                     summary_op=summary_op,
                                     saver=saver,
                                     global_step=global_step,
                                     summary_writer=summary_writer,
                                     stop_grace_secs=300,
                                     save_model_secs=10)
        else:
            sv = tf.train.Supervisor(is_chief=(task_index == 0),
                                     logdir=logdir,
                                     saver=saver,
                                     global_step=global_step,
                                     stop_grace_secs=300,
                                     save_model_secs=0)
            output_dir = hdfs_path(args.output)
            output_file = tf.gfile.Open("{0}/part-{1:05d}".format(output_dir, worker_num), mode='w')

        # The supervisor takes care of session initialization, restoring from
        # a checkpoint, and closing when done or an error occurs.
        with sv.managed_session(server.target) as sess:
            print("{0} session ready".format(datetime.now().isoformat()))

            # Loop until the supervisor shuts down or 1000000 steps have completed.
            step = 0
            count = 0
            while not sv.should_stop() and step < args.steps:
                # Run a training step asynchronously.
                # See `tf.train.SyncReplicasOptimizer` for additional details on how to
                # perform *synchronous* training.

                # using QueueRunners/Readers
                if args.mode == "train":
                    if (step % 100 == 0):
                        print(
                            "{0} step: {1} accuracy: {2}".format(datetime.now().isoformat(), step, sess.run(accuracy)))
                    _, summary, step = sess.run([train_op, summary_op, global_step])
                    summary_writer.add_summary(summary, step)
                else:  # args.mode == "inference"
                    labels, pred, acc = sess.run([label, prediction, accuracy])
                    # print("label: {0}, pred: {1}".format(labels, pred))
                    print("acc: {0}".format(acc))
                    for i in range(len(labels)):
                        count += 1
                        output_file.write("{0} {1}\n".format(labels[i], pred[i]))
                    print("count: {0}".format(count))

        if args.mode == "inference":
            output_file.close()
            # Delay chief worker from shutting down supervisor during inference, since it can load model, start session,
            # run inference and request stop before the other workers even start/sync their sessions.
            if task_index == 0:
                time.sleep(60)

        # Ask for all the services to stop.
        print("{0} stopping supervisor".format(datetime.now().isoformat()))
        sv.stop()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--epochs", help="number of epochs", type=int, default=0)
    parser.add_argument("-f", "--format", help="example format: (csv|pickle|tfr)", choices=["csv", "pickle", "tfr"],
                        default="tfr")
    parser.add_argument("-i", "--images", help="HDFS path to MNIST images in parallelized format")
    parser.add_argument("-l", "--labels", help="HDFS path to MNIST labels in parallelized format")
    parser.add_argument("-m", "--model", help="HDFS path to save/load model during train/test", default="mnist_model")
    parser.add_argument("-o", "--output", help="HDFS path to save test/inference output", default="predictions")
    parser.add_argument("-r", "--readers", help="number of reader/enqueue threads", type=int, default=1)
    parser.add_argument("-s", "--steps", help="maximum number of steps", type=int, default=1000)
    parser.add_argument("-X", "--mode", help="train|inference", default="train")
    args = parser.parse_args()
    print("args:", args)

    print("{0} ===== Start".format(datetime.now().isoformat()))
    main(args)
    print("{0} ===== Stop".format(datetime.now().isoformat()))


text:
using UnityEngine;
using UnityEditor;

[CanEditMultipleObjects, CustomEditor(typeof(MegaPush))]
public class MegaPushEditor : MegaModifierEditor
{
	public override string GetHelpString() { return "Push Modifier by Chris West"; }
	public override Texture LoadImage() { return (Texture)EditorGUIUtility.LoadRequired("MegaFiers\\push_help.png"); }

	public override bool Inspector()
	{
		MegaPush mod = (MegaPush)target;

#if !UNITY_5 && !UNITY_2017
		EditorGUIUtility.LookLikeControls();
#endif
		mod.amount = EditorGUILayout.FloatField("Amount", mod.amount);
		mod.method = (MegaNormType)EditorGUILayout.EnumPopup("Method", mod.method);
		return false;
	}
}


text:
description: Autodestroy
keywords: Autodestroy, service, terminate, container
redirect_from:
- /docker-cloud/feature-reference/auto-destroy/
title: Destroy containers automatically
---

When enabled on a service, **Autodestroy** automatically terminates containers
when they stop. **This destroys all data in the container on stop.** This is
useful for one-time actions that store their results in an external system.

The following Autodestroy options are available:

- `OFF`: the container remains in the **Stopped** state regardless of exit code, and is not destroyed.
- `ON_SUCCESS`: if the container stops with an exit code of 0 (normal shutdown), Docker Cloud automatically destroys it. If it stops with any other exit code, Docker Cloud leaves it in the **Stopped** state.
- `ALWAYS`: if the container stops, Docker Cloud automatically terminates it regardless of the exit code.

If **Autorestart** is activated, Docker Cloud evaluates whether to try restarting the container or not before evaluating **Autodestroy**.

## Launch a service with Autodestroy

You can enable **Autodestroy** on the **Service configuration** step of the **Launch new service** wizard.

![](images/autodestroy.png)

Autodestroy is set to `OFF` (deactivated) by default.

### Use the API or CLI

You can enable autodestroy when launching a service through the API or CLI.

If not provided, it has a default value of `OFF`. Check our [API documentation](/apidocs/docker-cloud.md) for more information.

#### Launch with autodestroy using the API
```
POST /api/app/v1/service/ HTTP/1.1
{
	 "autodestroy": "ALWAYS",
	 [...]
}
```

#### Launch with autodestroy using the CLI
```
$ docker-cloud service run --autodestroy ALWAYS [...]
```

## Enable autodestroy on an already deployed service

You can also activate or deactivate the **Autodestroy** setting on a service
after it has been deployed, by editing the service.

1. Go to the service detail page.
2. Click **Edit**.
3. Select the new autodestroy setting.
4. Click **Save**.

### Use the API or CLI

You can set the **Autodestroy** option after the service has been
deployed, using the API or CLI.

Check our [API documentation](/apidocs/docker-cloud.md) for more information.

#### Enable autodestroy using the API
```
PATCH /api/app/v1/service/(uuid)/ HTTP/1.1
{
	"autodestroy": "ALWAYS"
}
```

#### Enable autodestroy using the CLI
```
$ docker-cloud service set --autodestroy ALWAYS (name or uuid)
```


text:
<resources>

    <string name="app_name">Reindex Gallery</string>
</resources>


text:
#ifndef __ASM_SH_PGTABLE_H
#define __ASM_SH_PGTABLE_H

#ifdef CONFIG_X2TLB
#include <asm/pgtable-3level.h>
#else
#include <asm/pgtable-2level.h>
#endif
#include <asm/page.h>
#include <asm/mmu.h>

#ifndef __ASSEMBLY__
#include <asm/addrspace.h>
#include <asm/fixmap.h>

/*
 * ZERO_PAGE is a global shared page that is always zero: used
 * for zero-mapped memory areas etc..
 */
extern unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)];
#define ZERO_PAGE(vaddr) (virt_to_page(empty_zero_page))

#endif /* !__ASSEMBLY__ */

/*
 * Effective and physical address definitions, to aid with sign
 * extension.
 */
#define NEFF		32
#define	NEFF_SIGN	(1LL << (NEFF - 1))
#define	NEFF_MASK	(-1LL << NEFF)

static inline unsigned long long neff_sign_extend(unsigned long val)
{
	unsigned long long extended = val;
	return (extended & NEFF_SIGN) ? (extended | NEFF_MASK) : extended;
}

#ifdef CONFIG_29BIT
#define NPHYS		29
#else
#define NPHYS		32
#endif

#define	NPHYS_SIGN	(1LL << (NPHYS - 1))
#define	NPHYS_MASK	(-1LL << NPHYS)

#define PGDIR_SIZE	(1UL << PGDIR_SHIFT)
#define PGDIR_MASK	(~(PGDIR_SIZE-1))

/* Entries per level */
#define PTRS_PER_PTE	(PAGE_SIZE / (1 << PTE_MAGNITUDE))

#define FIRST_USER_ADDRESS	0

#define PHYS_ADDR_MASK29		0x1fffffff
#define PHYS_ADDR_MASK32		0xffffffff

static inline unsigned long phys_addr_mask(void)
{
	/* Is the MMU in 29bit mode? */
	if (__in_29bit_mode())
		return PHYS_ADDR_MASK29;

	return PHYS_ADDR_MASK32;
}

#define PTE_PHYS_MASK		(phys_addr_mask() & PAGE_MASK)
#define PTE_FLAGS_MASK		(~(PTE_PHYS_MASK) << PAGE_SHIFT)

#ifdef CONFIG_SUPERH32
#define VMALLOC_START	(P3SEG)
#else
#define VMALLOC_START	(0xf0000000)
#endif
#define VMALLOC_END	(FIXADDR_START-2*PAGE_SIZE)

#if defined(CONFIG_SUPERH32)
#include <asm/pgtable_32.h>
#else
#include <asm/pgtable_64.h>
#endif

/*
 * SH-X and lower (legacy) SuperH parts (SH-3, SH-4, some SH-4A) can't do page
 * protection for execute, and considers it the same as a read. Also, write
 * permission implies read permission. This is the closest we can get..
 *
 * SH-X2 (SH7785) and later parts take this to the opposite end of the extreme,
 * not only supporting separate execute, read, and write bits, but having
 * completely separate permission bits for user and kernel space.
 */
	 /*xwr*/
#define __P000	PAGE_NONE
#define __P001	PAGE_READONLY
#define __P010	PAGE_COPY
#define __P011	PAGE_COPY
#define __P100	PAGE_EXECREAD
#define __P101	PAGE_EXECREAD
#define __P110	PAGE_COPY
#define __P111	PAGE_COPY

#define __S000	PAGE_NONE
#define __S001	PAGE_READONLY
#define __S010	PAGE_WRITEONLY
#define __S011	PAGE_SHARED
#define __S100	PAGE_EXECREAD
#define __S101	PAGE_EXECREAD
#define __S110	PAGE_RWX
#define __S111	PAGE_RWX

typedef pte_t *pte_addr_t;

#define kern_addr_valid(addr)	(1)

#define io_remap_pfn_range(vma, vaddr, pfn, size, prot)		\
		remap_pfn_range(vma, vaddr, pfn, size, prot)

#define pte_pfn(x)		((unsigned long)(((x).pte_low >> PAGE_SHIFT)))

/*
 * Initialise the page table caches
 */
extern void pgtable_cache_init(void);

struct vm_area_struct;
struct mm_struct;

extern void __update_cache(struct vm_area_struct *vma,
			   unsigned long address, pte_t pte);
extern void __update_tlb(struct vm_area_struct *vma,
			 unsigned long address, pte_t pte);

static inline void
update_mmu_cache(struct vm_area_struct *vma, unsigned long address, pte_t *ptep)
{
	pte_t pte = *ptep;
	__update_cache(vma, address, pte);
	__update_tlb(vma, address, pte);
}

extern pgd_t swapper_pg_dir[PTRS_PER_PGD];
extern void paging_init(void);
extern void page_table_range_init(unsigned long start, unsigned long end,
				  pgd_t *pgd);

/* arch/sh/mm/mmap.c */
#define HAVE_ARCH_UNMAPPED_AREA
#define HAVE_ARCH_UNMAPPED_AREA_TOPDOWN

#define __HAVE_ARCH_PTE_SPECIAL

#include <asm-generic/pgtable.h>

#endif /* __ASM_SH_PGTABLE_H */


text:
<?php
namespace Concrete\Core\StyleCustomizer;

class Set
{
    protected $name;
    protected $elements = array();

    public function setName($name)
    {
        $this->name = $name;
    }

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

    /** Returns the display name for this style set (localized and escaped accordingly to $format)
     * @param string $format = 'html'
     *   Escape the result in html format (if $format is 'html').
     *   If $format is 'text' or any other value, the display name won't be escaped.
     *
     * @return string
     */
    public function getDisplayName($format = 'html')
    {
        $value = tc('StyleSetName', $this->getName());
        switch ($format) {
            case 'html':
                return h($value);
            case 'text':
            default:
                return $value;
        }
    }

    public function addStyle(\Concrete\Core\StyleCustomizer\Style\Style $style)
    {
        $this->styles[] = $style;
    }

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


text:
using UnityEngine;
using System.Collections;
using System;
using UniRx;
using UniRx.Triggers;

namespace SlidingPoint.Players
{
    public class PlayerInput : MonoBehaviour, IPlayerInput
    {
        private Subject<bool> _accelButtonSubject = new Subject<bool>();

        private Subject<bool> _slidingButtonSubject = new Subject<bool>();

        public IObservable<bool> AccelButtonObservable
        {
            get
            {
                return _accelButtonSubject.AsObservable();
            }
        }

        public IObservable<bool> SlidingButtonObservable
        {
            get
            {
                return _slidingButtonSubject.AsObservable();
            }
        }

        void Start()
        {
            /// 加速キーを押した通知
            this.UpdateAsObservable()
                .Select(_ => Input.GetKeyDown(KeyCode.Z) == true)
                .Where(x => x)
                .Subscribe(_accelButtonSubject);

            /// スライディングキーを押した通知
            this.UpdateAsObservable()
                .Select(_ => Input.GetKeyDown(KeyCode.X) == true)
                .Where(x => x)
                .Subscribe(_slidingButtonSubject);

        }
    }
}


text:
package org.sagebionetworks.table.query.model;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;
import org.sagebionetworks.table.query.ParseException;
import org.sagebionetworks.table.query.TableQueryParser;

class QualifiedJoinTest {
	TableReference lhs;
	TableReference rhs;

	@Test
	public void testParse() throws ParseException {
		TableReference lhs = new TableQueryParser("tableA").tableReference();
		QualifiedJoin join = new TableQueryParser("join tableB on tableA.id = tableB.id").qualifiedJoin(lhs);
		assertEquals("tableA JOIN tableB ON tableA.id = tableB.id",join.toSql());
	}

	@Test
	public void testParseWithInner() throws ParseException {
		TableReference lhs = new TableQueryParser("tableA").tableReference();
		QualifiedJoin join = new TableQueryParser("inner join tableB on tableA.id = tableB.id").qualifiedJoin(lhs);
		assertEquals("tableA INNER JOIN tableB ON tableA.id = tableB.id",join.toSql());
	}

	@Test
	public void testParseWithLeftOuter() throws ParseException {
		TableReference lhs = new TableQueryParser("tableA").tableReference();
		QualifiedJoin join = new TableQueryParser("left outer join tableB on tableA.id = tableB.id").qualifiedJoin(lhs);
		assertEquals("tableA LEFT OUTER JOIN tableB ON tableA.id = tableB.id",join.toSql());
	}

	@Test
	public void testParseWithRightOuter() throws ParseException {
		TableReference lhs = new TableQueryParser("tableA").tableReference();
		QualifiedJoin join = new TableQueryParser("right outer join tableB on tableA.id = tableB.id").qualifiedJoin(lhs);
		assertEquals("tableA RIGHT OUTER JOIN tableB ON tableA.id = tableB.id",join.toSql());
	}

	@Test
	public void testParseWithNoOn() throws ParseException {
		TableReference lhs = new TableQueryParser("tableA").tableReference();
		QualifiedJoin join = new TableQueryParser("join tableB").qualifiedJoin(lhs);
		assertEquals("tableA JOIN tableB",join.toSql());
	}

	@Test
	public void testWithJoinCondition() throws ParseException {
		lhs = new TableQueryParser("tableA").tableReference();
		rhs = new TableQueryParser("tableB").tableReference();
		JoinCondition joinCondition = new JoinCondition(new TableQueryParser("tableA.foo = tableB.foo").searchCondition());
		//not exposed to parser so no parsing of qualified join string
		QualifiedJoin join = new QualifiedJoin(lhs, rhs, joinCondition);
		assertEquals("tableA JOIN tableB ON tableA.foo = tableB.foo", join.toSql());
	}

	@Test
	public void testWithOuterJoinAndJoinCondition() throws ParseException {
		lhs = new TableQueryParser("tableA").tableReference();
		rhs = new TableQueryParser("tableB").tableReference();
		JoinCondition joinCondition = new JoinCondition(new TableQueryParser("tableA.foo = tableB.foo").searchCondition());
		//not exposed to parser so no parsing of qualified join string
		QualifiedJoin join = new QualifiedJoin(lhs, new JoinType(OuterJoinType.LEFT), rhs, joinCondition);
		assertEquals("tableA LEFT JOIN tableB ON tableA.foo = tableB.foo", join.toSql());
	}
}


text:
<?php

set_time_limit(0);

if (function_exists('ini_set')) {
    @ini_set('display_errors', 1);

    $memoryInBytes = function ($value) {
        $unit = strtolower(substr($value, -1, 1));
        $value = (int) $value;
        switch($unit) {
            case 'g':
                $value *= 1024;
                // no break (cumulative multiplier)
            case 'm':
                $value *= 1024;
                // no break (cumulative multiplier)
            case 'k':
                $value *= 1024;
        }

        return $value;
    };

    $memoryLimit = trim(ini_get('memory_limit'));
    // Increase memory_limit if it is lower than 512M
    if ($memoryLimit != -1 && $memoryInBytes($memoryLimit) < 512 * 1024 * 1024) {
        @ini_set('memory_limit', '512M');
    }
    unset($memoryInBytes, $memoryLimit);
}

use Dflydev\EmbeddedComposer\Core\EmbeddedComposerBuilder;
use Sculpin\Bundle\SculpinBundle\Console\Application;
use Sculpin\Bundle\SculpinBundle\HttpKernel\KernelFactory;
use Symfony\Component\Console\Input\ArgvInput;

$input = new ArgvInput;

if ($projectDir = $input->getParameterOption('--project-dir')) {
    if (false !== strpos($projectDir, '~') && function_exists('posix_getuid')) {
        $info = posix_getpwuid(posix_getuid());
        $projectDir = str_replace('~', $info['dir'], $projectDir);
    }

    if (! is_dir($projectDir)) {
        throw new \InvalidArgumentException(
            sprintf("Specified project directory %s does not exist", $projectDir)
        );
    }

    chdir($projectDir);
}

$embeddedComposerBuilder = new EmbeddedComposerBuilder($classLoader);

$embeddedComposer = $embeddedComposerBuilder
    ->setComposerFilename('sculpin.json')
    ->setVendorDirectory('.sculpin')
    ->build();

$embeddedComposer->processAdditionalAutoloads();

$kernel = KernelFactory::create($input);
$application = new Application($kernel, $embeddedComposer);
$application->run($input);


text:
<wicket:panel>

            []

</wicket:panel>


text:
class Projects::Ci::LintsController < Projects::ApplicationController
  before_action :authorize_create_pipeline!

  def show
  end

  def create
    @content = params[:content]
    @dry_run = params[:dry_run]

    @result = Gitlab::Ci::Lint
      .new(project: @project, current_user: current_user)
      .validate(@content, dry_run: @dry_run)

    render :show
  end
end


text:
package consulo.compiler.impl;

import com.intellij.compiler.impl.TranslatingCompilerFilesMonitorImpl;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.TranslatingCompiler;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vfs.VirtualFile;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @author VISTALL
 * @since 13:36/06.11.13
 */
public abstract class TranslatingCompilerFilesMonitor {
  @Nonnull
  public static TranslatingCompilerFilesMonitor getInstance() {
    return ServiceManager.getService(TranslatingCompilerFilesMonitor.class);
  }

  public abstract void suspendProject(Project project);

  public abstract void watchProject(Project project);

  public abstract boolean isSuspended(Project project);

  public abstract boolean isSuspended(int projectId);

  public abstract void collectFiles(CompileContext context,
                    TranslatingCompiler compiler,
                    Iterator<VirtualFile> scopeSrcIterator,
                    boolean forceCompile,
                    boolean isRebuild,
                    Collection<VirtualFile> toCompile,
                    Collection<Trinity<File, String, Boolean>> toDelete);

  public abstract void update(CompileContext context,
              @Nullable String outputRoot,
              Collection<TranslatingCompiler.OutputItem> successfullyCompiled,
              VirtualFile[] filesToRecompile) throws IOException;

  public abstract void updateOutputRootsLayout(Project project);

  public abstract List<String> getCompiledClassNames(VirtualFile srcFile, Project project);

  public abstract void scanSourceContent(TranslatingCompilerFilesMonitorImpl.ProjectRef projRef,
                         Collection<VirtualFile> roots,
                         int totalRootCount,
                         boolean isNewRoots);

  public abstract void ensureInitializationCompleted(Project project, ProgressIndicator indicator);

  public abstract void scanSourcesForCompilableFiles(Project project);

  public abstract boolean isMarkedForCompilation(Project project, VirtualFile file);
}


text:
package ch.softappeal.yass.tutorial.initiator.socket;

import ch.softappeal.yass.transport.TransportSetup;
import ch.softappeal.yass.transport.socket.SimpleSocketConnector;
import ch.softappeal.yass.transport.socket.SocketTransport;
import ch.softappeal.yass.transport.socket.SyncSocketConnection;
import ch.softappeal.yass.tutorial.acceptor.socket.SocketAcceptor;
import ch.softappeal.yass.tutorial.contract.Config;
import ch.softappeal.yass.tutorial.initiator.InitiatorReconnector;
import ch.softappeal.yass.tutorial.initiator.InitiatorSession;
import ch.softappeal.yass.util.Exceptions;
import ch.softappeal.yass.util.NamedThreadFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public final class ReconnectingSocketInitiator {

    public static void main(final String... args) throws InterruptedException {
        final Executor executor = Executors.newCachedThreadPool(new NamedThreadFactory("executor", Exceptions.STD_ERR));
        final InitiatorReconnector reconnector = new InitiatorReconnector();
        reconnector.start(
            executor,
            10,
            connection -> new InitiatorSession(connection, executor),
            sessionFactory -> SocketTransport.connect(
                executor,
                SyncSocketConnection.FACTORY,
                TransportSetup.ofContractSerializer(Config.CONTRACT_SERIALIZER, sessionFactory),
                new SimpleSocketConnector(SocketAcceptor.ADDRESS)
            )
        );
        System.out.println("started");
        while (true) {
            TimeUnit.SECONDS.sleep(1L);
            if (reconnector.connected()) {
                try {
                    System.out.println(reconnector.echoService.echo("knock"));
                } catch (final Exception e) {
                    System.out.println("race condition: " + e.toString());
                }
            } else {
                System.out.println("not connected");
            }
        }
    }

}


text:
description: This page is themguide to internationalizing an iOS application.
---

## iOS guide to i18n

Here are the instructions to internationalize your iOS application. Please follow the steps below:

1) Add a file named `Lock.strings`, which is the format for i18n in iOS, included in the bundle of the app when is built. The easier way to do it is using Xcode, just go to `File -> New File`, then `iOS -> Strings File`. The name will be Auth0 and make sure it's added to your application target by checking the box.

![](/media/articles/i18n/i18n-guide-mobile/i18n-guide-mobile-1.png)

![](/media/articles/i18n/i18n-guide-mobile/i18n-guide-mobile-2.png)

2) Then the file contents should be something like this:

```
"Email" = "Email";
"Password" = "Passwort";
"ACCESS" = "ZUGRIFF";
```

Where the key is the text you see in screen and the value is the translation.

3) To have multiple languages you'll need to add them in your project settings:

![](/media/articles/i18n/i18n-guide-mobile/i18n-guide-mobile-1.png)

4) Then you will see different files per language you can customize:

![](/media/articles/i18n/i18n-guide-mobile/i18n-guide-mobile-3.png)