text:
<?php

class CoDashboardWidget extends AppModel {
  // Define class name for cake
  public $name = "CoDashboardWidget";

  // Current schema version for API
  public $version = "1.0";

  // Add behaviors
  public $actsAs = array('Containable', 'Changelog' => array('priority' => 5));

  // Association rules from this model to other models
  public $belongsTo = array(
    "CoDashboard"
  );

  public $hasManyPlugins = array(
    "dashboardwidget" => array(
      'coreModelFormat' => 'Co%s'
    )
  );

  // Default display field for cake generated views
  public $displayField = "CoDashboardWidget.description";

  // Default ordering for find operations
  public $order = array("CoDashboardWidget.ordr");

  // Validation rules for table elements
  public $validate = array(
    'co_dashboard_id' => array(
      'rule' => 'numeric',
      'required' => true,
      'allowEmpty' => false
    ),
    'description' => array(
      'rule' => array('validateInput'),
      'required' => true,
      'allowEmpty' => false
    ),
    'plugin' => array(
      'rule' => array('validateInput'),
      'required' => true,
      'allowEmpty' => false
    ),
    'status' => array(
      'rule' => array('inList', array(SuspendableStatusEnum::Active,
                                      SuspendableStatusEnum::Suspended)),
      'required' => true,
      'allowEmpty' => false
    ),
    'ordr' => array(
      'rule' => 'numeric',
      'required' => false,
      'allowEmpty' => true
    )
  );

  public $_targetid = null;

  /**
   * Actions to take after a save operation is executed.
   *
   * @since  COmanage Registry v3.2.0
   * @param  boolean $created True if a new record was created (rather than update)
   * @param  array   $options As passed into Model::save()
   */

  public function afterSave($created, $options = array()) {
    if($created) {
      // We prefix a "Co" since this is a CO oriented plugin, but maybe the naming
      // should be cleaned up as part of v4.0.0. (CO-1593)
      $modelName = "Co" . $this->data['CoDashboardWidget']['plugin'];

      $target = array();
      $target[$modelName]['co_dashboard_widget_id'] = $this->data['CoDashboardWidget']['id'];

      // We need to disable validation since we want to create an empty row
      if(!$this->$modelName->save($target, false)) {
        $this->_rollback();

        return;
      }

      $this->_targetid = $this->$modelName->id;
    }

    $this->_commit();

    return;
  }

  /**
   * Actions to take before a save operation is executed.
   *
   * @since  COmanage Registry v3.2.0
   */

  public function beforeSave($options = array()) {
    // Start a transaction -- we'll commit in afterSave.
    // This is primarily for add(), since we want to create the plugin's record.

    $this->_begin();

    if(!empty($this->data['CoDashboardWidget']['co_dashboard_id'])
       && empty($this->data['CoDashboardWidget']['ordr'])) {
      // Find the current high value and add one
      $n = 1;

      $args = array();
      $args['fields'][] = "MAX(ordr) as m";
      $args['conditions']['CoDashboardWidget.co_dashboard_id'] = $this->data['CoDashboardWidget']['co_dashboard_id'];
      $args['order'][] = "m";

      $o = $this->find('first', $args);

      if(!empty($o[0]['m'])) {
        $n = $o[0]['m'] + 1;
      }

      $this->data['CoDashboardWidget']['ordr'] = $n;
    }

    return true;
  }

  /**
   * Obtain the CO ID for a record, overriding AppModel behavior.
   *
   * @since  COmanage Registry v3.2.0
   * @param  integer Record to retrieve for
   * @return integer Corresponding CO ID, or NULL if record has no corresponding CO ID
   * @throws InvalidArgumentException
   * @throws RunTimeException
   */

  public function findCoForRecord($id) {
    // Dashboard Widgets will refer to a Dashboards

    $args = array();
    $args['conditions'][$this->alias.'.id'] = $id;
    $args['contain'][] = 'CoDashboard';

    $codw = $this->find('first', $args);

    if(!empty($codw['CoDashboard']['co_id'])) {
      return $codw['CoDashboard']['co_id'];
    } else {
      return parent::findCoForRecord($id);
    }
  }
}


text:
package com.sequenceiq.cloudbreak.controller.validation.stack;

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

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.cloud.model.StackParamValidation;
import com.sequenceiq.cloudbreak.controller.BadRequestException;

@Component
public class ParametersRequiredValidator implements ParameterValidator {

    @Override
    public <O, E extends StackParamValidation> void validate(Map<String, O> parameters, List<E> paramsList) {
        for (E param : paramsList) {
            if (Boolean.TRUE.equals(param.getRequired()) && !parameters.containsKey(param.getName())) {
                throw new BadRequestException(String.format("%s is required.", param.getName()));
            }
        }
    }

    @Override
    public ValidatorType getValidatorType() {
        return ValidatorType.REQUIRED;
    }

}

redpajama_set_name: RedPajamaGithub


text:
define(['jquery', 'oae.core'], function($, oae) {

    return function(uid) {

        // The widget container
        var $rootel = $('#' + uid);

        /**
         * Reset the widget to its original state when the modal dialog is closed
         */
        var setUpReset = function() {
            $('#creategroup-modal').on('hidden.bs.modal', function() {
                // Reset the form
                var $form = $('#creategroup-form', $rootel);
                $form[0].reset();
                oae.api.util.validation().clear($form);
            });
        };

        /**
         * Initialize the visibility options and bind an event listener to the
         * change event of the radio group
         */
        var setUpVisibility = function() {
            oae.api.util.template().render($('#creategroup-visibility-template', $rootel), {
                'visibility': oae.api.config.getValue('oae-principals', 'group', 'visibility')
            }, $('#creategroup-visibility-container', $rootel));

            $rootel.on('change', '.oae-large-options-container input[type="radio"]', function() {
                $('.oae-large-options-container label', $rootel).removeClass('checked');
                $(this).parents('label').addClass('checked');
            });
        };

        /**
         * Create the group. When the group has been created successfully, the user will be redirected
         * to the created group
         */
        var createGroup = function() {
            // Disable the form
            $('#creategroup-form *', $rootel).prop('disabled', true);

            // Create the group
            var displayName = $('#creategroup-name', $rootel).val();
            var visibility = $('.oae-large-options-container input[type="radio"]:checked', $rootel).val();
            oae.api.group.createGroup(displayName, '', visibility, null, [], [], function(err, data) {
                if (!err) {
                    // Redirect to the members page so users can start adding member straight away
                    // instead of showing an empty activity feed
                    window.location = data.profilePath + '/members';
                } else {
                    // Re-enable the form
                    $('#creategroup-form *', $rootel).prop('disabled', false);

                    oae.api.util.notification(
                        oae.api.i18n.translate('__MSG__GROUP_NOT_CREATED__', 'creategroup'),
                        oae.api.i18n.translate('__MSG__GROUP_COULD_NOT_BE_CREATED__', 'creategroup'),
                        'error');
                }
            });
        };

        /**
         * Initialize the create group form and validation
         */
        var setUpValidation = function() {
            oae.api.util.validation().validate($('#creategroup-form', $rootel), {
                'submitHandler': createGroup
            });
        };

        /**
         * Initialize the create group modal dialog
         */
        var setUpCreateGroupModal = function() {
            $(document).on('click', '.oae-trigger-creategroup', function() {
                setUpVisibility();
                $('#creategroup-modal', $rootel).modal({
                    'backdrop': 'static'
                });
            });

            $('#creategroup-modal', $rootel).on('shown.bs.modal', function () {
                // Set focus to the group name field
                $('#creategroup-name', $rootel).focus();
            });
        };

        setUpValidation();
        setUpReset();
        setUpCreateGroupModal();

    };
});


text:
import colorsys
import itertools

from cachecow.decorators import cached_function
from django.db import models
from django.db.models import Q

from canvas.models import BaseCanvasModel
from canvas import json, bgwork
from canvas.redis_models import redis, RedisSet
from drawquest import knobs
from drawquest.activities import NewColorAlertActivity
from drawquest.apps.drawquest_auth.models import User
from drawquest.apps.push_notifications.models import push_notification
from drawquest.shop_utils import ShopMixin

DEFAULT_COLOR_COST = 10

def _legacy_palette_names(user):
    return [palette.name for palette in user.redis.palettes]

class ColorPack(BaseCanvasModel, ShopMixin):
    owners = models.ManyToManyField(User)

    colors = models.ManyToManyField('Color')

    ordinal = models.IntegerField()

    label = models.CharField(max_length=50, blank=False, db_index=False)
    cost = models.IntegerField(blank=False)
    is_for_sale = models.BooleanField(default=False)
    is_new = models.BooleanField(default=True)
    sale_text = models.CharField(max_length=50, blank=True, db_index=False)

    legacy_palette_name = models.CharField(max_length=20, blank=True, unique=True)

    class Meta(object):
        ordering = ['ordinal']

    @classmethod
    def visible_in_shop(cls, **kwargs):
        return cls.objects.filter(is_for_sale=True)

    @classmethod
    def for_user(cls, user):
        filter_query = Q(owners=user)

        if user.is_authenticated():
            palette_names = _legacy_palette_names(user)

            if palette_names:
                filter_query |= Q(legacy_palette_name__in=palette_names)

        return cls.objects.filter(filter_query)

    def to_client(self, viewer=None):
        colors = list(self.colors.all())

        if viewer is not None and viewer.is_authenticated():
            self._add_owned_by_viewer_field(Color, colors, viewer)

        ret = {
            'id': self.id,
            'label': self.label,
            'colors': colors,
            'cost': self.cost,
            'is_for_sale': self.is_for_sale,
            'is_new': self.is_for_sale,
            'sale_text': self.sale_text,
        }

        if hasattr(self, 'owned_by_viewer'):
            ret['owned_by_viewer'] = self.owned_by_viewer

            if viewer is not None:
                viewer_color_ids = Color.objects.filter(owners=viewer).values_list('id', flat=True)

                if (not self.owned_by_viewer
                        and all(color.id in viewer_color_ids for color in colors)):
                    ret['owned_by_viewer'] = True

        if ret.get('owned_by_viewer'):
            ret['is_new'] = False

        return ret

class Color(BaseCanvasModel, ShopMixin):
    owned_by_default = models.BooleanField(default=False, blank=True)
    owners = models.ManyToManyField(User)

    red   = models.IntegerField(blank=False)
    green = models.IntegerField(blank=False)
    blue  = models.IntegerField(blank=False)

    ordinal = models.IntegerField()

    label = models.CharField(max_length=50, blank=False, db_index=False)
    cost = models.IntegerField(blank=True, null=True)
    is_for_sale = models.BooleanField(default=False, blank=True)
    is_new = models.BooleanField(default=True, blank=True)

    class Meta(object):
        ordering = ['ordinal']

    #@cached_function(timeout=td(days=14), key=[
    #    ['user_colors', 'v1'],
    #    lambda username: username,
    #])
    #@classmethod
    #def _ids_for_user(cls, user):

    @classmethod
    def for_user(cls, user):
        queries = [cls.objects.filter(owned_by_default=True)]

        if user.is_authenticated():
            queries.append(cls.objects.filter(owners=user))
            queries.append(cls.objects.filter(colorpack__owners=user))

            palette_names = _legacy_palette_names(user)

            if palette_names:
                queries.append(cls.objects.filter(colorpack__legacy_palette_name__in=palette_names))

        ids = set(itertools.chain.from_iterable(list(q.values_list('id', flat=True)) for q in queries))

        return list(sorted(cls.objects.in_bulk_list(ids), key=lambda color: color.ordinal))

    @classmethod
    def includable_in_color_pack(cls):
        return cls.objects.filter(is_for_sale=True)

    @classmethod
    def visible_in_shop(cls, **kwargs):
        return cls.objects.filter(Q(is_for_sale=True) | Q(owned_by_default=True))

    def light_checkmark(self):
        _, lightness, _ = colorsys.rgb_to_hls(self.red / 255., self.green / 255., self.blue / 255.)
        return lightness < knobs.COLOR_CHECKMARK_LUMINOSITY_THRESHOLD

    def to_client(self, **kwargs):
        ret = {
            'id': self.id,
            'label': self.label,
            'rgb': (self.red, self.green, self.blue),
            'cost': self.cost,
            'is_for_sale': self.is_for_sale,
            'is_new': self.is_new,
            'light_checkmark': self.light_checkmark(),
            'owned_by_default': self.owned_by_default,
        }

        if self.owned_by_default:
            ret['owned_by_viewer'] = True
        elif hasattr(self, 'owned_by_viewer'):
            ret['owned_by_viewer'] = self.owned_by_viewer

        if ret.get('owned_by_viewer'):
            ret['is_new'] = False

        return ret

