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

<title>Uses of Interface com.badlogic.gdx.utils.Predicate (libgdx API)</title>
<meta name="date" content="2013-05-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.badlogic.gdx.utils.Predicate

Packages that use Predicate

Package
Description

com.badlogic.gdx.utils

Uses of Predicate in com.badlogic.gdx.utils

Fields in com.badlogic.gdx.utils declared as Predicate

Modifier and Type
Field and Description

Predicate<T>
Predicate.PredicateIterator.predicate

Predicate<T>
Predicate.PredicateIterable.predicate

Methods in com.badlogic.gdx.utils with parameters of type Predicate

Modifier and Type
Method and Description

java.lang.Iterable<T>
Array.select(Predicate<T> predicate)

Returns an iterable for the selected items in the array.

void
Predicate.PredicateIterator.set(java.lang.Iterable<T> iterable,
   Predicate<T> predicate)

void
Predicate.PredicateIterable.set(java.lang.Iterable<T> iterable,
   Predicate<T> predicate)

void
Predicate.PredicateIterator.set(java.util.Iterator<T> iterator,
   Predicate<T> predicate)

Constructors in com.badlogic.gdx.utils with parameters of type Predicate

Constructor and Description

Predicate.PredicateIterable(java.lang.Iterable<T> iterable,
                           Predicate<T> predicate)

Predicate.PredicateIterator(java.lang.Iterable<T> iterable,
                           Predicate<T> predicate)

Predicate.PredicateIterator(java.util.Iterator<T> iterator,
                           Predicate<T> predicate)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev

Next

Frames

No Frames

All Classes

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)

redpajama_set_name: RedPajamaGithub


text:
from telegram import TelegramObject

class Message(TelegramObject):
    def __init__(self,
                 message_id,
                 from_user,
                 date,
                 chat,
                 forward_from=None,
                 forward_date=None,
                 reply_to_message=None,
                 text=None,
                 audio=None,
                 document=None,
                 photo=None,
                 sticker=None,
                 video=None,
                 contact=None,
                 location=None,
                 new_chat_participant=None,
                 left_chat_participant=None,
                 new_chat_title=None,
                 new_chat_photo=None,
                 delete_chat_photo=None,
                 group_chat_created=None):
        self.message_id = message_id
        self.from_user = from_user
        self.date = date
        self.chat = chat
        self.forward_from = forward_from
        self.forward_date = forward_date
        self.reply_to_message = reply_to_message
        self.text = text
        self.audio = audio
        self.document = document
        self.photo = photo
        self.sticker = sticker
        self.video = video
        self.contact = contact
        self.location = location
        self.new_chat_participant = new_chat_participant
        self.left_chat_participant = left_chat_participant
        self.new_chat_title = new_chat_title
        self.new_chat_photo = new_chat_photo
        self.delete_chat_photo = delete_chat_photo
        self.group_chat_created = group_chat_created

    @property
    def chat_id(self):
        return self.chat.id

    @staticmethod
    def de_json(data):
        if 'from' in data:  # from is a reserved word, use from_user instead.
            from telegram import User
            from_user = User.de_json(data['from'])
        else:
            from_user = None

        if 'chat' in data:
            if 'first_name' in data['chat']:
                from telegram import User
                chat = User.de_json(data['chat'])
            if 'title' in data['chat']:
                from telegram import GroupChat
                chat = GroupChat.de_json(data['chat'])
        else:
            chat = None

        if 'forward_from' in data:
            from telegram import User
            forward_from = User.de_json(data['forward_from'])
        else:
            forward_from = None

        if 'reply_to_message' in data:
            reply_to_message = Message.de_json(data['reply_to_message'])
        else:
            reply_to_message = None

        if 'text' in data:
            text = data['text']
        else:
            text = None

        if 'audio' in data:
            from telegram import Audio
            audio = Audio.de_json(data['audio'])
        else:
            audio = None

        if 'document' in data:
            from telegram import Document
            document = Document.de_json(data['document'])
        else:
            document = None

        if 'photo' in data:
            from telegram import PhotoSize
            photo = [PhotoSize.de_json(x) for x in data['photo']]
        else:
            photo = None

        if 'sticker' in data:
            from telegram import Sticker
            sticker = Sticker.de_json(data['sticker'])
        else:
            sticker = None

        if 'video' in data:
            from telegram import Video
            video = Video.de_json(data['video'])
        else:
            video = None

        if 'contact' in data:
            from telegram import Contact
            contact = Contact.de_json(data['contact'])
        else:
            contact = None

        if 'location' in data:
            from telegram import Location
            location = Location.de_json(data['location'])
        else:
            location = None

        if 'new_chat_participant' in data:
            from telegram import User
            new_chat_participant = User.de_json(data['new_chat_participant'])
        else:
            new_chat_participant = None

        if 'left_chat_participant' in data:
            from telegram import User
            left_chat_participant = User.de_json(data['left_chat_participant'])
        else:
            left_chat_participant = None

        return Message(message_id=data.get('message_id', None),
                       from_user=from_user,
                       date=data.get('date', None),
                       chat=chat,
                       forward_from=forward_from,
                       forward_date=data.get('forward_date', None),
                       reply_to_message=reply_to_message,
                       text=text,
                       audio=audio,
                       document=document,
                       photo=photo,
                       sticker=sticker,
                       video=video,
                       contact=contact,
                       location=location,
                       new_chat_participant=new_chat_participant,
                       left_chat_participant=left_chat_participant,
                       new_chat_title=data.get('new_chat_title', None),
                       new_chat_photo=data.get('new_chat_photo', None),
                       delete_chat_photo=data.get('delete_chat_photo', None),
                       group_chat_created=data.get('group_chat_created', None))

    def to_dict(self):
        data = {'message_id': self.message_id,
                'from': self.from_user.to_dict(),
                'date': self.date,
                'chat': self.chat.to_dict()}
        if self.forward_from:
            data['forward_from'] = self.forward_from
        if self.forward_date:
            data['forward_date'] = self.forward_date
        if self.reply_to_message:
            data['reply_to_message'] = self.reply_to_message
        if self.text:
            data['text'] = self.text
        if self.audio:
            data['audio'] = self.audio.to_dict()
        if self.document:
            data['document'] = self.document.to_dict()
        if self.photo:
            data['photo'] = [p.to_dict() for p in self.photo]
        if self.sticker:
            data['sticker'] = self.sticker.to_dict()
        if self.video:
            data['video'] = self.video.to_dict()
        if self.contact:
            data['contact'] = self.contact.to_dict()
        if self.location:
            data['location'] = self.location.to_dict()
        if self.new_chat_participant:
            data['new_chat_participant'] = self.new_chat_participant
        if self.left_chat_participant:
            data['left_chat_participant'] = self.left_chat_participant
        if self.new_chat_title:
            data['new_chat_title'] = self.new_chat_title
        if self.new_chat_photo:
            data['new_chat_photo'] = self.new_chat_photo
        if self.delete_chat_photo:
            data['delete_chat_photo'] = self.delete_chat_photo
        if self.group_chat_created:
            data['group_chat_created'] = self.group_chat_created
        return data


text:
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
  "date-uk-pre": function ( a ) {
      var ukDatea = a.split('/');
      return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
  },

  "date-uk-asc": function ( a, b ) {
    return ((a  b) ? 1 : 0));
  },

  "date-uk-desc": function ( a, b ) {
    return ((a  b) ? -1 : 0));
  }
});

var table = $('#lista_mantenimientos_equipos').dataTable( {

  "dom": "T<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row dataTableFooter'<'col-md-6'i><'col-md-6'p>>",
  "tableTools": {
    "sSwfPath": "<?=base_url().'assets/global/plugins/datatables/extensions/TableTools'?>/swf/copy_csv_xls_pdf.swf",
    "aButtons": [ {"sExtends": "copy", "sButtonText": "Copiar", "mColumns": [0,1,2,3]},
                  {"sExtends": "pdf", "title": "Ingeniería Vialda C.A. - Listado mantenimientos para equipos", "sPdfSize": "letter", "sPdfOrientation": "landscape", "sButtonText": "Guardar PDF", "mColumns": [0,1,2,3]},
                  {"sExtends": "xls", "title": "Ingeniería Vialda C.A. - Listado mantenimientos para equipos", "sButtonText": "Guardar MS Excel", "mColumns": [0,1,2,3]} ]
  },
  "order": [[6, 'desc']],
  "processing": true,
  "ordering": true,
  "pageLength": 5,
  "searching": true,
  "ajax": '<?=base_url().'inventario/listaequipos_mantenimientos'?>',
  "language": {
    "url": "<?=base_url().'assets/global/plugins/datatables/extensions/es_ES.txt'?>"
  },
  "columnDefs": [
    { "width": "30%", "title": "Equipo", "data": "equipo", "targets": [0] },
    { "width": "25%", "title": "Mantenimiento", "data": "mantenimiento", "targets": [1] },
    { "width": "15%", "title": "Inicio", "data": "inicio", "type": "date-uk", "targets": [2] },
    { "width": "20%", "title": "Culminación", "data": "culminacion", "type": "date-uk", "targets": [3] },
    { "width": "20%", "title": "Estado", "data": "estado", "targets": [4],
      "render": function ( data, type, full, meta ) {
        if(data == "Finalizado"){
          return ''+data+'';
        }else{
          return ''+data+'';
        }
      }
    },
    { "data": "id", "visible": false, "orderable": false, "targets": [5] },
    { "data": "created_at", "visible": false, "type": "date", "targets": [6] },
    { "data": "responsable", "visible": false, "targets": [7] },
    { "data": "observaciones", "visible": false, "targets": [8] },
    { "data": "serial", "visible": false, "targets": [9] },
    { "data": "equipo_id", "visible": false, "targets": [10] },
    { "data": "mantenimiento_id", "visible": false, "targets": [11] },
  ],
  initComplete: function ( settings, json ) {
    $("#filtro").append( $('.DTTT')[0] );
  }

});

$('body').on('click', function (e) {
  $('[data-toggle="popover"]').each(function () {
    //the 'is' for buttons that trigger popups
    //the 'has' for icons within a button that triggers a popup
    if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('[data-toggle="popover"]').has(e.target).length === 0 && e.target.id !== "confirmEliminar" && e.target.id !== "confirmFinalizar"){
      $(this).popover('hide');
    }
  });
});

$(function(){
  $("button").on('click', function(){

    if(this.id == "ver"){

      if($("#nuevo").is(":visible")){
        $("#nuevo").hide();
      }
      $("#padre").html("");
      $("#id").val("");
      $("#cat_id").val("");
      $("#ref").empty();
      $("#nombre").empty();
      $("#descripcion").empty();
      $("#cat").empty();
      $("#detalles").hide();
    }

    if(this.id == "form"){
      $("#nuevo").hide();
    }

  });
});

$('#lista_mantenimientos_equipos').on('click', 'tbody tr', function(event){

  if($("#nuevo").is(":visible")){
    $("#nuevo").hide();
  }

  var sData = table.fnGetData(this);
  $("#id").val(sData.id);
  $("#equipo").html(sData.equipo);
  $("#equipo_id").val(sData.equipo_id);
  $("#serial_equipo").html(sData.serial);
  $("#mantenimiento_id").val(sData.mantenimiento_id);
  $("#mantenimiento").html(sData.mantenimiento);
  $("#estado").html(sData.estado);
  $("#responsable").html(sData.responsable);
  $("#observaciones").html(sData.observaciones);
  $("#fecha_inicio").html(sData.inicio);
  $("#fecha_culminacion").html(sData.culminacion);
  $("#detalles").show();

});

$('#form_mantenimiento_equipo_nuevo').validate({
    errorElement: 'span', //default input error message container
    errorClass: 'help-inline', // default input error message class
    focusInvalid: false, // do not focus the last invalid input
    ignore: "",
    rules: {
        equipo_id: {
            required: true
        },
        mantenimiento_id: {
            required: true
        },
        fecha_inicio: {
          required: true
        },
        fecha_culminacion: {
          required: true
        },
        responsable: {
          required: true
        }
    },

    invalidHandler: function (event, validator) { //display error alert on form submit
        $('.alert-success').hide();
        $('.alert-error').show();
    },

    submitHandler: function (form) {
        //$('.alert-success').show();
        $('.alert-error').hide();
        form.submit();
    },

    highlight: function (element) { // hightlight error inputs
        $(element).closest('.help-inline').removeClass('ok'); // display OK icon
        $(element).closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
    },

    unhighlight: function (element) { // revert the change dony by hightlight
        $(element).closest('.control-group').removeClass('error'); // set error class to the control group
    },

    success: function (label) {
        label.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
        .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
    }
});

$("#date-picker-start").datepicker({
  onRender: function(date){
    return date.valueOf() <= now.valueOf() ? 'disabled' : '';
  },
  format: 'dd/mm/yyyy',
  startDate: new Date(),
  autoclose: true,
  todayHighlight: true,
  language: "es"
}).on('changeDate', function(dateEvent) {
      start_date = $("#date-picker-start").val();
      $('#date-picker-end').datepicker({
        format: 'dd/mm/yyyy',
        startDate: start_date,
        autoclose: true,
        language: "es",
        onRender: function(date){
          return date.valueOf() <= now.valueOf() ? 'disabled' : '';
        },
      });
    });


text:
package com.google.i18n.addressinput.common;