def new_color_alert(message, color_packs_header, colors_header):
    version = int(redis.incr('color_alert_version'))

    push_notification('new_color_alert', message,
                      extra_metadata={'color_alert_version': version})

    activity_item = NewColorAlertActivity.with_message(message, version)

    @bgwork.defer
    def broadcast_to_activity_streams():
        for user in User.objects.all():
            user.redis.activity_stream.push(activity_item)
            user.redis.iphone_activity_stream.push(activity_item)

#
#
# LEGACY:
#
#

class LegacyColor(object):
    def __init__(self, rgb=None, index=None, cost=DEFAULT_COLOR_COST):
        self.rgb = rgb
        self.index = index
        self.cost = cost

    def to_client(self, **kwargs):
        ret = {
            'rgb': self.rgb,
            'cost': self.cost,
        }

        if self.index is not None:
            ret['index'] = self.index

        return ret

class Palette(object):
    def __init__(self, id_, name, human_readable_name, cost, colors, min_app_version=None):
        """
        `colors` is a list of Color instances.
        """
        self.id = id_
        self.name = name
        self.human_readable_name = human_readable_name
        self.colors = colors
        self.cost = cost
        self.min_app_version = min_app_version

    def __repr__(self):
        return self.name

    def available_to_app_version(self, version):
        if self.min_app_version is None:
            return True

        if version is None:
            return False

        if isinstance(version, basestring):
            version = tuple(int(v) for v in version.split('.'))

        return self.min_app_version <= version

    def to_client(self, **kwargs):
        return {
            'name': self.name,
            'human_readable_name': self.human_readable_name,
            'colors': self.colors,
            'cost': self.cost,
        }

def _colors(*rgbs):
    return [LegacyColor(rgb, index=idx) for (idx, rgb) in rgbs]

DEFAULT_PALETTE = Palette(0, 'default', 'Default', 0,
                          _colors(
                              (390,   (255,255,255)),
                              (410,   (184,182,181)),
                              ( 10,   (74,74,74)),
                              (180,   (108,214,116)),
                              (140,   (255,228,92)),
                              (120,   (248,172,85)),
                              ( 60,   (233,90,92)),
                              (340,   (124,130,255)),
                              (230,   (134,213,255)),
                              (375,   (255,228,177)),
                              (200,   (36,113,247)),
                              (355,   (156,103,95)),
                          ))

PALETTE_COST = 50

_legacy_purchasable_palettes = [
    Palette(8, 'camo', 'Camo', PALETTE_COST,
            _colors(
                (356,     (180,152,115)),
                (357,     (163,107,62)),
                (171,     (107,127,53)),
                (351,     (109,75,47)),
            ), min_app_version=(1,0,3,)),
    Palette(9, 'day_glowz', 'Day Glowz', PALETTE_COST,
            _colors(
                (141,     (255,253,69)),
                (185,     (0,255,48)),
                (245,     (0,255,210)),
                (335,     (255,9,235)),
            ), min_app_version=(1,0,3,)),
    Palette(1, 'vintage_rainbow', 'Vintage Rainbow', PALETTE_COST,
            _colors(
                ( 60,     (163,53,14)),
                (100,     (242,136,0)),
                (150,     (24,200,38)),
                (220,     (44,154,213)),
                (300,     (136,60,237))
            )),
    Palette(2, 'winter_hues', 'Winter Hues', PALETTE_COST,
            _colors(
                (280,     (221,251,253)),
                (400,     (239,239,239)),
                (195,     (206,225,214)),
                (170,     (59,121,77)),
                ( 50,     (118,0,0)),
            )),
    Palette(3, 'candy', 'Candy', PALETTE_COST,
            _colors(
                ( 80,     (254,67,101)),
                ( 90,     (255,171,187)),
                (190,     (150,255,171)),
                (240,     (18,238,255)),
            )),
    Palette(4, 'humane', 'Humane', PALETTE_COST,
            _colors(
                (380,     (255,233,215)),
                (370,     (255,224,214)),
                (360,     (241,189,171)),
                (350,     (87,37,30)),
            )),
    Palette(5, 'dawn', 'Dawn', PALETTE_COST,
            _colors(
                (320,     (91,35,105)),
                (330,     (161,28,71)),
                ( 40,     (235,30,37)),
                (110,     (255,161,0)),
                (130,     (255,227,0)),
            )),
    Palette(6, 'sky_shades', 'Sky Shades', PALETTE_COST,
            _colors(
                (210,     (30,66,176)),
                (250,     (139,220,255)),
                (270,     (212,242,255)),
                (260,     (182,216,230)),
            )),
    Palette(7, 'midnight', 'Midnight', PALETTE_COST,
            _colors(
                (420,     (0,0,0)),
                (205,     (2,14,106)),
                (310,     (50,2,85)),
                (160,     (8,51,55)),
                (145,     (255,254,222)),
            )),
]

all_palettes = _legacy_purchasable_palettes + [DEFAULT_PALETTE]

def legacy_purchasable_palettes(app_version=None):
    return [palette for palette in _legacy_purchasable_palettes
            if palette.available_to_app_version(app_version)]

_palette_names = dict((palette.name, palette) for palette in _legacy_purchasable_palettes + [DEFAULT_PALETTE])
_palette_ids = dict((palette.id, palette) for palette in _legacy_purchasable_palettes + [DEFAULT_PALETTE])

def palettes_hash():
    """ Returns the sum of all RGB values in all palettes. """
    return sum([sum(p.rgb) for p in all_palettes()])

def get_palette_by_id(id_):
    if isinstance(id_, basestring):
        id_ = int(id_)

    return _palette_ids[id_]

def user_palettes(user):
    if user.is_authenticated():
        return user.redis.palettes

    return UserPalettes()

def get_palette_by_name(name):
    return _palette_names[name]

class UserPalettes(object):
    def __init__(self, user_id=None):
        self.user_id = user_id

        self._palettes = None

        if user_id:
            self._palettes = RedisSet('user:{}:palettes'.format(user_id))

    def __iter__(self):
        yield DEFAULT_PALETTE

        if self._palettes:
            for palette in self._palettes.smembers():
                yield get_palette_by_id(palette)

    def __contains__(self, palette):
        if palette.id == DEFAULT_PALETTE.id:
            return True

        return self._palettes and palette.id in self._palettes

    def to_client(self, **kwargs):
        return [palette for palette in self]

    def unlock(self, palette):
        if not self.user_id:
            raise TypeError("Cannot unlock a palette for a logged-out user.")

        if isinstance(palette, basestring):
            palette = get_palette_by_name(name)

        if palette.id == DEFAULT_PALETTE.id:
            return

        self._palettes.sadd(palette.id)


text:
=========
Community
=========

Use these channels to communicate about the project.

Mailing list
============

The **user** mailing list is general discussion and support list for
Gunicorn users.

  * To **subscribe**, send an email to `user+subscribe@gunicorn.org
    <mailto:user+subscribe@gunicorn.org>`_
  * To **unsubscribe**, send an email to `user+unsubscribe@gunicorn.org
    <mailto:user+unsubscribe@gunicorn.org>`_
  * Finally, to post a message to the list use the address to
    `user@gunicorn.org <mailto:user@gunicorn.org>`_

The archive for this list can also be `browsed online
<http://lists.gunicorn.org/user>`_ .

Irc
===

The Gunicorn channel is on the `Freenode <http://freenode.net/>`_ IRC
network. You can chat with other on `#gunicorn channel <http://webchat.freenode.net/?channels=gunicorn>`_.

Issue Tracking
==============

Bug reports, enhancement requests and tasks generally go in the `Github
issue tracker <http://github.com/benoitc/gunicorn/issues>`_.


text:
function [mrQ,WFfile,CalibrationVal] = mrQ_WF(mrQ,dataDir,T1file,PDfile,Gainfile,B1file,saveoutput)
% [mrQ,WFfile,CalibrationVal] = mrQ_WF(mrQ,dataDir,T1file,PDfile,Gainfile,B1file);
%
% This function calculates the constant deviation of the PD. Since some
% flip angles have higher noise than others, the function finds the flip
% angles with the highest signal of the raw aligned data within the CSF (as
% the highest signal should reflect the highest SNR). Then, it creates an
% ROI which is the CSF only within a limited area around the ventricles,
% while excluding voxels with outliers in PD or in the raw data. Next, PD
% is calculated in the ROI, and assuming its value to be 1, the correction
% constant of the PD, and applies that constant to the PD image to create a
% WF map.
%

%  ~INPUT~
%            mrQ:     The mrQ structure
%        dataDir:     Where the structure with the raw data is located.
%                            (Default is mrQ.spgr_initDir)
%         T1file:     The path to the T1 map. This is used to create the
%                            CSF ROI. (Default is using mrQ_get_T1M0_files)
%         PDfile:     The path to the PD map.  (Default is opt.PDfile)
%       Gainfile:     The path to a Gain map. This is used for the PD
%                           calculation. The gain is defined differently,
%                           depending on the M0 calculation (if it's a
%                           multi-coil fit, then we take a different map)
%         B1file:     The path to a B1 map. This will be used to correct
%                     the FA value. (Default is mrQ.B1FileName)
%        saveoutput   true(defult) to save output
%
%
%  ~OUTPUT~
%            mrQ:
%         WFfile:
% CalibrationVal:
%
%
% (C) Mezer lab, the Hebrew University of Jerusalem, Israel
%   2015

%% I : check input
if notDefined('mrQ');
    mrQ = [];
end

if notDefined('dataDir');
    dataDir = mrQ.spgr_initDir;
end

if notDefined('T1file')
    [ T1file,~,~]=mrQ_get_T1M0_files(mrQ,1,0,0);
end
T1=readFileNifti(T1file); T1=T1.data;

if notDefined('PDfile')
    load(mrQ.opt_logname);
    PDfile=opt.PDfile;
end
PD=readFileNifti(PDfile);PD=PD.data;

if notDefined('B1file')
    B1file=mrQ.B1FileName;
end

if notDefined('saveoutput')
    saveoutput=true;
end
 B1=readFileNifti(B1file);B1=double(B1.data);

 if notDefined('Gainfile')
        load(mrQ.opt_logname);
        Gainfile=opt.Gainfile;