import static com.google.i18n.addressinput.common.Util.checkNotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * An immutable data structure for international postal addresses, built using the nested
 * {@link Builder} class.
 *

 * Addresses may seem simple, but even within the US there are many quirks (hyphenated street
 * addresses, etc.), and internationally addresses vary a great deal. The most sane and complete in
 * many ways is the OASIS "extensible Address Language", xAL, which is a published and documented
 * XML schema:

 *
 * http://www.oasis-open.org/committees/ciq/download.shtml
 *

 * An example address:
 *

 * postalCountry: US
 * streetAddress: 1098 Alta Ave
 * adminstrativeArea: CA
 * locality: Mountain View
 * dependentLocality:
 * postalCode: 94043
 * sortingCode:
 * organization: Google
 * recipient: Chen-Kang Yang
 * language code: en
 *

 *

 * When using this class it's advised to do as little pre- or post-processing of the fields as
 * possible. Typically we expect instances of this class to be used by the address widget and then
 * transmitted or converted to other representations using the standard conversion libraries or
 * formatted using one of the supported formatters. Attempting to infer semantic information from
 * the values of the fields in this class is generally a bad idea.
 *

 * Specifically the {@link #getFieldValue(AddressField)} is a problematic API as it encourages the
 * belief that it is semantically correct to iterate over the fields in order. In general it should
 * not be necessary to iterate over the fields in this class; instead use just the specific getter
 * methods for the fields you need.
 *

 * There are valid use cases for examining individual fields, but these are almost always region
 * dependent:
 *

 *
Finding the region of the address. This is really the only completely safe field you can
 * examine which gives an unambiguous and well defined result under all circumstances.
 *
Testing if two addresses have the same administrative area. This is only reliable if the
 * data was entered via a drop-down menu, and the size of administrative areas varies greatly
 * between and within countries so it doesn't infer much about locality.
 *
Extracting postal codes or sorting codes for address validation or external lookup. This
 * only works for certain countries, such as the United Kingdom, where postal codes have a high
 * resolution.
 *

 *

 * All values stored in this class are trimmed of ASCII whitespace. Setting an empty, or whitespace
 * only field in the builder will clear it and result in a {@code null} being returned from the
 * corresponding {@code AddressData} instance..
 */
// This is an external class and part of the widget's public API.
// TODO: Review public API for external classes and tidy JavaDoc.
public final class AddressData {
  // The list of deprecated address fields which are superseded by STREET_ADDRESS.
  @SuppressWarnings("deprecation")  // For legacy address fields.
  private static final List<AddressField> ADDRESS_LINE_FIELDS = Collections.unmodifiableList(
      Arrays.asList(AddressField.ADDRESS_LINE_1, AddressField.ADDRESS_LINE_2));

  private static final int ADDRESS_LINE_COUNT = ADDRESS_LINE_FIELDS.size();

  // The set of address fields for which a single string value can be mapped.
  private static final EnumSet<AddressField> SINGLE_VALUE_FIELDS;
  static {
    SINGLE_VALUE_FIELDS = EnumSet.allOf(AddressField.class);
    SINGLE_VALUE_FIELDS.removeAll(ADDRESS_LINE_FIELDS);
    SINGLE_VALUE_FIELDS.remove(AddressField.STREET_ADDRESS);
  }

  // When this is merged for use by GWT, remember to add @NonFinalForGwt in place of final fields.

  // Detailed information on these fields is available in the javadoc for their respective getters.

  // CLDR (Common Locale Data Repository) country code.
  private final String postalCountry;

  // The most specific part of any address. They may be left empty if more detailed fields are used
  // instead, or they may be used in addition to these if the more detailed fields do not fulfill
  // requirements, or they may be used instead of more detailed fields to represent the street-level
  // part.
  private final List<String> addressLines;

  // Top-level administrative subdivision of this country.
  private final String administrativeArea;

  // Generally refers to the city/town portion of an address.
  private final String locality;

  // Dependent locality or sublocality. Used for neighborhoods or suburbs.
  private final String dependentLocality;

  // Values are frequently alphanumeric.
  private final String postalCode;

  // This corresponds to the SortingCode sub-element of the xAL PostalServiceElements element.
  // Use is very country-specific.
  private final String sortingCode;

  // The firm or organization. This goes at a finer granularity than address lines in the address.
  private final String organization;

  // The recipient. This goes at a finer granularity than address lines in the address. Not present
  // in xAL.
  private final String recipient;

  // BCP-47 language code for the address. Can be set to null.
  private final String languageCode;

  // NOTE: If you add a new field which is semantically significant, you must also add a check for
  // that field in {@link equals} and {@link hashCode}.

  private AddressData(Builder builder) {
    this.postalCountry = builder.fields.get(AddressField.COUNTRY);
    this.administrativeArea = builder.fields.get(AddressField.ADMIN_AREA);
    this.locality = builder.fields.get(AddressField.LOCALITY);
    this.dependentLocality = builder.fields.get(AddressField.DEPENDENT_LOCALITY);
    this.postalCode = builder.fields.get(AddressField.POSTAL_CODE);
    this.sortingCode = builder.fields.get(AddressField.SORTING_CODE);
    this.organization = builder.fields.get(AddressField.ORGANIZATION);
    this.recipient = builder.fields.get(AddressField.RECIPIENT);
    this.addressLines = Collections.unmodifiableList(
        normalizeAddressLines(new ArrayList<String>(builder.addressLines)));
    this.languageCode = builder.language;
  }

  // Helper to normalize a list of address lines. The input may contain null entries or strings
  // which must be split into multiple lines. The resulting list entries will be trimmed
  // consistently with String.trim() and any empty results are ignored.
  // TODO: Trim entries properly with respect to Unicode whitespace.
  private static List<String> normalizeAddressLines(List<String> lines) {
    // Guava equivalent code for each line would look something like:
    // Splitter.on("\n").trimResults(CharMatcher.inRange('\0', ' ')).omitEmptyStrings();
    for (int index = 0; index < lines.size(); ) {
      String line = lines.remove(index);
      if (line == null) {
        continue;
      }
      if (line.contains("\n")) {
        for (String splitLine : line.split("\n")) {
          index = maybeAddTrimmedLine(splitLine, lines, index);
        }
      } else {
        index = maybeAddTrimmedLine(line, lines, index);
      }
    }
    return lines;
  }

  // Helper to trim a string and (if not empty) add it to the given list at the specified index.
  // Returns the new index at which any following elements should be added.
  private static int maybeAddTrimmedLine(String line, List<String> lines, int index) {
    line = Util.trimToNull(line);
    if (line != null) {
      lines.add(index++, line);
    }
    return index;
  }

  /**
   * Returns a string representation of the address, used for debugging.
   */
  @Override
  public String toString() {
    StringBuilder output = new StringBuilder("(AddressData: "
        + "POSTAL_COUNTRY=" + postalCountry + "; "
        + "LANGUAGE=" + languageCode + "; ");
    for (String line : addressLines) {
      output.append(line + "; ");
    }
    output.append("ADMIN_AREA=" + administrativeArea + "; "
        + "LOCALITY=" + locality + "; "
        + "DEPENDENT_LOCALITY=" + dependentLocality + "; "
        + "POSTAL_CODE=" + postalCode + "; "
        + "SORTING_CODE=" + sortingCode + "; "
        + "ORGANIZATION=" + organization + "; "
        + "RECIPIENT=" + recipient
        + ")");
    return output.toString();
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (!(o instanceof AddressData)) {
      return false;
    }
    AddressData addressData = (AddressData) o;

    return (postalCountry == null
            ? addressData.getPostalCountry() == null
            : postalCountry.equals(addressData.getPostalCountry()))
        && (addressLines == null
            ? addressData.getAddressLines() == null
            : addressLines.equals(addressData.getAddressLines()))
        && (administrativeArea == null
            ? addressData.getAdministrativeArea() == null
            : this.getAdministrativeArea().equals(addressData.getAdministrativeArea()))
        && (locality == null
            ? addressData.getLocality() == null
            : locality.equals(addressData.getLocality()))
        && (dependentLocality == null
            ? addressData.getDependentLocality() == null
            : dependentLocality.equals(addressData.getDependentLocality()))
        && (postalCode == null
            ? addressData.getPostalCode() == null
            : postalCode.equals(addressData.getPostalCode()))
        && (sortingCode == null
            ? addressData.getSortingCode() == null
            : sortingCode.equals(addressData.getSortingCode()))
        && (organization == null
            ? addressData.getOrganization() == null
            : organization.equals(addressData.getOrganization()))
        && (recipient == null
            ? addressData.getRecipient() == null
            : recipient.equals(addressData.getRecipient()))
        && (languageCode == null
            ? addressData.getLanguageCode() == null
            : languageCode.equals(addressData.getLanguageCode()));
  }

  @Override
  public int hashCode() {
    // 17 and 31 are arbitrary seed values.
    int result = 17;

    String[] fields =
        new String[] {
          postalCountry,
          administrativeArea,
          locality,
          dependentLocality,
          postalCode,
          sortingCode,
          organization,
          recipient,
          languageCode
        };

    for (String field : fields) {
      result = 31 * result + (field == null ? 0 : field.hashCode());
    }

    // The only significant field which is not a String.
    result = 31 * result + (addressLines == null ? 0 : addressLines.hashCode());

    return result;
  }

  /**
   * Returns the CLDR region code for this address; note that this is not the same as the
   * ISO 3166-1 2-letter country code. While technically optional, this field will always be set
   * by the address widget when an address is entered or edited, and will be assumed to be set by
   * many other tools.
   *

   * While they have most of their values in common with the CLDR region codes, the ISO 2-letter
   * country codes have one significant disadvantage; they are not stable and values can change over
   * time. For example {@code "CS"} was originally used to represent Czechoslovakia, but later
   * represented Serbia and Montenegro. In contrast, CLDR region codes are never reused and can
   * represent more regions, such as Ascension Island (AC).
   *

   * See the page on
   *
   * Territory Containment for a list of CLDR region codes.
   *

   * Note that the region codes not user-presentable; "GB" is Great Britain but this should always
   * be displayed to a user as "UK" or "United Kingdom".
   */
  public String getPostalCountry() {
    return postalCountry;
  }

  /**
   * Returns multiple free-form address lines representing low level parts of an address,
   * possibly empty. The first line represents the lowest level part of the address, other than
   * recipient or organization.
   *

   * Note that the number of lines returned by this method may be greater than the number of lines
   * set on the original builder if some of the lines contained embedded newlines. The values
   * returned by this method will never contain embedded newlines.
   *

   * For example:
   *
{@code
   *   data = AddressData.builder()
   *       .setAddressLine1("First line\nSecond line")
   *       .setAddressLine2("Last line")
   *       .build();
   *   // We end up with 3 lines in the final AddressData instance:
   *   // data.getAddressLines() == [ "First line", "Second line", "Last line" ]
   * }

   */
  public List<String> getAddressLines() {
    return addressLines;
  }

  /** @deprecated Use {@link #getAddressLines} in preference. */
  @Deprecated
  public String getAddressLine1() {
    return getAddressLine(1);
  }

  /** @deprecated Use {@link #getAddressLines} in preference. */
  @Deprecated
  public String getAddressLine2() {
    return getAddressLine(2);
  }

  // Helper for returning the Nth address line. This is split out here so that it's easily to
  // change the maximum number of address lines we support.
  private String getAddressLine(int lineNumber) {
    // If not the last available line, OR if we're the last line but there are no extra lines...
    if (lineNumber < ADDRESS_LINE_COUNT || lineNumber >= addressLines.size()) {
      return (lineNumber <= addressLines.size()) ? addressLines.get(lineNumber - 1) : null;
    }
    // We're asking for the last available line and there are additional lines in the data.
    // Here it should be true that: lineNumber == ADDRESS_LINE_COUNT
    // Guava equivalent:
    // return Joiner.on(", ")
    //     .join(addressLines.subList(ADDRESS_LINE_COUNT - 1, addressLines.size()));
    StringBuilder joinedLastLine = new StringBuilder(addressLines.get(lineNumber - 1));
    for (String line : addressLines.subList(lineNumber, addressLines.size())) {
      joinedLastLine.append(", ").append(line);
    }
    return joinedLastLine.toString();
  }

  /**
   * Returns the top-level administrative subdivision of this country. Different postal countries
   * use different names to refer to their administrative areas. For example: "state" (US), "region"
   * (Italy) or "prefecture" (Japan).
   *

   * Where data is available, the user will be able to select the administrative area name from a
   * drop-down list, ensuring that it has only expected values. However this is not always possible
   * and no strong assumptions about validity should be made by the user for this value.
   */
  public String getAdministrativeArea() {
    return administrativeArea;
  }

  /**
   * Returns the language specific locality, if present. The usage of this field varies by region,
   * but it generally refers to the "city" or "town" of the address. Some regions do not use this
   * field; their address lines combined with things like postal code or administrative area are
   * sufficient to locate an address.
   *

   * Different countries use different names to refer to their localities. For example: "city" (US),
   * "comune" (Italy) or "post town" (Great Britain). For Japan this would return the shikuchouson
   * and sub-shikuchouson.
   */
  public String getLocality() {
    return locality;
  }

  /**
   * Returns the dependent locality, if present.
   *

   * This is used for neighborhoods and suburbs. Typically a dependent locality will represent a
   * smaller geographical area than a locality, but need not be contained within it.
   */
  public String getDependentLocality() {
    return dependentLocality;
  }

  /**
   * Returns the postal code of the address, if present. This value is not language specific but
   * may contain arbitrary formatting characters such as spaces or hyphens and might require
   * normalization before any meaningful comparison of values.
   *

   * For example: "94043", "94043-1351", "SW1W", "SW1W 9TQ".
   */
  public String getPostalCode() {
    return postalCode;
  }

  /**
   * Returns the sorting code if present. Sorting codes are distinct from postal codes and only
   * used in a handful of regions (eg, France).
   *

   * For example in France this field would contain a
   * CEDEX value.
   */
  public String getSortingCode() {
    return sortingCode;
  }

  /**
   * Returns the free form organization string, if present. No assumptions should be made about
   * the contents of this field. This field exists because in some situations the organization
   * and recipient fields must be treated specially during formatting. It is not a good idea to
   * allow users to enter the organization or recipient in the street address lines as this will
   * result in badly formatted and non-geocodeable addresses.
   */
  public String getOrganization() {
    return organization;
  }

  /**
   * Returns the free form recipient string, if present. No assumptions should be made about the
   * contents of this field. This field exists because in some situations the organization
   * and recipient fields must be treated specially during formatting. It is not a good idea to
   * allow users to enter the organization or recipient in the street address lines as this will
   * result in badly formatted and non-geocodeable addresses.
   */
  public String getRecipient() {
    return recipient;
  }

  /**
   * Returns a value for those address fields which map to a single string value.
   *

   * Note that while it is possible to pass {@link AddressField#ADDRESS_LINE_1} and
   * {@link AddressField#ADDRESS_LINE_2} into this method, these fields are deprecated and will be
   * removed. In general you should be using named methods to obtain specific values for the address
   * (eg, {@link #getAddressLines()}) and avoid iterating in a general way over the fields.
   * This method has very little value outside of the widget itself and is scheduled for removal.
   *
   * @deprecated Do not use; scheduled for removal from the public API.
   */
  @Deprecated
  @SuppressWarnings("deprecation")
  // TODO: Move this to a utility method rather than exposing it in the public API.
  public String getFieldValue(AddressField field) {
    switch (field) {
      case COUNTRY:
        return postalCountry;
      case ADMIN_AREA:
        return administrativeArea;
      case LOCALITY:
        return locality;
      case DEPENDENT_LOCALITY:
        return dependentLocality;
      case POSTAL_CODE:
        return postalCode;
      case SORTING_CODE:
        return sortingCode;
      case ADDRESS_LINE_1:
        return getAddressLine1();
      case ADDRESS_LINE_2:
        return getAddressLine2();
      case ORGANIZATION:
        return organization;
      case RECIPIENT:
        return recipient;
      default:
        throw new IllegalArgumentException("multi-value fields not supported: " + field);
    }
  }

  /**
   * Returns the BCP-47 language code for this address which defines the language we expect to be
   * used for any language specific fields. If this method returns {@code null} then the language
   * is assumed to be in the default (most used) language for the region code of the address;
   * although the precise determination of a default language is often approximate and may change
   * over time. Wherever possible it is recommended to construct {@code AddressData} instances
   * with a specific language code.
   *

   * Languages are used to guide how the address is  formatted for
   * display. The same address may have different {@link AddressData} representations in
   * different languages. For example, the French name of "New Mexico" is "Nouveau-Mexique".
   */
  public String getLanguageCode() {
    return languageCode;
  }

  /** Returns a new builder to construct an {@code AddressData} instance. */
  public static Builder builder() {
    return new Builder();
  }

  /** Returns a new builder to construct an {@code AddressData} instance. */
  public static Builder builder(AddressData address) {
    return builder().set(address);
  }

  /** Builder for AddressData. */
  public static final class Builder {
    // A map of single value address fields to their values.
    private final Map<AddressField, String> fields = new HashMap<AddressField, String>();
    // The address lines, not normalized.
    private final List<String> addressLines = new ArrayList<String>();
    // The BCP-47 language of the address.
    private String language = null;

    /**
     * Constructs an empty builder for AddressData instances. Prefer to use one of the
     * {@link AddressData#builder} methods in preference to this.
     */
    // TODO: Migrate users and make this private.
    public Builder() {}

    /**
     * Constructs a builder for AddressData instances using data from the given address.
     * Prefer to use one of the {@link AddressData#builder} methods in preference to this.
     *
     * @deprecated Use the builder() methods on AddressData in preference to this.
     */
    @Deprecated
    // TODO: Migrate users and delete this method.
    public Builder(AddressData address) {
      set(address);
    }

    /**
     * Sets the 2-letter CLDR region code of the address; see
     * {@link AddressData#getPostalCountry()}. Unlike other values passed to the builder, the
     * region code can never be null.
     *
     * @param regionCode the CLDR region code of the address.
     */
    // TODO: Rename to setRegionCode.
    public Builder setCountry(String regionCode) {
      return set(AddressField.COUNTRY, checkNotNull(regionCode));
    }

    /**
     * Sets or clears the administrative area of the address; see
     * {@link AddressData#getAdministrativeArea()}.
     *
     * @param adminAreaName the administrative area name, or null to clear an existing value.
     */
    // TODO: Rename to setAdministrativeArea.
    public Builder setAdminArea(String adminAreaName) {
      return set(AddressField.ADMIN_AREA, adminAreaName);
    }

    /**
     * Sets or clears the locality of the address; see {@link AddressData#getLocality()}.
     *
     * @param locality the locality name, or null to clear an existing value.
     */
    public Builder setLocality(String locality) {
      return set(AddressField.LOCALITY, locality);
    }

    /**
     * Sets or clears the dependent locality of the address; see
     * {@link AddressData#getDependentLocality()}.
     *
     * @param dependentLocality the dependent locality name, or null to clear an existing value.
     */
    public Builder setDependentLocality(String dependentLocality) {
      return set(AddressField.DEPENDENT_LOCALITY, dependentLocality);
    }

    /**
     * Sets or clears the postal code of the address; see {@link AddressData#getPostalCode()}.
     *
     * @param postalCode the postal code, or null to clear an existing value.
     */
    public Builder setPostalCode(String postalCode) {
      return set(AddressField.POSTAL_CODE, postalCode);
    }

    /**
     * Sets or clears the sorting code of the address; see {@link AddressData#getSortingCode()}.
     *
     * @param sortingCode the sorting code, or null to clear an existing value.
     */
    public Builder setSortingCode(String sortingCode) {
      return set(AddressField.SORTING_CODE, sortingCode);
    }

    /**
     * Sets or clears the BCP-47 language code for this address (eg, "en" or "zh-Hant"). If the
     * language is not set, then the address will be assumed to be in the default language of the
     * country of the address; however it is highly discouraged to rely on this as the default
     * language may change over time. See {@link AddressData#getLanguageCode()}.
     *
     * @param languageCode the BCP-47 language code, or null to clear an existing value.
     */
    public Builder setLanguageCode(String languageCode) {
      this.language = languageCode;
      return this;
    }

    /**
     * Sets multiple unstructured street level lines in the address. Calling this method will
     * always discard any existing address lines before adding new ones.
     *

     * Note that the number of lines set by this method is preserved in the builder's state but a
     * single line set here may result in multiple lines in the resulting {@code AddressData}
     * instance if it contains embedded newline characters.
     *

     * For example:
     *
{@code
     *   data = AddressData.builder()
     *       .setAddressLines(Arrays.asList("First line\nSecond line"))
     *       .setAddressLine2("Last line");
     *       .build();
     *   // data.getAddressLines() == [ "First line", "Second line", "Last line" ]
     * }

     */
    public Builder setAddressLines(Iterable<String> lines) {
      addressLines.clear();
      for (String line : lines) {
        addressLines.add(line);
      }
      return this;
    }

    /**
     * Adds another address line. Embedded newlines will be normalized when "build()" is called.
     */
    // TODO: Consider removing this method if nobody is using it to simplify the API.
    public Builder addAddressLine(String value) {
      addressLines.add(value);
      return this;
    }

    /**
     * Sets multiple street lines from a single street string, clearing any existing address lines
     * first. The input string may contain new lines which will result in multiple separate lines
     * in the resulting {@code AddressData} instance. After splitting, each line is trimmed and
     * empty lines are ignored.
     *

     * Example: {@code "  \n   \n1600 Amphitheatre Ave\n\nRoom 122"} will set the lines:
     *

     *
"1600 Amphitheatre Ave"
     *
"Room 122"
     *

     *
     * @param value a string containing one or more address lines, separated by {@code "\n"}.
     */
    public Builder setAddress(String value) {
      addressLines.clear();
      addressLines.add(value);
      normalizeAddressLines(addressLines);
      return this;
    }

    /**
     * Copies all the data of the given address into the builder. Any existing data in the builder
     * is discarded.
     */
    public Builder set(AddressData data) {
      fields.clear();
      for (AddressField addressField : SINGLE_VALUE_FIELDS) {
        set(addressField, data.getFieldValue(addressField));
      }
      addressLines.clear();
      addressLines.addAll(data.addressLines);
      setLanguageCode(data.getLanguageCode());
      return this;
    }

    /**
     * TODO: Remove this method in favor of setAddressLines(Iterable<String>).
     *
     * @deprecated Use {@link #setAddressLines} instead.
     */
    @Deprecated
    public Builder setAddressLine1(String value) {
      return setAddressLine(1, value);
    }

    /**
     * TODO: Remove this method in favor of setAddressLines(Iterable<String>).
     *
     * @deprecated Use {@link #setAddressLines} instead.
     */
    @Deprecated
    public Builder setAddressLine2(String value) {
      return setAddressLine(2, value);
    }

    /**
     * Sets or clears the organization of the address; see {@link AddressData#getOrganization()}.
     *
     * @param organization the organization, or null to clear an existing value.
     */
    public Builder setOrganization(String organization) {
      return set(AddressField.ORGANIZATION, organization);
    }

    /**
     * Sets or clears the recipient of the address; see {@link AddressData#getRecipient()}.
     *
     * @param recipient the recipient, or null to clear an existing value.
     */
    public Builder setRecipient(String recipient) {
      return set(AddressField.RECIPIENT, recipient);
    }

    /**
     * Sets an address field with the specified value. If the value is empty (null or whitespace),
     * the original value associated with the field will be removed.
     *
     * @deprecated Do not use; scheduled for removal from the public API.
     */
    @Deprecated
    @SuppressWarnings("deprecation")
    // TODO: Reimplement using public API as a utility function in AddressWidget (the only caller).
    public Builder set(AddressField field, String value) {
      if (SINGLE_VALUE_FIELDS.contains(field)) {
        value = Util.trimToNull(value);
        if (value == null) {
          fields.remove(field);
        } else {
          fields.put(field, value);
        }
      } else if (field == AddressField.STREET_ADDRESS) {
        if (value == null) {
          addressLines.clear();
        } else {
          setAddress(value);
        }
      } else {
        int lineNum = ADDRESS_LINE_FIELDS.indexOf(field) + 1;
        if (lineNum > 0) {
          setAddressLine(lineNum, value);
        }
      }
      return this;
    }

    // This may preserve whitespace at the ends of lines, but this gets normalized when we build
    // the data instance.
    private Builder setAddressLine(int lineNum, String value) {
      if (Util.trimToNull(value) == null) {
        if (lineNum < addressLines.size()) {
          // Clearing an element that isn't the last in the list.
          addressLines.set(lineNum - 1, null);
        } else if (lineNum == addressLines.size()) {
          // Clearing the last element (remove it and clear up trailing nulls).
          addressLines.remove(lineNum - 1);
          for (int i = addressLines.size() - 1; i >= 0 && addressLines.get(i) == null; i--) {
            addressLines.remove(i);
          }
        }
      } else {
        // Padding the list with nulls if necessary.
        for (int i = addressLines.size(); i < lineNum; i++) {
          addressLines.add(null);
        }
        // Set the non-null value.
        addressLines.set(lineNum - 1, value);
      }
      return this;
    }

    /**
     * Builds an AddressData instance from the current state of the builder. A builder instance may
     * be used to build multiple data instances.
     *

     * During building the street address line information is normalized and the following will be
     * true for any build instance.
     *

     *
The order of address lines is retained relative to the builder.
     *
Empty address lines (empty strings, whitespace only or null) are removed.
     *
Remaining address lines are trimmed of whitespace.
     *

     */
    public AddressData build() {
      return new AddressData(this);
    }
  }
}


text:
from sqlalchemy import (
    Column,
    Index,
    Integer,
    Text,
    DateTime,
    ForeignKey
    )

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship)

from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class Event(Base):
    __tablename__ = 'events'
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    description = Column(Text)
    start_time = Column(DateTime)
    end_time = Column(DateTime)
    organisation_id = Column(Integer, ForeignKey('organisations.id'))
    organisation = relationship("Organisation", backref="events")

class Organisation(Base):
    __tablename__ = "organisations"

    id = Column(Integer, primary_key=True)
    name = Column(Text)
    website = Column(Text)
    primary_contact_name = Column(Text)
    primary_contact_details = Column(Text)

Index('event_index', Event.name, unique=True, mysql_length=255)


text:
package uk.co.norphos.crystallography.api.maths;

public interface Vector extends MatrixLike {

    double get(int i);

    Vector add(double[] vector);

    Vector add(Vector vector);

    Vector subtract(double[] vector);

    Vector subtract(Vector vector);

    double[] toArray();
}


text:
var gulp = require("gulp"),
  	clean = require("gulp-clean");

/*
 * config
 */
var config = {
	build: {
    	dest: "./app/build/"
    },

    importedVendorLib: {
    	dest: "./app/src/static/vendor/"
    }
};

/*
 * tasks
 */
gulp.task("cleanBuild", function() {
    return gulp.src(config.build.dest, { read: false })
        .pipe(clean({force: true}));
});

gulp.task("cleanImportedVendorLib", function() {
    return gulp.src(config.importedVendorLib.dest, { read: false })
        .pipe(clean({force: true}));
});


text:
"""Backward compatible behaviour with primary key 'Id' and upper-case field names"""

from salesforce import models
from salesforce.models import SalesforceModel

class User(SalesforceModel):
    username = models.CharField(max_length=80)
    email = models.CharField(max_length=100)
    last_name = models.CharField(max_length=80)
    first_name = models.CharField(max_length=40, null=True, blank=True)
    is_active = models.BooleanField(default=False)

class Lead(SalesforceModel):
    company = models.CharField(max_length=255)
    last_name = models.CharField(max_length=80)

    class Meta:
        db_table = 'Lead'

class Contact(SalesforceModel):
    last_name = models.CharField(max_length=80)
    owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, default=models.DefaultedOnCreate(User))

    class Meta:
        managed = True
        db_table = 'Contact'


text:
package org.apache.giraph.reducers.impl;

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

import org.apache.giraph.reducers.ReduceSameTypeOperation;
import org.apache.giraph.types.ops.DoubleTypeOps;
import org.apache.giraph.types.ops.IntTypeOps;
import org.apache.giraph.types.ops.LongTypeOps;
import org.apache.giraph.types.ops.NumericTypeOps;
import org.apache.giraph.types.ops.TypeOpsUtils;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.WritableComparable;