end
Gain=readFileNifti(Gainfile); Gain=Gain.data;

% currently, flipangle is chosen based on signal within CSF.
%  if instead it would be decided based on signal with WM, that we would
%  need a brainmask:

% if notDefined('BMfile')
%     BMfile= mrQ.BrainMask;
% end
% BM=readFileNifti(BMfile); BM=BM.data;

%% II. Load aligned raw data

% next we load the file that contains the aligned raw data
% this file contains: xform, mmPerVox, and the struct 's'
% s.flipAngle contains the flipngle, and s.imData the data.
outFile  = fullfile(dataDir,'dat_aligned.mat'); %without coilWeights data
disp(['Loading aligned data from ' outFile '...']);
load(outFile);

%% III. find area of high T1=[4 - 5]  around the vetricles

WFmask=ones(size(T1));

% clip around the ventricals:
if notDefined('boxsize')
    boxsize(1)=30;
    boxsize(2)=40;
    boxsize(3)=20;
end
sz=size(WFmask); szH=round(sz./2);
XX=boxsize(1)./round(mmPerVox(1));
YY=boxsize(2)./round(mmPerVox(2));
ZZ=boxsize(3)./round(mmPerVox(3));

WFmask(szH(1)+XX:end,:,:)=0;
WFmask(1:szH(1)-XX,:,:)=0;

WFmask(:,1:szH(2)-YY,:)=0;
WFmask(:,szH(2)+YY:end,:,:)=0;

WFmask(:,:,1:szH(3)-ZZ)=0;
WFmask(:,:,szH(3)+ZZ:end)=0;

% find areas within the ventricles area with high value of T1 (4.2-4.7)
%WFmask1=WFmask;
WFmask= WFmask & T1<=4.7 & T1>=4.2;

%% IV. data for WF:
% % loop over raw (aligned and combined) data and find the flip angle(s) with
% % the best SNR. it is hard to measure noise. so we will use the signal in WM
% % as a reference because it's a place with good signal across flip angles)

for ii=1:length(s)
%     subplot(2,2,ii); hist(s(ii).imData(WFmask),100), title(num2str(s(ii).flipAngle))
    CSF_Sig(ii)=median(s(ii).imData(WFmask));
end

[~,SelectedFA]=(max(CSF_Sig));

%%

%  Instead of finding the best FA within CSF, another option is using WM
%  ROI,
% %     WMmask=?
% WMmask=ones(size(T1));
% WMmask(T1<0.7)=0;
% WMmask(T1>1.1)=0;
% WMmask=WMmask & BM;
%
% for ii=1:length(s)
%
%     rawDat=s(ii).imData;
%
%     %     per file??
%     %     mean?
%
%      WM_Sig(ii)=median(s(ii).imData(WMmask));

% end
%
% FAloc=find(WMdata==max(WMdata));

%% V. data for WF:

datForPD=s(SelectedFA).imData;
TR=s(SelectedFA).TR;
fa=s(SelectedFA).flipAngle;
  if mrQ.PDfit_Method==2 || mrQ.PDfit_Method==3

        gainField=['Align',num2str(fa),'deg'];
        datafile=mrQ.MultiCoilSummedFiles.(gainField);
        datForPD=readFileNifti(datafile);datForPD=double(datForPD.data);
        % another way to do this is to make sure the M0file saved in the
        % opt is the aligned combined file in the right 2_2_2 resolution.
  end

%% VI : exclude M0 outliers in the ROI

WFmask=WFmask & PD<prctile(PD(WFmask),99) & PD>prctile(PD(WFmask),1) & datForPD< prctile(datForPD(WFmask),99) &  datForPD>prctile(datForPD(WFmask),1);

%% VII. calculate PD
% calculate  PD within the selected ROI and flip angle(s) (using the SPGR
% equation, T1, and gain

% [note gain for multi coil is define for the sum of multi coils, and for
% the combine as arrived from the scanner])

% calculate PD for the FA with the best Signal

% change FA into radians
fa = (fa.*B1)./180.*pi;

% calculate PD assuming we're in CSF (so T1 is 4300ms)
PDcsf=datForPD./(Gain.* ( (1-exp(-TR./4300)).*sin(fa)./(1-exp(-TR./4300).*cos(fa))));

%% VIII. scale this roi to have pd of 1. --> this is our global scale

[csfValues, csfDensity]= ksdensity(PDcsf((WFmask)), [min(PDcsf((WFmask))):0.001:max(PDcsf((WFmask)))] ); % figure;plot(csfDensity,csfValues)
CalibrationVal= csfDensity(csfValues==max(csfValues)); % CalibrationVal=median(PDcsf(WFmask));
CalibrationVal=1./CalibrationVal;

%% IX. apply to PD images to make WFfile --> save
if saveoutput
WF=PD.*CalibrationVal(1);

WFfile=fullfile(dataDir,'WF_map.nii.gz');
dtiWriteNiftiWrapper(WF,xform,WFfile);

mrQ.WFfile=WFfile;
mrQ.ScalePD_2_WF=CalibrationVal;

 save(mrQ.name,'mrQ');
else
    WFfile=[];
end


text: python tokenize.py <$1 >output.txt


text:
MMDB_s *
get_handle(void);

// function to give to vcl
void
close_mmdb(void *);

// function to open the maxmind db once
int
open_mmdb(MMDB_s *);

// function to get a value from the returned mmdb lookup
char *
get_value(MMDB_lookup_result_s *, const char **);

char *
geo_lookup(MMDB_s *const mmdb_handle, const char *ipstr, const char **lookup_path);

// a utility function. Suppose you have an IP that you tought failed
// you can run this to see what came back from the maxmind db
// lookup
void
dump_failed_lookup(MMDB_s *const mmdb_handle, const char *ipstr, const char *file_to_write_to);

// lookup an NYT weather code from ip address
char *
geo_lookup_weather(MMDB_s *const mmdb_handle, const char *ipstr, int use_default);

// lookup a location from ip address
char *
geo_lookup_location(MMDB_s *const mmdb_handle, const char *ipstr);

// lookup a timezone from ip address
char *
geo_lookup_timezone(MMDB_s *const mmdb_handle, const char *ipstr, int use_default);

// the cookie header can be too big for regusub or regusuball so we need
// a function to pull a cookie value from the Cookie header. Here is an
// example of whour cookie can look like:
// NYT_W2=New%20YorkNYUS; abc=ChicagoILUS|London--UK|Los%20AngelesCAUS
//
// it can be anywere in the cookie string, front, middle blank or not
// even existant. because regsub and regsuball bail when the cookie
// string is larger than 5655, I created this function.
char *
get_weather_code_from_cookie(const char *cookiestr, const char *cookiename);

// get the value of a cookie by name.
char *
get_cookie(const char *cookiestr, const char *cookiename);

char *
geo_lookup_latlon(MMDB_s *const mmdb_handle, const char *ipstr);
#endif


text:
*   Touch all corresponding model records after ActiveStorage::Blob is analyzed

    This fixes a race condition where a record can be requested and have a cache entry built, before
    the initial `analyze_later` completes, which will not be invalidated until something else
    updates the record. This also invalidates cache entries when a blob is re-analyzed, which
    is helpful if a bug is fixed in an analyzer or a new analyzer is added.

    *Nate Matykiewicz*

*   Add ability to use pre-defined variants when calling `preview` or
    `representation` on an attachment.

    ```ruby
    class User < ActiveRecord::Base
      has_one_attached :file do |attachable|
        attachable.variant :thumb, resize_to_limit: [100, 100]
      end
    end

    <%= image_tag user.file.representation(:thumb) %>
    ```

    *Richard Böhme*

*   Method `attach` always returns the attachments except when the record
    is persisted, unchanged, and saving it fails, in which case it returns `nil`.

    *Santiago Bartesaghi*

*   Fixes multiple `attach` calls within transaction not uploading files correctly.

    In the following example, the code failed to upload all but the last file to the configured service.
    ```ruby
      ActiveRecord::Base.transaction do
        user.attachments.attach({
          content_type: "text/plain",
          filename: "dummy.txt",
          io: ::StringIO.new("dummy"),
        })
        user.attachments.attach({
          content_type: "text/plain",
          filename: "dummy2.txt",
          io: ::StringIO.new("dummy2"),
        })
      end

      assert_equal 2, user.attachments.count
      assert user.attachments.first.service.exist?(user.attachments.first.key)  # Fails
    ```

    This was addressed by keeping track of the subchanges pending upload, and uploading them
    once the transaction is committed.

    Fixes #41661

    *Santiago Bartesaghi*, *Bruno Vezoli*, *Juan Roig*, *Abhay Nikam*

*   Raise an exception if `config.active_storage.service` is not set.

    If Active Storage is configured and `config.active_storage.service` is not
    set in the respective environment's configuration file, then an exception
    is raised with a meaningful message when attempting to use Active Storage.

    *Ghouse Mohamed*

*   Fixes proxy downloads of files over 5mb

    Previously, trying to view and/or download files larger than 5mb stored in
    services like S3 via proxy mode could return corrupted files at around
    5.2mb or cause random halts in the download. Now,
    `ActiveStorage::Blobs::ProxyController` correctly handles streaming these
    larger files from the service to the client without any issues.

    Fixes #44679

    *Felipe Raul*

*   Saving attachment(s) to a record returns the blob/blobs object

    Previously, saving attachments did not return the blob/blobs that
    were attached. Now, saving attachments to a record with `#attach`
    method returns the blob or array of blobs that were attached to
    the record. If it fails to save the attachment(s), then it returns
    `false`.

    *Ghouse Mohamed*

*   Don't stream responses in redirect mode

    Previously, both redirect mode and proxy mode streamed their
    responses which caused a new thread to be created, and could end
    up leaking connections in the connection pool. But since redirect
    mode doesn't actually send any data, it doesn't need to be
    streamed.

    *Luke Lau*