/**
 * Reducer for calculating min of values
 * @param <T> Value type
 */
public class MinReduce<T extends WritableComparable>
    extends ReduceSameTypeOperation<T> {
  /** DoubleWritable specialization */
  public static final MinReduce<DoubleWritable> DOUBLE =
      new MinReduce<>(DoubleTypeOps.INSTANCE);
  /** LongWritable specialization */
  public static final MinReduce<LongWritable> LONG =
      new MinReduce<>(LongTypeOps.INSTANCE);
  /** IntWritable specialization */
  public static final MinReduce<IntWritable> INT =
      new MinReduce<>(IntTypeOps.INSTANCE);

  /** Value type operations */
  private NumericTypeOps<T> typeOps;

  /** Constructor used for deserialization only */
  public MinReduce() {
  }

  /**
   * Constructor
   * @param typeOps Value type operations
   */
  public MinReduce(NumericTypeOps<T> typeOps) {
    this.typeOps = typeOps;
  }

  @Override
  public T createInitialValue() {
    return typeOps.createMaxPositiveValue();
  }

  @Override
  public T reduce(T curValue, T valueToReduce) {
    if (curValue.compareTo(valueToReduce) > 0) {
      typeOps.set(curValue, valueToReduce);
    }
    return curValue;
  }

  @Override
  public void write(DataOutput out) throws IOException {
    TypeOpsUtils.writeTypeOps(typeOps, out);
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    typeOps = TypeOpsUtils.readTypeOps(in);
  }
}


text:
'use strict';

const is = require('is');
const fs = require('fs');

function getYtPlayerConfigFromSource(src, ytplayer_config_re) {
  return new Promise((resolve, reject) => {
    try {
      if (!is.string(src)) return reject('!is.string(src)');
      else if (!is.regexp(ytplayer_config_re))
        return reject('!is.regexp(ytplayer_config_re)');

      let ytplayer_config_matches = ytplayer_config_re.exec(src);

      // console.log('ytplayer_config_matches', ytplayer_config_matches);

      // fs.writeFileSync('/home/s/dev/outs/player.html', src);

      // console.log(ytplayer_config_re);

      // process.exit();

      if (
        true ||
        (is.array(ytplayer_config_matches) && ytplayer_config_matches[1])
      )
        resolve(JSON.parse(ytplayer_config_matches[1]));
      else reject('!ytplayer_config_matches');
    } catch (err) {
      reject(err);
    }
  });
}

module.exports = getYtPlayerConfigFromSource;


text:
var kendoDatasourceHelper = (function () {
  var instance;

  function init() {
    return {
     	getNewItems: function(dataSource){
            	var modelItems = [];
            	$.each( dataSource.data(), function( i, dataItem ) {
            		if (dataItem.dirty){
            			modelItems.push(dataItem.toJSON());
            		}
				});
				if (modelItems.length == 0){
					alert("No se registran cambios");
					throw new Error("Save an empty model is not allowed.");
				}
            	return modelItems;
        }
    };

  };

  return {

    getInstance: function () {

      if ( !instance ) {
        instance = init();
      }

      return instance;
    }

  };

})();


text: export {default} from './positioning-portal'


text:
namespace Appleseed.Services.Knowledge.Model.Illumination.Services.AlchemyIlluminator
{
    using System;
    using System.Web;

    public class AlchemyAPI_TargetedSentimentParams : AlchemyAPI_BaseParams
	{

		private enum TBOOL
		{
			NONE,
			FALSE,
			TRUE
		}

		private TBOOL showSourceText;
		private string target;

		public bool isshowSourceText()
		{
			if (TBOOL.TRUE == this.showSourceText)
				return true;
			return false;
		}

		public void setShowSourceText(bool showSourceText)
		{
			if (showSourceText)
				this.showSourceText = TBOOL.TRUE;
			else
				this.showSourceText = TBOOL.FALSE;
		}

		public string getTarget()
		{
			return this.target;
		}

		public void setTarget(string target)
		{
			this.target = target;
		}

		override public String getParameterString()
		{
			String retString = base.getParameterString();

			if (this.showSourceText != TBOOL.NONE) retString += "&showSourceText=" + (this.showSourceText ==TBOOL.TRUE ? "1" : "0");
			if (this.target != null) retString += "&target=" + HttpUtility.UrlEncode(this.target);

			return retString;
		}
	}
}


text:
#pragma once

/*

Base class used for all games, all games must inherit from this

*/

#include <QtGui/QPainter>
#include <memory>
#include <functional>
#include <vector>
#include <string>
#include "entity.h"
#include "randgen.h"
#include "resources.h"
#include "object-ids.h"
#include "game-registry.h"
#include "buffer.h"

// We want all games to have same observation space. So all these
// constants here related to observation space are constants forever.
const int RES_W = 64;
const int RES_H = 64;

const int RENDER_RES = 512;

void bgr32_to_rgb888(void *dst_rgb888, void *src_bgr32, int w, int h);

class VecOptions;

enum DistributionMode {
    EasyMode = 0,
    HardMode = 1,
    ExtremeMode = 2,
    MemoryMode = 10,
};

struct StepData {
    float reward = 0.0f;
    bool done = false;
    bool level_complete = false;
};

struct GameOptions {
    bool paint_vel_info = false;
    bool use_generated_assets = false;
    bool use_monochrome_assets = false;
    bool restrict_themes = false;
    bool use_backgrounds = true;
    bool center_agent = false;
    int debug_mode = 0;
    DistributionMode distribution_mode = HardMode;
    bool use_sequential_levels = false;

    // coinrun_old
    bool use_easy_jump = false;
    int plain_assets = 0;
    int physics_mode = 0;
};

class Game {
  public:
    const std::string game_name;
    std::map<std::string, int> info_name_to_offset;

    GameOptions options;

    bool initial_reset_complete = false;
    bool grid_step = false;
    int level_seed_low = 0;
    int level_seed_high = 1;
    int game_type = 0;
    int game_n = 0;

    RandGen level_seed_rand_gen;
    RandGen rand_gen;

    StepData step_data;
    int action = 0;

    int timeout = 0;

    int current_level_seed = 0;
    int prev_level_seed = 0;
    int episodes_remaining = 0;
    bool episode_done = false;

    int last_reward_timer = 0;
    float last_reward = 0.0f;
    int default_action = 0;

    int fixed_asset_seed = 0;

    uint32_t render_buf[RES_W * RES_H];

    int cur_time = 0;

    bool is_waiting_for_step = false;

    // pointers to buffers
    int32_t *action_ptr;
    std::vector<void *> obs_bufs;
    std::vector<void *> info_bufs;
    float *reward_ptr = nullptr;
    uint8_t *first_ptr = nullptr;

    Game(std::string name);
    void step();
    void reset();
    void render_to_buf(void *buf, int w, int h, bool antialias);
    void parse_options(std::string name, VecOptions opt_vec);

    virtual ~Game() = 0;
    virtual void observe();
    virtual void game_init() = 0;
    virtual void game_reset() = 0;
    virtual void game_step() = 0;
    virtual void game_draw(QPainter &p, const QRect &rect) = 0;
    virtual void serialize(WriteBuffer *b);
    virtual void deserialize(ReadBuffer *b);

  private:
    int reset_count = 0;
    float total_reward = 0.0f;
};


text:
import os

import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def add_todo():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1MijXcz1fedvq4kT34QUQTHI_mgje-1C6m1cdYKDoOQQ'
    rangeName = 'NamedRange1'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()


text:
local L = LibStub("AceLocale-3.0"):NewLocale(..., "enUS", true)
L["announceChange"] = "Your current setting is %s. Type %s to change."
L["announceDefer"] = "%s is announcing fails."
L["announceOff"] = "Announcing fails is disabled."
L["announceSelf"] = "Announcing fails to self only."
L["announceRaid"] = "Announcing fails to raid chat."
L["help.1"] = "version %s by %s"
L["help.2"] = "Your current setting is %s. To change it, type one of:"
L["help.always"] = "announce fails to raid chat for Normal+, to self Raid Finder"
L["help.off"] = "do not announce fails"
L["help.raid"] = "announce fails to raid chat for Normal+"
L["help.self"] = "announce fails to self for Normal+"
L["fail.detonation"] = "%s has eye, %s hit the raid. A healer needed the eye to dispel the Priest's bomb."
L["fail.conduit"] = "%s has eye, %s hit the raid. Only the person with the eye can interrupt the Warden's cast."
L["fail.corruption"] = "%s has eye, %s hit %s. The Raven tank needed the eye to prevent the debuff."
L["fail.winds"] = "%s has eye for %ss during %s."
L["newerVersion"] = "Version %s is available. You're currently running version %s."
L["nobody"] = "NOBODY"

-- If you would like to translate, please do!
-- http://wow.curseforge.com/addons/iskarfails/localization/

local locale = GetLocale()
if locale == "deDE" then
  L = LibStub("AceLocale-3.0"):NewLocale(..., locale)
  L["announceChange"] = "Deine aktuelle Einstellung ist %s. Tippe %s ein, um dies zu ändern."
  L["announceDefer"] = "%s kündigt Fehler an."
  L["announceOff"] = "Fehlerankündigung ist deaktiviert."
  L["announceRaid"] = "Fehler werden in den Schlachtzugs-Chat angekündigt."
  L["announceSelf"] = "Fehlerankündigung nur zu dir selbst" -- Needs review
  L["fail.conduit"] = "%s hat das Auge, %s hat den Schlachtzug getroffen. Nur die Person mit dem Auge kann den Zauber vom Wächter unterbrechen."
  L["fail.corruption"] = "%s hat das Auge, %s hat den Schlachtzug getroffen. Der Tank des Rabens brauchte das Auge, um den Debuff zu verhindern."
  L["fail.detonation"] = "%s hat das Auge, %s hat den Schlachtzug getroffen. Ein Heiler brauchte das Auge, um die Bombe des Priesters zu bannen."
  L["fail.winds"] = "%s hat das Auge für %ss während %s." -- Needs review
  L["help.1"] = "Version %s von %s"
  L["help.2"] = "Deine aktuelle Einstellung ist %s. Um dies zu ändern, Tippe einen der:" -- Needs review
  L["help.always"] = "Fehler werden ab Normal in den Schlachtzugs-Chat angekündigt und im Schlachtzugsbrowser zu dir" -- Needs review
  L["help.off"] = "Fehler nicht ankündigen"
  L["help.raid"] = "Fehler werden auf Normal oder höher in den Schlachtzugs-Chat angekündigt"
  L["help.self"] = "Fehler werden auf Normal oder höher dir selbst angekündigt" -- Needs review
  L["newerVersion"] = "Version %s ist verfügbar. Du benutzt momentan die Version %s."
  L["nobody"] = "NIEMAND"
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>wCMF 4.0: DefaultPersistentObject Class Reference</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="A MDSD framework for building reliable, maintainable and extendable web applications with PHP">
  <meta name="keywords" content="PHP, web application framework, model driven development">
  <meta name="author" content="wemove digital solutions">
  <link rel="shortcut icon" href="theme/images/favicon.ico">

  <link href="theme/css/doxstyles.css" rel="stylesheet">

  <link href="theme/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
  <link href="theme/bootstrap3/css/font-awesome.min.css" rel="stylesheet">

  <link href="theme/js/tocify/jquery.tocify.css" rel="stylesheet">

  <link href="theme/css/syntax.css" rel="stylesheet">
  <link href="theme/css/style.css" rel="stylesheet">

          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".menu-navbar-collapse">
            Toggle navigation
          </button>
          wCMF 4.0

 Guides

Getting started

Architecture

Model

Persistence

Presentation

Configuration

Security

I18n & l10n

Tests

 API

 Code

 Support

                <input id="MSearchField" type="text" class="form-control" placeholder="Search API" name="query" onkeyup="searchBox.OnSearchFieldChange(event)">

wcmf

lib

persistence

impl

DefaultPersistentObject

Public Member Functions |
Protected Member Functions |
List of all members

DefaultPersistentObject Class Reference

Detailed Description

DefaultPersistentObject is the base class of all persistent objects.

It mainly implements an unique identifier for each instance (ObjectId), tracking of the persistent state, methods for setting and getting values as well as callback methods for lifecycle events.

Author

ingo herwig ingo@.nosp@m.wemo.nosp@m.ve.co.nosp@m.m

Definition at line 34 of file DefaultPersistentObject.php.

   Inheritance diagram for DefaultPersistentObject:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Public Member Functions

 	__construct (ObjectId $oid=null)

 	initialize (array $data)

 	getType ()

 	getMapper ()

 	getOID ()

 	setOID (ObjectId $oid)

 	getState ()

 	setState ($state)

 	delete ()

 	__clone ()

 	copyValues (PersistentObject $object, $copyPkValues=true)

 	mergeValues (PersistentObject $object)

 	clearValues ()

 	afterCreate ()

 	beforeInsert ()

 	afterInsert ()

 	afterLoad ()

 	beforeUpdate ()

 	afterUpdate ()

 	beforeDelete ()

 	afterDelete ()

 	getValue ($name)

 	setValue ($name, $value, $forceSet=false, $trackChange=true)

 	hasValue ($name)

 	removeValue ($name)

 	validateValues (Message $message)

 	validateValue ($name, $value, Message $message)

 	getChangedValues ()

 	getOriginalValues ()

 	getIndispensableObjects ()

 	getProperty ($name)

 	setProperty ($name, $value)

 	getPropertyNames ()

 	getValueProperty ($name, $property)

 	setValueProperty ($name, $property, $value)

 	getValuePropertyNames ($name)

 	getValueNames ($excludeTransient=false)

 	getDisplayValue ()

 	dump ()

 	__toString ()

 	serialize ()

 	unserialize ($serialized)

Protected Member Functions

 	setOIDInternal (ObjectId $oid, $triggerListeners)

 	setValueInternal ($name, $value)

 	validateValueAgainstValidateType ($name, $value, Message $message)

Additional Inherited Members

 Public Attributes inherited from PersistentObject

const 	STATE_CLEAN = 0

const 	STATE_DIRTY = 1

const 	STATE_NEW = 2

const 	STATE_DELETED = 3

Constructor & Destructor Documentation

          __construct
          (
          ObjectId
          $oid = null	)

Constructor.

The object will be bound to the appropriate PersistenceMapper automatically, if the PersistenceFacade knows the type. The object id is needed to extract the type. If the id parameter of the object id is a dummy id, the object is supposed to be a newly created object (

See also

ObjectId::containsDummyIds()).

Parameters

$oid	ObjectId instance (optional)

Definition at line 58 of file DefaultPersistentObject.php.

Member Function Documentation

          initialize
          (
          array
          $data	)

See also

PersistentObject::initialize()

Implements PersistentObject.

Definition at line 78 of file DefaultPersistentObject.php.

          getType
          (
          	)

See also

PersistentObject::getType()

Implements PersistentObject.

Definition at line 106 of file DefaultPersistentObject.php.

          getMapper
          (
          	)

See also

PersistentObject::getMapper()

Implements PersistentObject.

Definition at line 113 of file DefaultPersistentObject.php.

          getOID
          (
          	)

See also

PersistentObject::getOID()

Implements PersistentObject.

Definition at line 123 of file DefaultPersistentObject.php.

          setOID
          (
          ObjectId
          $oid	)

See also

PersistentObject::setOID()

Implements PersistentObject.

Definition at line 130 of file DefaultPersistentObject.php.

          setOIDInternal
          (
          ObjectId
          $oid,

          $triggerListeners

          )

protected

Set the object id of the PersistentObject.

Parameters

$oid	The PersistentObject's oid.

$triggerListeners	Boolean, whether value CahngeListeners should be notified or not

Definition at line 140 of file DefaultPersistentObject.php.

          getState
          (
          	)

See also

PersistentObject::getState()

Implements PersistentObject.

Definition at line 159 of file DefaultPersistentObject.php.

          setState
          (

          $state	)

See also

PersistentObject::setState()

Implements PersistentObject.

Definition at line 166 of file DefaultPersistentObject.php.

          delete
          (
          	)

See also

PersistentObject::delete()

Implements PersistentObject.

Definition at line 198 of file DefaultPersistentObject.php.

          __clone
          (
          	)

See also

PersistentObject::__clone()

Implements PersistentObject.

Definition at line 206 of file DefaultPersistentObject.php.

          copyValues
          (
          PersistentObject
          $object,

          $copyPkValues = true

          )

See also

PersistentObject::copyValues()

Implements PersistentObject.

Definition at line 222 of file DefaultPersistentObject.php.

          mergeValues
          (
          PersistentObject
          $object	)

See also

PersistentObject::mergeValues()

Implements PersistentObject.

Definition at line 235 of file DefaultPersistentObject.php.

          clearValues
          (
          	)

See also

PersistentObject::clearValues()

Implements PersistentObject.

Definition at line 247 of file DefaultPersistentObject.php.

          afterCreate
          (
          	)

See also

PersistentObject::afterCreate()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 276 of file DefaultPersistentObject.php.

          beforeInsert
          (
          	)

See also

PersistentObject::beforeInsert()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 282 of file DefaultPersistentObject.php.

          afterInsert
          (
          	)

See also

PersistentObject::afterInsert()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 288 of file DefaultPersistentObject.php.

          afterLoad
          (
          	)

See also

PersistentObject::afterLoad()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 294 of file DefaultPersistentObject.php.

          beforeUpdate
          (
          	)

See also

PersistentObject::beforeUpdate()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 300 of file DefaultPersistentObject.php.

          afterUpdate
          (
          	)

See also

PersistentObject::afterUpdate()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 306 of file DefaultPersistentObject.php.

          beforeDelete
          (
          	)

See also

PersistentObject::beforeDelete()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 312 of file DefaultPersistentObject.php.

          afterDelete
          (
          	)

See also

PersistentObject::afterDelete()

Note

The default implementation does nothing

Implements PersistentObject.

Definition at line 318 of file DefaultPersistentObject.php.

          getValue
          (

          $name	)

See also

PersistentObject::getValue()

Implements PersistentObject.

Definition at line 323 of file DefaultPersistentObject.php.

          setValue
          (

          $name,

          $value,

          $forceSet = false,

          $trackChange = true

          )

See also

PersistentObject::setValue()

Implements PersistentObject.

Definition at line 333 of file DefaultPersistentObject.php.

          setValueInternal
          (

          $name,

          $value

          )

protected

Internal (fast) version to set a value without any validation, state change, listener notification etc.

Parameters

$name	The name of the value

$value	The value

Definition at line 367 of file DefaultPersistentObject.php.

          hasValue
          (

          $name	)

See also

PersistentObject::hasValue()

Implements PersistentObject.

Definition at line 374 of file DefaultPersistentObject.php.

          removeValue
          (

          $name	)

See also

PersistentObject::removeValue()

Implements PersistentObject.

Definition at line 381 of file DefaultPersistentObject.php.

          validateValues
          (
          Message
          $message	)

See also

PersistentObject::validateValues()

Implements PersistentObject.

Definition at line 390 of file DefaultPersistentObject.php.

          validateValue
          (

          $name,

          $value,

          Message
          $message

          )

See also

PersistentObject::validateValue()

Implements PersistentObject.

Definition at line 410 of file DefaultPersistentObject.php.

          validateValueAgainstValidateType
          (

          $name,

          $value,

          Message
          $message

          )

protected

Check a value's value against the validation type set on it.

This method uses the validateType property of the attribute definition. Throws a ValidationException if the valud is not valid.

Parameters

$name	The name of the item to set.

$value	The value of the item.

$message	The Message instance used to provide translations.

Definition at line 422 of file DefaultPersistentObject.php.

          getChangedValues
          (
          	)

See also

PersistentObject::getChangedValues()

Implements PersistentObject.

Definition at line 447 of file DefaultPersistentObject.php.

          getOriginalValues
          (
          	)

See also

PersistentObject::getOriginalValues()

Implements PersistentObject.

Definition at line 454 of file DefaultPersistentObject.php.

          getIndispensableObjects
          (
          	)

See also

PersistentObject::getIndispensableObjects()

Implements PersistentObject.

Definition at line 461 of file DefaultPersistentObject.php.

          getProperty
          (

          $name	)

See also

PersistentObject::getProperty()

Implements PersistentObject.

Definition at line 468 of file DefaultPersistentObject.php.

          setProperty
          (

          $name,

          $value

          )

See also

PersistentObject::setProperty()

Implements PersistentObject.

Definition at line 485 of file DefaultPersistentObject.php.

          getPropertyNames
          (
          	)

See also

PersistentObject::getPropertyNames()

Implements PersistentObject.