Please check [7-0-stable](https://github.com/rails/rails/blob/7-0-stable/activestorage/CHANGELOG.md) for previous changes.


text:
var app = angular.module('myApp');

app.factory('ProviderService', ['$resource', function($resource) {

}]);


text:
'use strict';

angular.module('zpWeather')
    .controller('zpwWeatherCtrl',
    ['$scope', '$stateParams', '$q', '$cordovaGeolocation', 'zpwWeatherService', '$ionicModal', '$timeout', 'zpwFocusCitiesStorage',
        function ($scope, $stateParams, $q, $cordovaGeolocation, zpwWeatherService, $ionicModal, $timeout, zpwFocusCitiesStorage) {
            $scope.doRefresh = function () {
                var rtwPromise, twPromise, wwPromise;

                rtwPromise = zpwWeatherService.getRealtimeWeather($scope.currentCity.d1);
                twPromise = zpwWeatherService.getTodayWeather($scope.currentCity.d1);
                wwPromise = zpwWeatherService.getWeeklyWeather($scope.currentCity.d1);

                $q.all([rtwPromise, twPromise, wwPromise]).then(function success(data) {
                    //<1>
                    $scope.realtimeWeatherInfo = data[0];

                    //<2>
                    $scope.todayWeatherInfo = data[1];

                    //http://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng
                    String.prototype.paddingLeft = function (paddingValue) {
                        return String(paddingValue + this).slice(-paddingValue.length);
                    };
                    $scope.todayWeatherInfo.onlineImg = 'http://mobile.weather.com.cn/images/day/' + $scope.todayWeatherInfo.img1.replace('d', '').replace('n', '').replace('.gif', '').paddingLeft('00') + '.png';

                    //<3>
                    $scope.weeklyWeatherInfo = data[2];

                    //fixbug 缺少当天最高气温和天气图标
                    var curDayWeather = data[2][0];
                    if (curDayWeather !== null && (curDayWeather.fa === "" || curDayWeather.fc === "")) {
                        curDayWeather.fc = $scope.todayWeatherInfo.temp2;
                        var index = curDayWeather.fc.indexOf("℃");
                        if (index !== -1) {
                            curDayWeather.fc = curDayWeather.fc.slice(0, index);
                        }
                        curDayWeather.fa = $scope.todayWeatherInfo.img1;
                    }

                }).catch(function error(err) {
                    console.error(err);
                }).finally(function () {
                    // Stop the ion-refresher from spinning
                    $scope.$broadcast('scroll.refreshComplete');
                });

//                 被注释掉的这段代码,是按照chain的风格调用3个http api的,而上面的代码,是按照Parallel的风格并行执行3个http api请求的
                /*zpwWeatherService.getRealtimeWeather($scope.currentCity.d1).then(function success(data0) {
                 $scope.realtimeWeatherInfo = data0;

                 return zpwWeatherService.getTodayWeather($scope.currentCity.d1);
                 }).then(function success(data1) {
                 $scope.todayWeatherInfo = data1;

                 //http://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng
                 String.prototype.paddingLeft = function (paddingValue) {
                 return String(paddingValue + this).slice(-paddingValue.length);
                 };
                 $scope.todayWeatherInfo.onlineImg = 'http://mobile.weather.com.cn/images/day/' + $scope.todayWeatherInfo.img1.replace('d', '').replace('n', '').replace('.gif', '').paddingLeft('00') + '.png';

                 return zpwWeatherService.getWeeklyWeather($scope.currentCity.d1);
                 }).then(function success(data2) {
                 $scope.weeklyWeatherInfo = data2;

                 //fixbug 缺少当天最高气温和天气图标
                 var curDayWeather = data2[0];
                 if (curDayWeather !== null && (curDayWeather.fa === "" || curDayWeather.fc === "")) {
                 curDayWeather.fa = $scope.todayWeatherInfo.img1;
                 curDayWeather.fc = $scope.todayWeatherInfo.temp2;
                 var index = curDayWeather.fc.indexOf("℃");
                 if (index !== -1) {
                 curDayWeather.fc = curDayWeather.fc.slice(0, index);
                 }
                 }

                 }).catch(function error(err) {
                 console.info(err);
                 }).finally(function () {
                 // Stop the ion-refresher from spinning
                 $scope.$broadcast('scroll.refreshComplete');*/
            };

            /////////
            $scope.todayDate = new Date();
            console.log($scope.todayDate);

            $scope.currentCity = zpwFocusCitiesStorage.getCurrentCity();
            if ($scope.currentCity !== null) {
                $scope.doRefresh();
            }

            $scope.$on('zpw.currentCity.updated', function (event, city) {
                $scope.currentCity = city;
                if ($scope.currentCity !== null) {
                    $scope.doRefresh();
                }
            });

//            $scope.webVersion = '0.1.2';

            /**
             *
             $cordovaGeolocation.getCurrentPosition().then(function (position) {
                // alert('get geo');
                // Position here: position.coords.latitude, position.coords.longitude
                // alert('Latitude: '          + position.coords.latitude          + '\n' +
                //   'Longitude: '         + position.coords.longitude         + '\n' +
                //   'Altitude: '          + position.coords.altitude          + '\n' +
                //   'Accuracy: '          + position.coords.accuracy          + '\n' +
                //   'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
                //   'Heading: '           + position.coords.heading           + '\n' +
                //   'Speed: '             + position.coords.speed             + '\n' +
                //   'Timestamp: '         + position.timestamp                + '\n');

                $scope.lat = position.coords.latitude;
                $scope.lng = position.coords.longitude;
            }, function (err) {
                // error
                alert(err);
            });

             $cordovaGeolocation.watchPosition().then(function () {
                // Not currently used
            }, function (err) {
                // An error occured. Show a message to the user
            }, function (position) {
                // Active updates of the position here
            });
             * */

        }]);


text:
git-patch-patch is an attempt a making a not-too-bright not-too-stupid script
to review Git commit history.

Using it, you could, for instance, have the ground matter to make a real
`git-mv` with history.

## Installation

Ruby 1.9.2 is required.

It is packaged as a gem, so :

Install it with rubygems:

    gem install git-patch-patch

With bundler, add it to your `Gemfile`:

``` ruby
gem "git-patch-patch"
```

## Use

### Script

``` shell
ruby bin/git-patch-patch --repo /home/me/my_repo \
     --pattern pattern_to_replace --replacement replacement \
     --patch_dir '/tmp' --branch master --patch_patch --dont_ask

```

I hope most of the options will be crystal clear without explanation. Yet :
 - patch dir is temp' directory where work files (patches) will be stored
 - patch_patch asks the script to perform replacement not only on filenames
 - dont_ask enters interactive mode only in case of a Git error

It works on a dedicated branch with a barbaric name, trying the script should
be completely harmful, if not useful.

### Home-made fitting lib's

The script relies on two classes, a controller that manages some sort of
workflow, and a model attempting to represent the patch shrewdly.

I am not going to document this any further though.

If you have the kind of need falling in the scope of the script, you should be,
by far, able to modify the script, and understand what the underlying lib's are
doing.

## Use ?

Well, here's what the script does :
 - creates a specific work branch
 - iterates over all the commits of the designated branch
 - apply pattern replacement on patch file
   - only on filenames (default and pretty safe, and conflict-proof)
   - on patch content if asked
 - apply patch to working directory reusing the commit information (date,
   author, message), hence creating a new sha
 - let's you review the patch if not only on filenames
   (patch edition through `vim`)
 - let's you review the patch if an error on patch application occurred

In the end, you have a whole new set of commits, keeping track of the project
history, integrating the changes you want to see in your file tree or file
contents.

So, if all that's of any help to you, yeah, use it.

It's safe, because it's Git (rollback should be easy), and because it's
operating on its own branch (revert being then a childlike
`git branch -D work_branch`). And there's a ludicrous amount of spec's to ensure
the script does what it says it does.

## TODO
- use cherry-pick instead of making a new commit when no modification was made
- checkout -b new_branch to a specific commit to reduce the amount of reviewed
  commits
- add path delimiter to review history only on a subset of the repo' file, again
  to reduce the amount of reviewed commits
- have an idea when i'll do all the above-mentionned

Copyright
---------

I was tempted by the WTFPL, but i have to take time to read it.
So far see LICENSE.


text:
#pragma once

#include "gl.h"
#include "../math/vector.h"
#include "quad.h"
#include "image.h"

typedef struct {
  graphics_Image image;

//  GLuint fbo;
  GLuint stencilBuf;
  mat4x4 projectionMatrix;
} graphics_Canvas;

void graphics_Canvas_new(graphics_Canvas *canvas, int width, int height);
void graphics_Canvas_free(graphics_Canvas *canvas);
void graphics_Canvas_draw(graphics_Canvas const* canvas, graphics_Quad const* quad,
                         float x, float y, float r, float sx, float sy,
                         float ox, float oy, float kx, float ky);
void graphics_setCanvas(graphics_Canvas ** canvas, int count);
int graphics_getCanvas(graphics_Canvas **canvases);
int graphics_getCanvasCount(void);
graphics_Canvas* graphics_getCanvasN(int i);
void graphics_canvas_init(int width, int height);
void graphics_Canvas_createStencilBuffer(graphics_Canvas *canvas);


text:
name 'mongodb_spec'

depends 'sc-mongodb'


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

module Domgen
  module JPA
    module Helper
      def j_jpa_field_attributes(attribute)
        s = ''
        s << "  @javax.persistence.Id\n" if attribute.primary_key?
        s << "  @javax.persistence.GeneratedValue( strategy = javax.persistence.GenerationType.IDENTITY )\n" if attribute.sql.identity?
        s << gen_relation_annotation(attribute, true) if attribute.reference?
        s << gen_column_annotation(attribute)
        s << "  @javax.persistence.Basic( optional = #{attribute.nullable?}, fetch = javax.persistence.FetchType.EAGER )\n" unless attribute.reference?
        s << "  @javax.persistence.Enumerated( javax.persistence.EnumType.#{ attribute.enumeration.numeric_values? ? "ORDINAL" : "STRING"} )\n" if attribute.enumeration?
        s << "  @javax.persistence.Temporal( javax.persistence.TemporalType.#{attribute.datetime? ? "TIMESTAMP" : "DATE"} )\n" if attribute.datetime? || attribute.date?
        s << "  @javax.validation.constraints.NotNull\n" if !attribute.nullable? && !attribute.generated_value?
        s << nullable_annotate(attribute, '', true)
        if attribute.text?
          unless attribute.length.nil? && attribute.min_length.nil?
            s << "  @javax.validation.constraints.Size( "
            s << "min = #{attribute.min_length} " unless attribute.min_length.nil?
            s << ", " unless attribute.min_length.nil? || !attribute.has_non_max_length?
            s << "max = #{attribute.length} " if attribute.has_non_max_length?
            s << " )\n"
          end
        end
        s
      end

      def j_declared_relation(attribute)
        s = ''
        s << gen_relation_annotation(attribute, false)
        s << gen_fetch_mode_if_specified(attribute)
        if attribute.inverse.multiplicity == :many
          s << "  private java.util.List<#{attribute.entity.jpa.qualified_name}> #{Domgen::Naming.pluralize(Domgen::Naming.camelize(attribute.inverse.name))};\n"
        else # attribute.inverse.multiplicity == :one || attribute.inverse.multiplicity == :zero_or_one
          s << "  private #{attribute.entity.jpa.qualified_name} #{Domgen::Naming.camelize(attribute.inverse.name)};\n"
        end
        s
      end

      def gen_column_annotation(attribute)
        parameters = []
        parameters << "name = \"#{attribute.sql.column_name}\""
        parameters << "nullable = #{attribute.nullable?}"
        parameters << "updatable = #{attribute.updatable?}"
        parameters << "unique = #{attribute.unique?}"
        parameters << "insertable = #{!attribute.generated_value? || attribute.primary_key?}"

        if attribute.reference?
          parameters << "referencedColumnName = \"#{attribute.referenced_entity.primary_key.sql.column_name}\""
        end

        if !attribute.reference? && attribute.has_non_max_length?
          parameters << "length = #{attribute.length}"
        end

        annotation = attribute.reference? ? "JoinColumn" : "Column"
        "  @javax.persistence.#{annotation}( #{parameters.join(', ')} )\n"
      end

      def gen_relation_annotation(attribute, declaring_relationship)
        parameters = []
        cascade = declaring_relationship ? attribute.jpa.cascade : attribute.inverse.jpa.cascade
        unless cascade.nil? || cascade.empty?
          parameters << "cascade = { #{cascade.map { |c| "javax.persistence.CascadeType.#{c.to_s.upcase}" }.join(", ")} }"
        end

        fetch_type = declaring_relationship ? attribute.jpa.fetch_type : attribute.inverse.jpa.fetch_type
        parameters << "fetch = javax.persistence.FetchType.#{fetch_type.to_s.upcase}"

        if declaring_relationship
          parameters << "optional = #{attribute.nullable?}"
          parameters << "targetEntity = #{attribute.referenced_entity.jpa.qualified_name}.class"
        end

        if !declaring_relationship
          parameters << "orphanRemoval = #{attribute.inverse.jpa.orphan_removal?}"
          parameters << "mappedBy = \"#{attribute.jpa.field_name}\""
          parameters << "targetEntity = #{attribute.entity.jpa.qualified_name}.class"
        end

        #noinspection RubyUnusedLocalVariable
        annotation = nil
        if attribute.inverse.multiplicity == :one || attribute.inverse.multiplicity == :zero_or_one
          annotation = "OneToOne"
        elsif declaring_relationship
          annotation = "ManyToOne"
        else
          annotation = "OneToMany"
        end

        "  @javax.persistence.#{annotation}( #{parameters.join(", ")} )\n"
      end

      def gen_fetch_mode_if_specified(attribute)
        fetch_mode = attribute.inverse.jpa.fetch_mode
        if fetch_mode
          "  @org.hibernate.annotations.Fetch( org.hibernate.annotations.FetchMode.#{fetch_mode.to_s.upcase} )\n"
        else
          ''
        end
      end

      def j_constructors(entity)
        immutable_attributes = entity.attributes.select{|a| a.immutable? && !a.generated_value? && a.jpa.persistent? }
        declared_attribute_names = entity.declared_attributes.collect{|a| a.name}
        declared_immutable_attributes = immutable_attributes.select{ |a| declared_attribute_names.include?(a.name) }
        undeclared_immutable_attributes = immutable_attributes.select{ |a| !declared_attribute_names.include?(a.name) }
        return '' if immutable_attributes.empty?
        java = <<JAVA
  protected #{entity.jpa.name}()
  {
  }

  @SuppressWarnings( { "ConstantConditions", "deprecation" } )
  public #{entity.jpa.name}(#{immutable_attributes.collect{|a| "final #{nullable_annotate(a, a.jpa.java_type, false)} #{a.jpa.name}"}.join(", ")})
  {
#{undeclared_immutable_attributes.empty? ? '' : "    super(#{undeclared_immutable_attributes.collect{|a| a.jpa.name}.join(", ")});\n"}
#{declared_immutable_attributes.select{|a|!a.nullable? && !a.jpa.primitive?}.collect{|a| "    if( null == #{a.jpa.name} )\n    {\n      throw new NullPointerException( \"#{a.jpa.name} is not nullable\" );\n    }"}.join("\n")}
#{declared_immutable_attributes.collect { |a| "    this.#{a.jpa.field_name} = #{a.jpa.name};" }.join("\n")}
#{declared_immutable_attributes.select{|a|a.reference?}.collect { |a| "    " + j_add_to_inverse(a) }.join("\n")}
  }
JAVA
        java
      end

      def j_declared_attribute_accessors(entity)
        entity.declared_attributes.select{|attribute| attribute.jpa.persistent? }.collect do |attribute|
          if attribute.abstract?
            j_abstract_attribute(attribute)
          elsif attribute.reference?
            j_reference_attribute(attribute)
          else
            j_simple_attribute(attribute)
          end
        end.compact.join("\n")
      end

      def j_declared_attribute_and_relation_accessors(entity)
        relation_methods = entity.referencing_attributes.collect do |attribute|

          if attribute.abstract? || attribute.inherited? || !attribute.entity.jpa? || !attribute.jpa.persistent? || !attribute.inverse.jpa.java_traversable? || attribute.referenced_entity != entity
            # Ignore abstract attributes as will appear in child classes
            # Ignore inherited attributes as appear in parent class
            # Ignore attributes that have no inverse relationship
            nil
          elsif attribute.inverse.multiplicity == :many
            j_has_many_attribute(attribute)
          else #attribute.inverse.multiplicity == :one || attribute.inverse.multiplicity == :zero_or_one
            name = attribute.inverse.name
            field_name = Domgen::Naming.camelize( name )
            type = nullable_annotate(attribute, attribute.entity.jpa.qualified_name, false, true)

            java = description_javadoc_for attribute
            java << <<JAVA
  public #{type} #{getter_for(attribute, name)}
  {
     #{attribute.primary_key? ? "":"verifyNotRemoved();"}
     return #{field_name};
  }

  #{j_deprecation_warning(attribute)}final void add#{name}( final #{type} value )
  {
     #{attribute.primary_key? ? "":"verifyNotRemoved();"}
    if( null != this.#{field_name} )
    {
      throw new IllegalStateException("Attempted to add value when non null value exists.");
    }
    if( value != this.#{field_name} )
    {
      this.#{field_name} = value;
    }
  }

  public final void remove#{name}( final #{type} value )
  {
     #{attribute.primary_key? ? "":"verifyNotRemoved();"}
    if( null != this.#{field_name} && value != this.#{field_name} )
    {
      throw new IllegalStateException("Attempted to remove value that was not the same.");
    }
    if( null != this.#{field_name} )
    {
      this.#{field_name} = null;
    }
  }
JAVA
            java
          end
        end
        j_declared_attribute_accessors(entity) + relation_methods.compact.join("\n")
      end

      def j_return_if_value_same(name, primitive, nullable)
        if primitive
          return <<JAVA
     if( #{name} == value )
     {
       return;
     }
JAVA
        elsif !nullable
          return <<JAVA
     //noinspection ConstantConditions
     if( null == value )
     {
       throw new NullPointerException( "#{name} parameter is not nullable" );
     }

     if( value.equals( this.#{name} ) )
     {
       return;
     }
JAVA
        else
          return <<JAVA
     if( null != this.#{name} && this.#{name}.equals( value ) )
     {
       return;
     }
     else if( null != value && value.equals( this.#{name} ) )
     {
       return;
     }
     else if( null == this.#{name} && null == value )
     {
       return;
     }
JAVA
        end
      end

      def j_simple_attribute(attribute)
        name = attribute.jpa.name
        field_name = attribute.jpa.field_name
        type = nullable_annotate(attribute, attribute.jpa.java_type, false)
        java = description_javadoc_for attribute
        java << <<JAVA
  public #{type} #{getter_for(attribute)}
  {
     #{attribute.primary_key? ? "":"verifyNotRemoved();"}
JAVA
        if attribute.generated_value? && !attribute.nullable?
          java << <<JAVA
      if( null == this.#{field_name} )
      {
        throw new IllegalStateException("Attempting to access generated value #{name} before it has been flushed to the database.");
      }
JAVA

        end
        java << <<JAVA
     return doGet#{name}();
  }

  protected #{type} doGet#{name}()
  {
    return #{field_name};
  }

JAVA
        if attribute.updatable?
          java << <<JAVA
  public void set#{name}( final #{type} value )
  {
#{j_return_if_value_same(field_name, attribute.jpa.primitive?, attribute.nullable?)}
        this.#{field_name} = value;
  }
JAVA
        end
        java
      end

      def j_add_to_inverse(attribute)
        name = attribute.jpa.name
        field_name = attribute.jpa.field_name
        inverse_name = attribute.inverse.name
        if !attribute.inverse.jpa.java_traversable?
          ''
        else
          null_guard(attribute.nullable?, field_name) { "this.#{field_name}.add#{inverse_name}( this );" }
        end
      end

      def j_remove_from_inverse(attribute)
        name = attribute.jpa.name
        field_name = attribute.jpa.field_name
        inverse_name = attribute.inverse.name
        if !attribute.inverse.jpa.java_traversable?
          ''
        else
          null_guard(true, field_name) { "#{field_name}.remove#{inverse_name}( this );" }
        end
      end

      def j_reference_attribute(attribute)
        name = attribute.jpa.name
        field_name = attribute.jpa.field_name
        type = nullable_annotate(attribute, attribute.jpa.java_type, false)
        java = description_javadoc_for attribute
        java << <<JAVA
  public #{type} #{getter_for(attribute)}
  {
     #{attribute.primary_key? ? "":"verifyNotRemoved();"}
     return doGet#{attribute.jpa.name}();
  }

  protected #{type} doGet#{attribute.jpa.name}()
  {
    return #{field_name};
  }

JAVA
        if attribute.updatable?
          java << <<JAVA
  @SuppressWarnings( { "deprecation" } )
  public void set#{name}( final #{type} value )
  {
 #{j_return_if_value_same(field_name, attribute.referenced_entity.primary_key.jpa.primitive?, attribute.nullable?)}
        #{j_remove_from_inverse(attribute)}
        this.#{field_name} = value;
 #{j_add_to_inverse(attribute)}
  }
JAVA
        end
        java
      end

      def j_abstract_attribute(attribute)
        <<JAVA
    public abstract #{attribute.jpa.java_type} #{getter_for(attribute)};
JAVA
      end

      def j_deprecation_warning(attribute)
        if attribute.entity.data_module.name != entity.data_module.name
          <<STR
  /**
   * This method should not be called directly. It is called from the constructor of #{attribute.entity.jpa.qualified_name}.
   * @deprecated
   */
  @Deprecated public
STR
        else
          ''
        end
      end

      def j_has_many_attribute(attribute)
        name = attribute.inverse.name
        plural_name = Domgen::Naming.pluralize(name)
        field_name = Domgen::Naming.camelize(plural_name)
        type = attribute.entity.jpa.qualified_name
        java = description_javadoc_for attribute
        java << <<STR
  public java.util.List<#{type}> get#{plural_name}()
  {
    return java.util.Collections.unmodifiableList( safeGet#{plural_name}() );
  }

  #{j_deprecation_warning(attribute)} final void add#{name}( final #{type} value )
  {
    final java.util.List<#{type}> #{field_name}Safe = safeGet#{plural_name}();
    if ( !#{field_name}Safe.contains( value ) )
    {
      #{field_name}Safe.add( value );
    }
  }

  public final void remove#{name}( final #{type} value )
  {
    if ( null != this.#{field_name} && this.#{field_name}.contains( value ) )
    {
      this.#{field_name}.remove( value );
    }
  }

  private java.util.List<#{type}> safeGet#{plural_name}()
  {
    if( null == this.#{field_name} )
    {
      this.#{field_name} = new java.util.LinkedList<#{type}>();
    }
    return this.#{field_name};
  }
STR
        java
      end

      def j_equals_method(entity)
        return '' if entity.abstract?
        pk = entity.primary_key
        pk_getter = "doGet#{entity.primary_key.jpa.name}()"
        pk_type = nullable_annotate(pk, pk.jpa.java_type, false)
        equality_comparison = (!pk.jpa.primitive?) ? "null != key && key.equals( that.#{pk_getter} )" : "key == that.#{pk_getter}"
        s = <<JAVA
  @Override
  public boolean equals( final Object o )
  {
    if ( this == o )
    {
      return true;
    }
    else if ( o == null || !(o instanceof #{entity.jpa.name}) )
    {
      return false;
    }
    else
    {
      final #{entity.jpa.name} that = (#{entity.jpa.name}) o;
      final #{pk_type} key = #{pk_getter};
      return #{equality_comparison};
    }
  }
JAVA
        s += <<JAVA
  @Override
  public int hashCode()
  {
    final #{pk_type} key = #{pk_getter};
JAVA
        if pk.jpa.primitive?
          s += <<JAVA
    return key;
JAVA
        else
          s += <<JAVA
    if( null == key )
    {
      return System.identityHashCode( this );
    }
    else
    {
      return key.hashCode();
    }
JAVA
        end
        s += <<JAVA
  }
JAVA
        s
      end

      def j_to_string_methods(entity)
        return '' if entity.abstract?
        s = <<JAVA
  @Override
  public String toString()
  {
    return "#{entity.name}[" +
JAVA
        s += entity.attributes.select{|a| a.jpa.persistent?}.collect do |a|
          "           \"#{a.jpa.name} = \" + doGet#{a.jpa.name}()"
        end.join(" + \", \" +\n")
        s += <<JAVA
 +
           "]";
  }
JAVA
        s
      end

      def nullable_annotate(attribute, type, is_field_annotation, inverse_side = false)
        # Not sure why PrimaryKeys can not have annotation other than the fact that EclipseLink fails
        # to find ID if it is
        if attribute.jpa.primitive? || attribute.primary_key?
          return type
        elsif !attribute.nullable? &&
          !attribute.generated_value? &&
          !(attribute.reference? && attribute.inverse.multiplicity == :zero_or_one && inverse_side)
          annotation = "#{nullability_annotation(false)} #{type}"
        else
          annotation = "#{nullability_annotation(true)} #{type}"
        end
        if is_field_annotation
          "  #{annotation}\n"
        else
          annotation
        end
      end

      def query_return_type(query)
        return "int" if query.query_type != :select
        name = query.entity.jpa.qualified_name
        return "#{nullability_annotation(false)} java.util.List<#{name}>" if query.multiplicity == :many
        "#{nullability_annotation(query.multiplicity == :zero_or_one)} #{name}"
      end

      def null_guard(nullable, name)
        s = ''
        if nullable
          s += <<JAVA
  if( null != #{name} )
  {
JAVA
        end
        s += yield
        if nullable
          s += <<JAVA
  }
JAVA
        end
        s
      end

      def description_javadoc_for(element, depth = "  ")
        description = element.tags[:Description]
        return '' unless description
        return <<JAVADOC
#{depth}/**
#{depth} * #{description.gsub(/\n+\Z/,"").gsub("\n\n","\n<br />\n").gsub("\n","\n#{depth} * ")}
#{depth} */
JAVADOC
      end

      def getter_for( attribute, name = nil )
        name = attribute.jpa.name unless name
        "#{getter_prefix(attribute)}#{name}()"
      end

      def validation_name(constraint_name)
        "Validate#{constraint_name}"
      end

      def jpa_validation_in_jpa?(constraint)
        entity = constraint.entity
        if constraint.is_a?(CodependentConstraint) || constraint.is_a?(IncompatibleConstraint)
          return constraint.attribute_names.all? { |attribute_name| a = entity.attribute_by_name(attribute_name); a.jpa? && a.jpa.persistent? }
        elsif constraint.is_a?(RelationshipConstraint)
          lhs = entity.attribute_by_name(constraint.lhs_operand)
          rhs = entity.attribute_by_name(constraint.rhs_operand)
          return lhs.jpa? && lhs.jpa.persistent? && rhs.jpa? && rhs.jpa.persistent?
        elsif constraint.is_a?(CycleConstraint)
          target_attribute = entity.attribute_by_name(constraint.attribute_name)
          scoping_attribute = target_attribute.referenced_entity.attribute_by_name(constraint.scoping_attribute)

          current_entity = entity
          elements = constraint.attribute_name_path.collect do |element_name|
            new_attr = current_entity.attribute_by_name(element_name)
            current_entity = new_attr.referenced_entity
            new_attr
          end + [target_attribute, scoping_attribute]
          return elements.all? { |attribute| attribute.jpa? && attribute.jpa.persistent? }
        elsif constraint.is_a?(DependencyConstraint)
          target_attribute = entity.attribute_by_name(constraint.attribute_name)

          return target_attribute.jpa? &&
            constraint.dependent_attribute_names.all? { |attribute_name| a = entity.attribute_by_name(attribute_name); a.jpa? && a.jpa.persistent? }
        else
          return false
        end
      end

      def validation_prefix(constraint_name, entity)
        return <<JAVA
  @java.lang.annotation.Target( { java.lang.annotation.ElementType.TYPE } )
  @java.lang.annotation.Retention( java.lang.annotation.RetentionPolicy.RUNTIME )
  @javax.validation.Constraint( validatedBy = #{constraint_name}Validator.class )
  @java.lang.annotation.Documented
  public @interface #{validation_name(constraint_name)}
  {
    String message() default "{#{entity.jpa.qualified_name}.#{constraint_name}}";

    Class<?>[] groups() default { };

    Class<? extends javax.validation.Payload>[] payload() default { };
  }

  public static class #{constraint_name}Validator
    implements javax.validation.ConstraintValidator<#{validation_name(constraint_name)}, #{entity.jpa.name}>
  {
    @Override
    public void initialize( final #{validation_name(constraint_name)} constraintAnnotation )
    {
    }

    @Override
    public boolean isValid( final #{entity.jpa.name} object, final javax.validation.ConstraintValidatorContext constraintContext )
    {
      if ( null == object )
      {
        return true;
      }
      try
      {
JAVA
      end

      def validation_suffix
        return <<JAVA
      }
      catch( final Throwable t )
      {
        return false;
      }
      return true;
    }
  }
JAVA
      end
    end
  end
end


text:
package org.projog.core.event;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.projog.TermFactory.atom;
import static org.projog.TermFactory.integerNumber;
import static org.projog.TermFactory.list;
import static org.projog.TermFactory.structure;
import static org.projog.TermFactory.variable;

import org.junit.Test;
import org.projog.SimpleProjogListener;
import org.projog.TestUtils;
import org.projog.core.kb.KnowledgeBase;
import org.projog.core.predicate.PredicateKey;
import org.projog.core.predicate.udp.ClauseModel;
import org.projog.core.predicate.udp.DynamicUserDefinedPredicateFactory;
import org.projog.core.term.EmptyList;
import org.projog.core.term.Term;
import org.projog.core.term.Variable;

public class SpyPointsTest {
   private final KnowledgeBase kb = TestUtils.createKnowledgeBase();

   @Test
   public void testGetSameSpyPointForSamePredicateKey() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key = createKey("test", 2);
      assertSame(testObject.getSpyPoint(key), testObject.getSpyPoint(key));
   }

   @Test
   public void testGetSameSpyPointWhenPredicateKeysEqual() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key1 = createKey("test", 2);
      PredicateKey key2 = createKey("test", 2);
      assertNotSame(key1, key2);
      assertSame(testObject.getSpyPoint(key1), testObject.getSpyPoint(key2));
   }

   @Test
   public void testGetDifferentSpyPointWhenPredicateKeysNotEqual() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key1 = createKey("test1", 0);
      PredicateKey key2 = createKey("test1", 1);
      PredicateKey key3 = createKey("test1", 2);
      PredicateKey key4 = createKey("test2", 2);
      assertNotSame(testObject.getSpyPoint(key1), testObject.getSpyPoint(key2));
      assertNotSame(testObject.getSpyPoint(key2), testObject.getSpyPoint(key3));
      assertNotSame(testObject.getSpyPoint(key3), testObject.getSpyPoint(key4));
   }

   @Test
   public void testGetPredicateKey() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key1 = createKey("test1", 2);
      PredicateKey key2 = createKey("test1", 2);
      PredicateKey key3 = createKey("test1", 1);
      PredicateKey key4 = createKey("test2", 1);
      assertNotSame(key1, key2);

      assertSame(key1, testObject.getSpyPoint(key1).getPredicateKey());
      assertSame(key1, testObject.getSpyPoint(key2).getPredicateKey());
      assertSame(key3, testObject.getSpyPoint(key3).getPredicateKey());
      assertSame(key4, testObject.getSpyPoint(key4).getPredicateKey());
   }

   @Test
   public void testGetSpyPoints() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey[] keys = {createKey("test1", 0), createKey("test1", 2), createKey("test2", 2)};
      SpyPoints.SpyPoint[] spyPoints = new SpyPoints.SpyPoint[keys.length];

      assertTrue(testObject.getSpyPoints().isEmpty());
      for (int i = 0; i < keys.length; i++) {
         spyPoints[i] = testObject.getSpyPoint(keys[i]);
         assertEquals(i + 1, testObject.getSpyPoints().size());
      }

      for (int i = 0; i < keys.length; i++) {
         assertSame(spyPoints[i], testObject.getSpyPoints().get(keys[i]));
      }
   }

   @Test
   public void testSetSpyPointOnlyAltersSingleSpyPoint() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key1 = createKey("test1", 2);
      PredicateKey key2 = createKey("test2", 2);
      SpyPoints.SpyPoint sp1 = testObject.getSpyPoint(key1);
      SpyPoints.SpyPoint sp2 = testObject.getSpyPoint(key2);

      assertFalse(sp1.isSet());
      assertFalse(sp2.isSet());

      testObject.setSpyPoint(key1, true);
      assertTrue(sp1.isSet());
      assertFalse(sp2.isSet());

      testObject.setSpyPoint(key1, true);
      assertTrue(sp1.isSet());
      assertFalse(sp2.isSet());

      testObject.setSpyPoint(key1, false);
      assertFalse(sp1.isSet());
      assertFalse(sp2.isSet());
   }

   @Test
   public void testSetSpyPointWorksEvenBeforeGetSpyPointCalled() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key = createKey("test", 2);
      testObject.setSpyPoint(key, true);
      assertTrue(testObject.getSpyPoint(key).isSet());
   }

   @Test
   public void testSpyPointAffectedBySetTraceEnabledCallAfterItWasCreated() {
      SpyPoints testObject = new SpyPoints(kb);
      SpyPoints.SpyPoint sp = testObject.getSpyPoint(createKey("test", 1));
      assertFalse(sp.isEnabled());
      testObject.setTraceEnabled(true);
      assertTrue(sp.isEnabled());
      testObject.setTraceEnabled(false);
      assertFalse(sp.isEnabled());
   }

   @Test
   public void testSpyPointAffectedBySetTraceEnabledCallBeforeItWasCreated() {
      SpyPoints testObject = new SpyPoints(kb);
      testObject.setTraceEnabled(true);
      SpyPoints.SpyPoint sp = testObject.getSpyPoint(createKey("test", 1));
      assertTrue(sp.isEnabled());
      testObject.setTraceEnabled(false);
      assertFalse(sp.isEnabled());
   }

   @Test
   public void testSetTraceEnabledIndependantOfSetSpyPoint() {
      SpyPoints testObject = new SpyPoints(kb);
      PredicateKey key = createKey("test", 2);

      SpyPoints.SpyPoint sp = testObject.getSpyPoint(key);
      assertTrue(sp.isSet() == false && sp.isEnabled() == false);

      testObject.setTraceEnabled(true);
      assertTrue(sp.isSet() == false && sp.isEnabled() == true);

      testObject.setTraceEnabled(false);
      assertTrue(sp.isSet() == false && sp.isEnabled() == false);

      testObject.setSpyPoint(key, true);
      assertTrue(sp.isSet() == true && sp.isEnabled() == true);

      testObject.setTraceEnabled(true);
      assertTrue(sp.isSet() == true && sp.isEnabled() == true);

      testObject.setTraceEnabled(false);
      assertTrue(sp.isSet() == true && sp.isEnabled() == true);

      testObject.setTraceEnabled(true);
      assertTrue(sp.isSet() == true && sp.isEnabled() == true);

      testObject.setSpyPoint(key, false);
      assertTrue(sp.isSet() == false && sp.isEnabled() == true);
   }

   @Test
   public void testSpyPointUpdatesObserver() {
      // add a listener to the KnowledgeBase's ProjogListeners
      // so we can keep track of ProjogEvent objects created by the SpyPoint
      final SimpleProjogListener listener = new SimpleProjogListener();
      kb.getProjogListeners().addListener(listener);

      PredicateKey key = createKey("test", 1);
      DynamicUserDefinedPredicateFactory pf = new DynamicUserDefinedPredicateFactory(kb, key);
      pf.addFirst(ClauseModel.createClauseModel(structure("test", new Variable())));
      kb.getPredicates().addUserDefinedPredicate(pf);

      SpyPoints testObject = new SpyPoints(kb);
      SpyPoints.SpyPoint sp = testObject.getSpyPoint(key);

      // make a number of log calls to the spy point -
      // the observer should not be updated with any of them as the spy point is not set
      assertFalse(sp.isSet());
      sp.logCall(this, new Term[] {atom("a")});
      sp.logExit(this, new Term[] {atom("b")}, 1);
      sp.logFail(this, new Term[] {atom("c")});
      sp.logRedo(this, new Term[] {atom("d")});
      assertTrue(listener.isEmpty());

      // set the spy point and then make a number of log calls to the spy point -
      // the observer should now be updated with each call in the order they are made
      testObject.setSpyPoint(key, true);
      sp.logCall(this, new Term[] {atom("z")});
      sp.logExit(this, new Term[] {list(atom("a"), variable("X"))}, 0);
      sp.logFail(this, new Term[] {structure("c", EmptyList.EMPTY_LIST, atom("z"), integerNumber(1))});
      sp.logRedo(this, new Term[] {new Variable()});
      assertEquals(4, listener.size());
      assertProjogEvent(listener.get(0), "CALL", "test(z)");
      assertProjogEvent(listener.get(1), "EXIT", "test([a,X])");
      assertProjogEvent(listener.get(2), "FAIL", "test(c([], z, 1))");
      assertProjogEvent(listener.get(3), "REDO", "test(_)");
   }

   private void assertProjogEvent(String event, String expectedType, String expectedMessage) {
      assertEquals(expectedType + expectedMessage, event);
   }

   private PredicateKey createKey(String name, int numArgs) {
      return new PredicateKey(name, numArgs);
   }
}


text:
<?php
namespace Kr\Bol\Tests;
require __DIR__ . '/../vendor/autoload.php';


text:
#include <string>
#define BOOST_LCAST_NO_COMPILE_TIME_PRECISION
#include <boost/lexical_cast.hpp>

#include <boost/test/unit_test.hpp>

void main_check() {
    BOOST_CHECK(!boost::lexical_cast<std::string>(2.12345).empty());
    BOOST_CHECK(!boost::lexical_cast<std::string>(2.12345678).empty());
}

boost::unit_test::test_suite *init_unit_test_suite(int, char *[])
{
    boost::unit_test::test_suite *suite =
        BOOST_TEST_SUITE("lexical_cast no-compile-time-precision check");
    suite->add(BOOST_TEST_CASE(main_check));
    return suite;
}


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

<title>SpawnBed</title>
<meta name="date" content="2012-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.pvminecraft.points.commands.spawn

Class SpawnBed

java.lang.Object

com.pvminecraft.points.commands.ArgumentSet

com.pvminecraft.points.commands.spawn.SpawnBed

public class SpawnBed
extends ArgumentSet

Field Summary

Fields inherited from class com.pvminecraft.points.commands.ArgumentSet

base, pattern, perms, plugin, regex

Constructor Summary

Constructors

Constructor and Description

SpawnBed(Command base,
        java.lang.String pat,
        JavaPlugin plugin,
        Permission... perms)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
execute(CommandSender sender,
       java.lang.String command,
       java.lang.String[] args)

Pair<java.lang.String,java.lang.String>
getHelp()

Methods inherited from class com.pvminecraft.points.commands.ArgumentSet

getBase, getPattern, getPerms, getRegex, hasPermission, match

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SpawnBed

public SpawnBed(Command base,
        java.lang.String pat,
        JavaPlugin plugin,
        Permission... perms)

Method Detail

execute

public boolean execute(CommandSender sender,
              java.lang.String command,
              java.lang.String[] args)

Specified by:

execute in class ArgumentSet

getHelp

public Pair<java.lang.String,java.lang.String> getHelp()

Specified by:

getHelp in class ArgumentSet

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import * as React from 'react';
import Header from './header';
import '../../stylesheets/article.scss';

interface Comment {
  author: string;
  content: string;
  avatar: string;
  time: number;
  id: number;
  likes: string;
  reply_to?: any;
}

interface ArticleProps {
  article: any;
  comments: Array<Comment>;
  fetchArticle: any;
  fetchShortComments: any;
  cleanData: any;
  location: any;
  match: any;
  push: any;
  replace: any;
  go: any;
  goBack: any;
  goForward: any;
}

export default class ArticleComponent extends React.Component<ArticleProps, any> {
  constructor(props: ArticleProps){
    super(props);
  }
  componentWillMount(){
    let root = document.getElementById("container");
    root.scrollTop = 0;
  }
  componentDidMount(){
    this.props.fetchArticle(this.props.match.params.id);
    this.props.fetchShortComments(this.props.match.params.id);
  }
  getDate(time: number){
    let date = new Date(time*1000);
    return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
  }
  componentWillUnmount(){
    this.props.cleanData("articleReducer");
  }
  render(){
    const { article, comments } = this.props;
    return (

        <Header title={"文章"} backButton={<button className="back-button" onClick={()=>this.props.goBack()}></button>}/>

{article.title}

{"图片来源:"+article.image_source}

评论

            {
              comments.map((comment: Comment)=>{
                return (

                        {comment.author}
                        {comment.reply_to?" 回复 ":""}
                        {comment.reply_to?comment.author:""}

{comment.content}

                        {comment.likes}
                        {this.getDate(comment.time)}

                );
              })
            }

    );
  }
};


text:
package org.apache.hadoop.yarn.server.applicationhistoryservice;

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

import junit.framework.Assert;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainersRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainersResponse;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptReport;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerReport;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestApplicationHistoryClientService extends
    ApplicationHistoryStoreTestUtils {

  ApplicationHistoryServer historyServer = null;
  String expectedLogUrl = null;

  @Before
  public void setup() {
    historyServer = new ApplicationHistoryServer();
    Configuration config = new YarnConfiguration();
    expectedLogUrl = WebAppUtils.getHttpSchemePrefix(config) +
        WebAppUtils.getAHSWebAppURLWithoutScheme(config) +
        "/applicationhistory/logs/localhost:0/container_0_0001_01_000001/" +
        "container_0_0001_01_000001/test user";
    config.setClass(YarnConfiguration.APPLICATION_HISTORY_STORE,
      MemoryApplicationHistoryStore.class, ApplicationHistoryStore.class);
    historyServer.init(config);
    historyServer.start();
    store =
        ((ApplicationHistoryManagerImpl) historyServer.getApplicationHistory())
          .getHistoryStore();
  }

  @After
  public void tearDown() throws Exception {
    historyServer.stop();
  }

  @Test
  public void testApplicationReport() throws IOException, YarnException {
    ApplicationId appId = null;
    appId = ApplicationId.newInstance(0, 1);
    writeApplicationStartData(appId);
    writeApplicationFinishData(appId);
    GetApplicationReportRequest request =
        GetApplicationReportRequest.newInstance(appId);
    GetApplicationReportResponse response =
        historyServer.getClientService().getClientHandler()
          .getApplicationReport(request);
    ApplicationReport appReport = response.getApplicationReport();
    Assert.assertNotNull(appReport);
    Assert.assertEquals("application_0_0001", appReport.getApplicationId()
      .toString());
    Assert.assertEquals("test type", appReport.getApplicationType().toString());
    Assert.assertEquals("test queue", appReport.getQueue().toString());
  }

  @Test
  public void testApplications() throws IOException, YarnException {
    ApplicationId appId = null;
    appId = ApplicationId.newInstance(0, 1);
    writeApplicationStartData(appId);
    writeApplicationFinishData(appId);
    ApplicationId appId1 = ApplicationId.newInstance(0, 2);
    writeApplicationStartData(appId1);
    writeApplicationFinishData(appId1);
    GetApplicationsRequest request = GetApplicationsRequest.newInstance();
    GetApplicationsResponse response =
        historyServer.getClientService().getClientHandler()
          .getApplications(request);
    List<ApplicationReport> appReport = response.getApplicationList();
    Assert.assertNotNull(appReport);
    Assert.assertEquals(appId, appReport.get(0).getApplicationId());
    Assert.assertEquals(appId1, appReport.get(1).getApplicationId());
  }

  @Test
  public void testApplicationAttemptReport() throws IOException, YarnException {
    ApplicationId appId = ApplicationId.newInstance(0, 1);
    ApplicationAttemptId appAttemptId =
        ApplicationAttemptId.newInstance(appId, 1);
    writeApplicationAttemptStartData(appAttemptId);
    writeApplicationAttemptFinishData(appAttemptId);
    GetApplicationAttemptReportRequest request =
        GetApplicationAttemptReportRequest.newInstance(appAttemptId);
    GetApplicationAttemptReportResponse response =
        historyServer.getClientService().getClientHandler()
          .getApplicationAttemptReport(request);
    ApplicationAttemptReport attemptReport =
        response.getApplicationAttemptReport();
    Assert.assertNotNull(attemptReport);
    Assert.assertEquals("appattempt_0_0001_000001", attemptReport
      .getApplicationAttemptId().toString());
  }

  @Test
  public void testApplicationAttempts() throws IOException, YarnException {
    ApplicationId appId = ApplicationId.newInstance(0, 1);
    ApplicationAttemptId appAttemptId =
        ApplicationAttemptId.newInstance(appId, 1);
    ApplicationAttemptId appAttemptId1 =
        ApplicationAttemptId.newInstance(appId, 2);
    writeApplicationAttemptStartData(appAttemptId);
    writeApplicationAttemptFinishData(appAttemptId);
    writeApplicationAttemptStartData(appAttemptId1);
    writeApplicationAttemptFinishData(appAttemptId1);
    GetApplicationAttemptsRequest request =
        GetApplicationAttemptsRequest.newInstance(appId);
    GetApplicationAttemptsResponse response =
        historyServer.getClientService().getClientHandler()
          .getApplicationAttempts(request);
    List<ApplicationAttemptReport> attemptReports =
        response.getApplicationAttemptList();
    Assert.assertNotNull(attemptReports);
    Assert.assertEquals(appAttemptId, attemptReports.get(0)
      .getApplicationAttemptId());
    Assert.assertEquals(appAttemptId1, attemptReports.get(1)
      .getApplicationAttemptId());
  }

  @Test
  public void testContainerReport() throws IOException, YarnException {
    ApplicationId appId = ApplicationId.newInstance(0, 1);
    writeApplicationStartData(appId);
    ApplicationAttemptId appAttemptId =
        ApplicationAttemptId.newInstance(appId, 1);
    ContainerId containerId = ContainerId.newInstance(appAttemptId, 1);
    writeContainerStartData(containerId);
    writeContainerFinishData(containerId);
    writeApplicationFinishData(appId);
    GetContainerReportRequest request =
        GetContainerReportRequest.newInstance(containerId);
    GetContainerReportResponse response =
        historyServer.getClientService().getClientHandler()
          .getContainerReport(request);
    ContainerReport container = response.getContainerReport();
    Assert.assertNotNull(container);
    Assert.assertEquals(containerId, container.getContainerId());
    Assert.assertEquals(expectedLogUrl, container.getLogUrl());
  }

  @Test
  public void testContainers() throws IOException, YarnException {
    ApplicationId appId = ApplicationId.newInstance(0, 1);
    writeApplicationStartData(appId);
    ApplicationAttemptId appAttemptId =
        ApplicationAttemptId.newInstance(appId, 1);
    ContainerId containerId = ContainerId.newInstance(appAttemptId, 1);
    ContainerId containerId1 = ContainerId.newInstance(appAttemptId, 2);
    writeContainerStartData(containerId);
    writeContainerFinishData(containerId);
    writeContainerStartData(containerId1);
    writeContainerFinishData(containerId1);
    writeApplicationFinishData(appId);
    GetContainersRequest request =
        GetContainersRequest.newInstance(appAttemptId);
    GetContainersResponse response =
        historyServer.getClientService().getClientHandler()
          .getContainers(request);
    List<ContainerReport> containers = response.getContainerList();
    Assert.assertNotNull(containers);
    Assert.assertEquals(containerId, containers.get(1).getContainerId());
    Assert.assertEquals(containerId1, containers.get(0).getContainerId());
  }
}


text:
<?php

namespace SpecificationGeneration\Domain\Exception;

/**
 * @author Guillaume MOREL <github.com/gmorel>
 */
class UnableToWriteSpecificationException extends \Exception
{

}


text:
package org.jmxtrans.agent.util.collect;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;

/**
 * Inspired by com.google.common.collect.Iterables.
 *
 * @author Cyrille Le Clerc
 */
public class Iterables2 {

    /**
     * Returns the element at the specified position in an iterable.
     *
     * @param iterable the iterable to search into
     * @param position the position of the entry to return
     * @return the entry at the given location in the given iterable
     *         throws
     * @throws IndexOutOfBoundsException if given {@code position} is negative or
     *                                   greater than or equal to the size of given iterable
     */
    @Nullable
    public static <T> T get(@Nonnull Iterable<T> iterable, @Nonnegative int position) throws NullPointerException, IndexOutOfBoundsException {
        if (iterable == null)
            throw new NullPointerException("iterable");

        if (iterable instanceof List) {
            return ((List<T>) iterable).get(position);
        }

        if (position < 0)
            throw new IndexOutOfBoundsException("Requested position must be greater than 0, '" + position + "' is invalid");

        int idx = 0;
        for (T value : iterable) {
            if (idx == position) {
                return value;
            }
            idx++;
        }
        throw new IndexOutOfBoundsException("Requested position must be smaller than iterable size (" + idx + "), '" + position + "' is invalid");
    }
}


text:
namespace google {
namespace protobuf {
namespace compiler {
namespace php {

class LIBPROTOC_EXPORT Generator
    : public google::protobuf::compiler::CodeGenerator {
  virtual bool Generate(
      const FileDescriptor* file,
      const string& parameter,
      GeneratorContext* generator_context,
      string* error) const;
};

// To skip reserved keywords in php, some generated classname are prefixed.
// Other code generators may need following API to figure out the actual
// classname.
LIBPROTOC_EXPORT std::string GeneratedClassName(
    const google::protobuf::Descriptor* desc);
LIBPROTOC_EXPORT std::string GeneratedClassName(
    const google::protobuf::EnumDescriptor* desc);
LIBPROTOC_EXPORT std::string GeneratedClassName(
    const google::protobuf::ServiceDescriptor* desc);

}  // namespace php
}  // namespace compiler
}  // namespace protobuf
}  // namespace google

#endif  // GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__


text:
<?php

namespace Batna\ToolsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{

    public function indexAction($name)
    {
        return $this->render('BatnaToolsBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
package lang

import (
	"github.com/Frederick-S/jvmgo/native_methods"
	"github.com/Frederick-S/jvmgo/runtime_data_area"
	"github.com/Frederick-S/jvmgo/runtime_data_area/heap"
)

const javaLangClass = "java/lang/Class"

func init() {
	native_methods.RegisterNativeMethod(javaLangClass, "getPrimitiveClass", "(Ljava/lang/String;)Ljava/lang/Class;", getPrimitiveClass)
	native_methods.RegisterNativeMethod(javaLangClass, "getName0", "()Ljava/lang/String;", getName0)
	native_methods.RegisterNativeMethod(javaLangClass, "desiredAssertionStatus0", "(Ljava/lang/Class;)Z", desiredAssertionStatus0)
}

func getPrimitiveClass(frame *runtime_data_area.Frame) {
	nameObject := frame.GetLocalVariables().GetReferenceValue(0)
	name := heap.ConvertJavaStringToGoString(nameObject)

	classLoader := frame.GetMethod().GetClass().GetClassLoader()
	class := classLoader.LoadClass(name).GetJavaClass()

	frame.GetOperandStack().PushReferenceValue(class)
}

func getName0(frame *runtime_data_area.Frame) {
	class := frame.GetLocalVariables().GetThis().GetExtraData().(*heap.Class)

	name := class.GetJavaName()
	nameObject := heap.ConvertGoStringToJavaString(class.GetClassLoader(), name)

	frame.GetOperandStack().PushReferenceValue(nameObject)
}

func desiredAssertionStatus0(frame *runtime_data_area.Frame) {
	frame.GetOperandStack().PushBooleanValue(false)
}

func isInterface(frame *runtime_data_area.Frame) {
	class := frame.GetLocalVariables().GetThis().GetExtraData().(*heap.Class)

	frame.GetOperandStack().PushBooleanValue(class.IsInterface())
}

func isPrimitive(frame *runtime_data_area.Frame) {
	class := frame.GetLocalVariables().GetThis().GetExtraData().(*heap.Class)

	frame.GetOperandStack().PushBooleanValue(class.IsPrimitive())
}


text:
package majordodo.daemons;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

/**
 * Lock sul pid file, per evitare avvii concorrenti del servizio
 *
 * @author enrico.olivelli
 */
public class PidFileLocker implements AutoCloseable {

    private final Path file;
    private final byte[] pid;
    private final static String PIDFILE = System.getProperty("pidfile", "");

    public PidFileLocker(Path basePath) {
        this.file = basePath.resolve(PIDFILE);
        String _pid = ManagementFactory.getRuntimeMXBean().getName();
        int choi = _pid.indexOf('@');
        _pid = _pid.substring(0, choi);
        System.out.println("Current process PID:" + _pid);
        this.pid = _pid.getBytes(StandardCharsets.UTF_8);
    }

    public void lock() throws IOException {
        if (PIDFILE.isEmpty()) {
            return;
        }
        System.out.println("Creating and locking file " + file.toAbsolutePath());
        if (Files.exists(file)) {
            throw new IOException("file " + file.toAbsolutePath() + " already exists");
        }
        Files.write(file, pid, StandardOpenOption.CREATE_NEW);
    }

    public void check() throws Exception {
        if (PIDFILE.isEmpty()) {
            return;
        }
        if (!Files.isRegularFile(file)) {
            System.out.println("Lock file " + file.toAbsolutePath() + " does not exists any more. stopping service");
            throw new Exception("Lock file " + file.toAbsolutePath() + " does not exists any more. stopping service");
        } else {
            byte[] actualContent;
            try {
                actualContent = Files.readAllBytes(file);
            } catch (IOException err) {
                System.out.println("Lock file " + file.toAbsolutePath() + " cannot be read (" + err + "). stopping service");
                throw new Exception("Lock file " + file.toAbsolutePath() + " cannot be read (" + err + "). stopping service", err);
            }
            if (!Arrays.equals(pid, actualContent)) {
                System.out.println("Lock file " + file.toAbsolutePath() + " changed, now contains " + new String(actualContent, StandardCharsets.UTF_8) + ". stopping service");
                throw new Exception("Lock file " + file.toAbsolutePath() + " changed, now contains " + new String(actualContent, StandardCharsets.UTF_8) + ". stopping service");
            }
        }
    }

    @Override
    public void close() {
        if (PIDFILE.isEmpty()) {
            return;
        }
        try {
            Files.deleteIfExists(file);
        } catch (IOException err) {
        }
    }

}


text:
using Lucene.Net.QueryParsers.Flexible.Core.Nodes;
using Lucene.Net.QueryParsers.Flexible.Core.Processors;
using Lucene.Net.QueryParsers.Flexible.Standard.Nodes;
using System.Collections.Generic;

namespace Lucene.Net.QueryParsers.Flexible.Standard.Processors
{

    /// <summary>
    /// This processor removes invalid <see cref="SlopQueryNode"/> objects in the query
    /// node tree. A <see cref="SlopQueryNode"/> is invalid if its child is neither a
    /// <see cref="TokenizedPhraseQueryNode"/> nor a <see cref="MultiPhraseQueryNode"/>.
    /// </summary>
    /// <seealso cref="SlopQueryNode"/>
    public class PhraseSlopQueryNodeProcessor : QueryNodeProcessor
    {
        public PhraseSlopQueryNodeProcessor()
        {
            // empty constructor
        }

        protected override IQueryNode PostProcessNode(IQueryNode node)
        {
            if (node is SlopQueryNode phraseSlopNode)
            {
                if (!(phraseSlopNode.GetChild() is TokenizedPhraseQueryNode)
                    && !(phraseSlopNode.GetChild() is MultiPhraseQueryNode))
                {
                    return phraseSlopNode.GetChild();
                }
            }

            return node;
        }

        protected override IQueryNode PreProcessNode(IQueryNode node)
        {
            return node;
        }

        protected override IList<IQueryNode> SetChildrenOrder(IList<IQueryNode> children)
        {
            return children;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven>
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="objectMapper" ref="jacksonObjectMapper"/>
			</bean>
    	</mvc:message-converters>
	</mvc:annotation-driven>
	<!-- <mvc:interceptors>
	    <ref bean="customerCacheController"/>
	</mvc:interceptors> -->
	<!-- customizacion de jackson -->
	<bean id="jacksonObjectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
	<bean id="JacksonConfiguration" class="technology.tikal.gae.jackson.JacksonBasicConfiguration" init-method="init">
		<property name="objectMapper" ref="jacksonObjectMapper"/>
	</bean>
	<!-- i18n -->
	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    	<property name="basename" value="/WEB-INF/resources/i18n/ValidationMessages" />
  	</bean>

</beans>


text:
package pl.pzagawa.diamond.jack.ui;

import java.sql.SQLException;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;

public abstract class OperationWithProgress
{
	private final String title;
	private final String text;
	private final Handler uiHandler = new Handler();

	public OperationWithProgress(String title, String text)
	{
		this.title = title;
		this.text = text;
	}

	public void run(Context context)
	{
		final ProgressDialog progress = ProgressDialog.show(context, title, text, true);

		//do worker thread
		Thread th = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					runWorkerThread();
				}
				catch (SQLException e1)
				{
					e1.printStackTrace();
				}

				//call event on UI thread when finish
				uiHandler.post(new Runnable()
				{
					@Override
					public void run()
					{
						try
						{
							progress.dismiss();
						}
						catch(Exception e)
						{
						}

						runFinishUiThread();
					}
				});
			}
		});

		th.start();
	}

	protected abstract void runWorkerThread()
		throws SQLException;

	protected abstract void runFinishUiThread();

}