Definition at line 495 of file DefaultPersistentObject.php.

          getValueProperty
          (

          $name,

          $property

          )

See also

PersistentObject::getValueProperty()

Implements PersistentObject.

Definition at line 503 of file DefaultPersistentObject.php.

          setValueProperty
          (

          $name,

          $property,

          $value

          )

See also

PersistentObject::setValueProperty()

Implements PersistentObject.

Definition at line 525 of file DefaultPersistentObject.php.

          getValuePropertyNames
          (

          $name	)

See also

PersistentObject::getValuePropertyNames()

Implements PersistentObject.

Definition at line 535 of file DefaultPersistentObject.php.

          getValueNames
          (

          $excludeTransient = false	)

See also

PersistentObject::getValueNames()

Implements PersistentObject.

Definition at line 550 of file DefaultPersistentObject.php.

          getDisplayValue
          (
          	)

See also

PersistentObject::getDisplayValue()

Note

Subclasses will override this for special application requirements

Implements PersistentObject.

Definition at line 569 of file DefaultPersistentObject.php.

          dump
          (
          	)

See also

PersistentObject::dump()

Implements PersistentObject.

Definition at line 576 of file DefaultPersistentObject.php.

          __toString
          (
          	)

Get a string representation of the PersistentObject.

Returns

String

Definition at line 620 of file DefaultPersistentObject.php.

          serialize
          (
          	)

Definition at line 624 of file DefaultPersistentObject.php.

          unserialize
          (

          $serialized	)

Definition at line 629 of file DefaultPersistentObject.php.

        © 2016 wemove digital solutions

          Generated on Fri Jul 15 2016 22:20:47 for wCMF by  doxygen 1.8.10


text:
<!DOCTYPE html>

    <title>About – Patricio Astudillo – Wonderlust for the interested mind</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="Wonderlust for the interested mind">
    <meta property="og:description" content="Wonderlust for the interested mind" />

    <meta name="author" content="Patricio Astudillo" />

    <meta property="og:title" content="About" />
    <meta property="twitter:title" content="About" />

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Patricio Astudillo - Wonderlust for the interested mind" href="/feed.xml" />

Patricio Astudillo

Wonderlust for the interested mind

            Blog
            About

About

Blog/pages/interesting for and from me

More Information

wonderlust …

Contact me

email@domain.com


text:
package BasicPrivilegeProfileParser;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * This class represents a parser that parses a valid xml to a list of
 * PrivilegeGroup objects
 *
 * @author LXP
 */
public class PrivilegeGroupParser {

    /**
     * Parse a bpp xml string to a list of PrivilegeGroup *
     *
     *
     * @param based64Xml
     * @return list of PrivilegeGroup
     * @throws java.io.UnsupportedEncodingException
     * @throws org.xml.sax.SAXException
     * @throws javax.xml.parsers.ParserConfigurationException
     */
    public static List<PrivilegeGroup> Parse(String based64Xml) throws UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException {
        String bppString = new String(Base64.decodeBase64(based64Xml.getBytes()), "UTF-8");
        List<PrivilegeGroup> result = new ArrayList<>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(bppString)));
        NodeList nodeList = document.getDocumentElement().getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {

            //We have encountered an <employee> tag.
            Node node = nodeList.item(i);
            if (node instanceof Element) {
                Element pElement = (Element) node;
                result.add(new PrivilegeGroup(pElement));
            }
        }
        return result;
    }

    /**
     * Convert a list of PrivilegeGroup to a json string
     *
     * @param privilegeGroups
     * @return
     */
    public static String ConvertToJsonString(List<PrivilegeGroup> privilegeGroups) {
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        return gson.toJson(privilegeGroups);
    }
}


text:
package org.apache.beam.fn.harness.state;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import com.google.common.util.concurrent.Uninterruptibles;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.CallStreamObserver;
import io.grpc.stub.StreamObserver;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateRequest;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateResponse;
import org.apache.beam.model.fnexecution.v1.BeamFnStateGrpc;
import org.apache.beam.model.pipeline.v1.Endpoints;
import org.apache.beam.sdk.fn.IdGenerators;
import org.apache.beam.sdk.fn.stream.StreamObserverFactory.StreamObserverClientFactory;
import org.apache.beam.sdk.fn.test.TestStreams;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link BeamFnStateGrpcClientCache}. */
@RunWith(JUnit4.class)
public class BeamFnStateGrpcClientCacheTest {
  private static final String SUCCESS = "SUCCESS";
  private static final String FAIL = "FAIL";
  private static final String TEST_ERROR = "TEST ERROR";
  private static final String SERVER_ERROR = "SERVER ERROR";

  private Endpoints.ApiServiceDescriptor apiServiceDescriptor;
  private ManagedChannel testChannel;
  private Server testServer;
  private BeamFnStateGrpcClientCache clientCache;
  private BlockingQueue<StreamObserver<StateResponse>> outboundServerObservers;
  private BlockingQueue<StateRequest> values;

  @Before
  public void setUp() throws Exception {
    values = new LinkedBlockingQueue<>();
    outboundServerObservers = new LinkedBlockingQueue<>();
    CallStreamObserver<StateRequest> inboundServerObserver =
        TestStreams.withOnNext(values::add).build();

    apiServiceDescriptor =
        Endpoints.ApiServiceDescriptor.newBuilder()
            .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
            .build();
    testServer = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
        .addService(new BeamFnStateGrpc.BeamFnStateImplBase() {
          @Override
          public StreamObserver<StateRequest> state(
              StreamObserver<StateResponse> outboundObserver) {
            Uninterruptibles.putUninterruptibly(outboundServerObservers, outboundObserver);
            return inboundServerObserver;
          }
        })
        .build();
    testServer.start();

    testChannel = InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();

    clientCache =
        new BeamFnStateGrpcClientCache(
            PipelineOptionsFactory.create(),
            IdGenerators.decrementingLongs(),
            (Endpoints.ApiServiceDescriptor descriptor) -> testChannel,
            this::createStreamForTest);
  }

  @After
  public void tearDown() throws Exception {
    testServer.shutdownNow();
    testChannel.shutdownNow();
  }

  @Test
  public void testCachingOfClient() throws Exception {
    assertSame(clientCache.forApiServiceDescriptor(apiServiceDescriptor),
        clientCache.forApiServiceDescriptor(apiServiceDescriptor));
    assertNotSame(clientCache.forApiServiceDescriptor(apiServiceDescriptor),
        clientCache.forApiServiceDescriptor(
            Endpoints.ApiServiceDescriptor.getDefaultInstance()));
  }

  @Test
  public void testRequestResponses() throws Exception {
    BeamFnStateClient client = clientCache.forApiServiceDescriptor(apiServiceDescriptor);

    CompletableFuture<StateResponse> successfulResponse = new CompletableFuture<>();
    CompletableFuture<StateResponse> unsuccessfulResponse = new CompletableFuture<>();

    client.handle(
        StateRequest.newBuilder().setInstructionReference(SUCCESS), successfulResponse);
    client.handle(
        StateRequest.newBuilder().setInstructionReference(FAIL), unsuccessfulResponse);

    // Wait for the client to connect.
    StreamObserver<StateResponse> outboundServerObserver = outboundServerObservers.take();
    // Ensure the client doesn't break when sent garbage.
    outboundServerObserver.onNext(StateResponse.newBuilder().setId("UNKNOWN ID").build());

    // We expect to receive and handle two requests
    handleServerRequest(outboundServerObserver, values.take());
    handleServerRequest(outboundServerObserver, values.take());

    // Ensure that the successful and unsuccessful responses were propagated.
    assertNotNull(successfulResponse.get());
    try {
      unsuccessfulResponse.get();
      fail("Expected unsuccessful response");
    } catch (ExecutionException e) {
      assertThat(e.toString(), containsString(TEST_ERROR));
    }
  }

  @Test
  public void testServerErrorCausesPendingAndFutureCallsToFail() throws Exception {
    BeamFnStateClient client = clientCache.forApiServiceDescriptor(apiServiceDescriptor);

    CompletableFuture<StateResponse> inflight = new CompletableFuture<>();
    client.handle(StateRequest.newBuilder().setInstructionReference(SUCCESS), inflight);

    // Wait for the client to connect.
    StreamObserver<StateResponse> outboundServerObserver = outboundServerObservers.take();
    // Send an error from the server.
    outboundServerObserver.onError(
        new StatusRuntimeException(Status.INTERNAL.withDescription(SERVER_ERROR)));

    try {
      inflight.get();
      fail("Expected unsuccessful response due to server error");
    } catch (ExecutionException e) {
      assertThat(e.toString(), containsString(SERVER_ERROR));
    }

    // Send a response after the client will have received an error.
    CompletableFuture<StateResponse> late = new CompletableFuture<>();
    client.handle(StateRequest.newBuilder().setInstructionReference(SUCCESS), late);

    try {
      inflight.get();
      fail("Expected unsuccessful response due to server error");
    } catch (ExecutionException e) {
      assertThat(e.toString(), containsString(SERVER_ERROR));
    }
  }

  @Test
  public void testServerCompletionCausesPendingAndFutureCallsToFail() throws Exception {
    BeamFnStateClient client = clientCache.forApiServiceDescriptor(apiServiceDescriptor);

    CompletableFuture<StateResponse> inflight = new CompletableFuture<>();
    client.handle(StateRequest.newBuilder().setInstructionReference(SUCCESS), inflight);

    // Wait for the client to connect.
    StreamObserver<StateResponse> outboundServerObserver = outboundServerObservers.take();
    // Send that the server is done.
    outboundServerObserver.onCompleted();

    try {
      inflight.get();
      fail("Expected unsuccessful response due to server completion");
    } catch (ExecutionException e) {
      assertThat(e.toString(), containsString("Server hanged up"));
    }

    // Send a response after the client will have received an error.
    CompletableFuture<StateResponse> late = new CompletableFuture<>();
    client.handle(StateRequest.newBuilder().setInstructionReference(SUCCESS), late);

    try {
      inflight.get();
      fail("Expected unsuccessful response due to server completion");
    } catch (ExecutionException e) {
      assertThat(e.toString(), containsString("Server hanged up"));
    }
  }

  private void handleServerRequest(
      StreamObserver<StateResponse> outboundObserver, StateRequest value) {
    switch (value.getInstructionReference()) {
      case SUCCESS:
        outboundObserver.onNext(StateResponse.newBuilder().setId(value.getId()).build());
        return;
      case FAIL:
        outboundObserver.onNext(StateResponse.newBuilder()
            .setId(value.getId())
            .setError(TEST_ERROR)
            .build());
        return;
      default:
        outboundObserver.onNext(StateResponse.newBuilder().setId(value.getId()).build());
        return;
    }
  }

  private <ReqT, RespT> StreamObserver<RespT> createStreamForTest(
      StreamObserverClientFactory<ReqT, RespT> clientFactory, StreamObserver<ReqT> handler) {
    return clientFactory.outboundObserverFor(handler);
  }
}


text:
"""
Copyright (c) 2014-2015 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying permission
"""

import re

from core.common import retrieve_content

__url__ = "http://osint.bambenekconsulting.com/feeds/c2-ipmasterlist.txt"
__check__ = "Master Feed"
__reference__ = "bambenekconsulting.com"

def fetch():
    retval = {}
    content = retrieve_content(__url__)

    if __check__ in content:
        for match in re.finditer(r"(?m)^([\d.]+),IP used by ([^,]+) C&C", content):
            retval[match.group(1)] = ("%s (malware)" % match.group(2).lower(), __reference__)

    return retval


text:
.. _nanokernel:

Nanokernel Services
###################

This section describes the various services provided by the nanokernel.
Unless otherwise noted, these services are available in both microkernel
applications and nanokernel applications.

.. toctree::
   :maxdepth: 1

   nanokernel_tasks.rst
   nanokernel_fibers
   nanokernel_timers
   nanokernel_synchronization
   nanokernel_data
   nanokernel_interrupts
   nanokernel_kernel_event_logger


text:
require 'spec_helper'

RSpec.describe ObjectStorage::MigrateUploadsWorker do
  let(:model_class) { Project }
  let(:uploads) { Upload.all }
  let(:to_store) { ObjectStorage::Store::REMOTE }

  def perform(uploads, store = nil)
    described_class.new.perform(uploads.ids, model_class.to_s, mounted_as, store || to_store)
  rescue ObjectStorage::MigrateUploadsWorker::Report::MigrationFailures
    # swallow
  end

  context "for AvatarUploader" do
    let!(:projects) { create_list(:project, 10, :with_avatar) }
    let(:mounted_as) { :avatar }

    before do
      stub_uploads_object_storage(AvatarUploader)
    end

    it_behaves_like "uploads migration worker"

    describe "limits N+1 queries" do
      it "to N*5" do
        query_count = ActiveRecord::QueryRecorder.new { perform(uploads) }

        more_projects = create_list(:project, 3, :with_avatar)

        expected_queries_per_migration = 5 * more_projects.count
        expect { perform(Upload.all) }.not_to exceed_query_limit(query_count).with_threshold(expected_queries_per_migration)
      end
    end
  end

  context "for FileUploader" do
    let!(:projects) { create_list(:project, 10) }
    let(:secret) { SecureRandom.hex }
    let(:mounted_as) { nil }

    def upload_file(project)
      uploader = FileUploader.new(project)
      uploader.store!(fixture_file_upload('spec/fixtures/doc_sample.txt'))
    end

    before do
      stub_uploads_object_storage(FileUploader)

      projects.map(&method(:upload_file))
    end

    it_behaves_like "uploads migration worker"

    describe "limits N+1 queries" do
      it "to N*5" do
        query_count = ActiveRecord::QueryRecorder.new { perform(uploads) }

        more_projects = create_list(:project, 3)
        more_projects.map(&method(:upload_file))

        expected_queries_per_migration = 5 * more_projects.count
        expect { perform(Upload.all) }.not_to exceed_query_limit(query_count).with_threshold(expected_queries_per_migration)
      end
    end
  end

  context 'for DesignManagement::DesignV432x230Uploader' do
    let(:model_class) { DesignManagement::Action }
    let!(:design_actions) { create_list(:design_action, 10, :with_image_v432x230) }
    let(:mounted_as) { :image_v432x230 }

    before do
      stub_uploads_object_storage(DesignManagement::DesignV432x230Uploader)
    end

    it_behaves_like 'uploads migration worker'
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestodb.benchto.driver.jdbc;

import io.prestodb.benchto.driver.IntegrationTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.sql.DataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import static org.assertj.core.api.Assertions.assertThat;

public class MultipleDataSourcesTest
        extends IntegrationTest
{
    private static final String SQL_TEST_STATEMENT = "SELECT TOP 1 1 as VAL FROM INFORMATION_SCHEMA.SYSTEM_TABLES";

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testAllDataSourcesAvailable()
            throws Exception
    {
        testDataSourceAvailable("test_datasource");
        testDataSourceAvailable("test_datasource_2");
    }

    private void testDataSourceAvailable(String dataSourceName)
            throws SQLException
    {
        DataSource dataSource = applicationContext.getBean(dataSourceName, DataSource.class);
        try (Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(SQL_TEST_STATEMENT)) {
            int rowsCount = 0;
            while (resultSet.next()) {
                rowsCount++;
            }
            assertThat(rowsCount).isEqualTo(1);
        }
    }
}


text:
package org.apache.syncope.core.persistence.jpa.entity;

import org.apache.syncope.common.lib.types.AttributableType;
import org.apache.syncope.core.persistence.api.entity.Attributable;
import org.apache.syncope.core.persistence.api.entity.AttributableUtil;
import org.apache.syncope.core.persistence.api.entity.AttributableUtilFactory;
import org.apache.syncope.core.persistence.api.entity.conf.Conf;
import org.apache.syncope.core.persistence.api.entity.membership.Membership;
import org.apache.syncope.core.persistence.api.entity.role.Role;
import org.apache.syncope.core.persistence.api.entity.user.User;
import org.identityconnectors.framework.common.objects.ObjectClass;
import org.springframework.stereotype.Component;

@Component
public class JPAttributableUtilFactory implements AttributableUtilFactory {

    @Override
    public AttributableUtil getInstance(final AttributableType type) {
        return new JPAAttributableUtil(type);
    }

    @Override
    public AttributableUtil getInstance(final String attributableType) {
        return new JPAAttributableUtil(AttributableType.valueOf(attributableType));
    }

    @Override
    public AttributableUtil getInstance(final ObjectClass objectClass) {
        AttributableType type = null;
        if (ObjectClass.ACCOUNT.equals(objectClass)) {
            type = AttributableType.USER;
        }
        if (ObjectClass.GROUP.equals(objectClass)) {
            type = AttributableType.ROLE;
        }

        if (type == null) {
            throw new IllegalArgumentException("ObjectClass not supported: " + objectClass);
        }

        return new JPAAttributableUtil(type);
    }

    @Override
    public AttributableUtil getInstance(final Attributable<?, ?, ?> attributable) {
        AttributableType type = null;
        if (attributable instanceof User) {
            type = AttributableType.USER;
        }
        if (attributable instanceof Role) {
            type = AttributableType.ROLE;
        }
        if (attributable instanceof Membership) {
            type = AttributableType.MEMBERSHIP;
        }
        if (attributable instanceof Conf) {
            type = AttributableType.CONFIGURATION;
        }

        if (type == null) {
            throw new IllegalArgumentException("Attributable type not supported: " + attributable.getClass().getName());
        }

        return new JPAAttributableUtil(type);
    }

}


text:
"""\
PyMzn can be configured with custom executable paths and other variables.
Configuration is done via the ``pymzn.config`` object. For instance:

.. code-block:: python3

    import pymzn
    pymzn.config.set('minizinc', 'path/to/minizinc')

The configurable properties used by PyMzn are the following:

 * **minizinc**: Path to the minizinc executable;
 * **solver**: Solver instance to use when calling pymzn.minizinc;
 * **solver_args**: Arguments to pass to the solver when calling pymzn.minizinc;
 * **args**: Additional arguments to pass to the template engine;
 * **include**: List of search paths to include in all minizinc calls;
 * **keep**: Overrides the keep flag of all minizinc calls;
 * **dzn_width**: The horizontal character limit for dzn files;
   This property is used to wrap long dzn statements when writing dzn files.
   This property is also used in the minizinc function as a limit to decide
   whether to write the inline data into a file.

One can also set custom properties to be used for custom solvers.

The configuration of PyMzn can be made permanent by using the ``dump`` function
of the ``config`` object:

.. code-block:: python3

    pymzn.config.dump()

This operation, as well as loading the saved configuration file, requires the
``appdirs`` and ``pyyaml`` libraries to be installed on your system.

Debug
-----

PyMzn can also be set to print debugging messages on standard output via:

.. code-block:: python3

    pymzn.debug()

This function is meant to be used in interactive sessions or in
applications that do not configure the ``logging`` library. If you configure the
``logging`` library in your application, then PyMzn will print logging messages
as well. To disable debugging messages you can then call:

.. code-block:: python3

    pymzn.debug(False)

"""

import os

class Config(dict):

    _defaults = {
        'minizinc': 'minizinc',
        'dzn_width': 70
    }

    def __init__(self, **kwargs):
        super().__init__(**{**Config._defaults, **kwargs})

        try:
            import yaml
            cfg_file = self._cfg_file()
            if cfg_file and os.path.isfile(cfg_file):
                with open(cfg_file) as f:
                    _config = yaml.load(f)
                self.update(_config)
        except ImportError:
            pass

    def __setattr__(self, key, value):
        self[key] = value

    def __dir__(self):
        return self.keys()

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(key)

    def __setstate__(self, state):
        pass

    def _cfg_file(self):
        try:
            import appdirs
            return os.path.join(appdirs.user_config_dir(__name__), 'config.yml')
        except ImportError:
            return None

    def dump(self):
        """Writes the changes to the configuration file."""
        try:
            import yaml
            cfg_file = self._cfg_file()
            cfg_dir, __ = os.path.split(cfg_file)
            os.makedirs(cfg_dir, exist_ok=True)
            with open(cfg_file, 'w') as f:
                yaml.dump(self, f)
        except ImportError as err:
            raise RuntimeError(
                'Cannot dump the configuration settings to file. You need to '
                'install the necessary dependencies (pyyaml, appdirs).'
            ) from err

config = Config()


text:
[![Build Status](https://travis-ci.org/ToshUxanoff/P2P-Chat.svg?branch=master)](https://travis-ci.org/ToshUxanoff/P2P-Chat)

 - [x] 1. Added Peer-Server and Peer-Peer interaction. Peers can send message to each other and get information about another peers from InfoServer.
 - [x] 2. Added smart pointers.
 - [x] 3. Added "Grasshopper" encryption.
 - [x] 4. Added Diffie-Helman mechanism for keys exchange.
 - [x] 5. Added Issue creator