text:
package com.phloc.commons.jaxb.validation;

import java.net.URL;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.ValidationEventLocator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;

import com.phloc.commons.annotations.OverrideOnDemand;
import com.phloc.commons.error.EErrorLevel;
import com.phloc.commons.error.IResourceError;
import com.phloc.commons.error.IResourceLocation;
import com.phloc.commons.error.ResourceError;
import com.phloc.commons.error.ResourceLocation;
import com.phloc.commons.string.ToStringGenerator;
import com.phloc.commons.xml.serialize.XMLWriter;

/**
 * An abstract implementation of the JAXB {@link ValidationEventHandler}
 * interface.
 *
 * @author Philip Helger
 */
@NotThreadSafe
public abstract class AbstractValidationEventHandler implements ValidationEventHandler
{
  private static final Logger s_aLogger = LoggerFactory.getLogger (AbstractValidationEventHandler.class);

  private final ValidationEventHandler m_aWrappedHandler;

  /**
   * Constructor not encapsulating any existing handler.
   */
  public AbstractValidationEventHandler ()
  {
    this (null);
  }

  /**
   * Constructor.
   *
   * @param aWrappedHandler
   *        Optional validation event handler to be invoked after this handler.
   *        May be null.
   */
  public AbstractValidationEventHandler (@Nullable final ValidationEventHandler aWrappedHandler)
  {
    m_aWrappedHandler = aWrappedHandler;
  }

  /**
   * @return The original validation event handler passed in the constructor.
   */
  @Nullable
  public final ValidationEventHandler getWrappedHandler ()
  {
    return m_aWrappedHandler;
  }

  /**
   * Get the error level matching the passed JAXB severity.
   *
   * @param nSeverity
   *        The JAXB severity.
   * @return The matching {@link EErrorLevel}. Never null.
   */
  @Nonnull
  @OverrideOnDemand
  protected EErrorLevel getErrorLevel (final int nSeverity)
  {
    switch (nSeverity)
    {
      case ValidationEvent.WARNING:
        return EErrorLevel.WARN;
      case ValidationEvent.ERROR:
        return EErrorLevel.ERROR;
      case ValidationEvent.FATAL_ERROR:
        return EErrorLevel.FATAL_ERROR;
      default:
        s_aLogger.warn ("Unknown JAXB validation severity: " + nSeverity + "; defaulting to error");
        return EErrorLevel.ERROR;
    }
  }

  @Nullable
  @OverrideOnDemand
  protected String getLocationResourceID (@Nullable final ValidationEventLocator aLocator)
  {
    if (aLocator != null)
    {
      // Source file found?
      final URL aURL = aLocator.getURL ();
      if (aURL != null)
        return aURL.toString ();

      // Source object found?
      final Object aObj = aLocator.getObject ();
      if (aObj != null)
        return "obj: " + aObj.toString ();

      // Source node found?
      final Node aNode = aLocator.getNode ();
      if (aNode != null)
        return XMLWriter.getXMLString (aNode);
    }
    return null;
  }

  protected abstract void onEvent (@Nonnull IResourceError aEvent);

  /**
   * Should the processing be continued? By default it is always continued, as
   * long as no fatal error occurs. This method is only invoked, if no wrapped
   * handler is present.
   *
   * @param eErrorLevel
   *        The error level to be checked.
   * @return true if processing should be continued,
   *         false if processing should stop.
   */
  @OverrideOnDemand
  protected boolean continueProcessing (@Nonnull final EErrorLevel eErrorLevel)
  {
    // Continue as long as it is no fatal error. On Fatal error stop!
    return eErrorLevel.isLessSevereThan (EErrorLevel.FATAL_ERROR);
  }

  public final boolean handleEvent (@Nonnull final ValidationEvent aEvent)
  {
    final EErrorLevel eErrorLevel = getErrorLevel (aEvent.getSeverity ());

    // call our callback
    final ValidationEventLocator aLocator = aEvent.getLocator ();
    final IResourceLocation aLocation = new ResourceLocation (getLocationResourceID (aLocator),
                                                              aLocator != null ? aLocator.getLineNumber ()
                                                                              : IResourceLocation.ILLEGAL_NUMBER,
                                                              aLocator != null ? aLocator.getColumnNumber ()
                                                                              : IResourceLocation.ILLEGAL_NUMBER);
    // Message may be null in some cases (e.g. when a linked exception is
    // present), but is not allowed to be null!
    String sMsg = aEvent.getMessage ();
    if (sMsg == null)
    {
      if (aEvent.getLinkedException () != null)
      {
        sMsg = aEvent.getLinkedException ().getMessage ();
        if (sMsg == null)
          sMsg = "Exception";
      }
      else
      {
        // Does this ever happen????
        sMsg = "Validation event";
      }
    }
    onEvent (new ResourceError (aLocation, eErrorLevel, sMsg, aEvent.getLinkedException ()));

    if (m_aWrappedHandler != null)
    {
      // call wrapped handler
      return m_aWrappedHandler.handleEvent (aEvent);
    }

    // Continue processing?
    return continueProcessing (eErrorLevel);
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("wrappedHandler", m_aWrappedHandler).toString ();
  }
}


text:
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Divelements.SandRibbon;
using MeTLLib.DataTypes;
using MeTLLib.Providers.Connection;
using Microsoft.Practices.Composite.Presentation.Commands;
using SandRibbon.Components.BannedContent;
using SandRibbon.Providers;
using System.Windows.Input;
using SandRibbon.Utils;

namespace SandRibbon.Tabs
{
    public partial class ConversationManagement : RibbonTab
    {
        public List<TargettedSubmission> submissionList = new List<TargettedSubmission>();
        public static RoutedCommand ManageBannedContent = new RoutedCommand();
        public ConversationManagement()
        {
            InitializeComponent();
            Commands.UpdateConversationDetails.RegisterCommandToDispatcher(new DelegateCommand<ConversationDetails>(updateConversationDetails));
            Commands.JoinConversation.RegisterCommandToDispatcher(new DelegateCommand<string>(JoinConversation));
            Commands.ReceiveScreenshotSubmission.RegisterCommand(new DelegateCommand<TargettedSubmission>(receiveSubmission));
            Commands.PreParserAvailable.RegisterCommand(new DelegateCommand<PreParser>(PreParserAvailable));
            Commands.ViewBannedContent.RegisterCommand(new DelegateCommand<object>(viewBannedContent, canViewBannedContent));
        }

        private void viewBannedContent(object _obj)
        {
            var bannedContent = new BannedContent(submissionList);
            bannedContent.Owner = Window.GetWindow(this);
            bannedContent.Show();
            banContent.IsChecked = false;
            Commands.BanhammerActive.Execute(false);
            ManageBannedContent.Execute(null, null);
        }

        private bool canViewBannedContent(object _e)
        {
            return submissionList.Count > 0;
        }

        private void CheckManageBannedAllowed(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = StateHelper.mustBeInConversation();
        }

        private void PreParserAvailable(PreParser parser)
        {
            foreach (var submission in parser.submissions)
                receiveSubmission(submission);
        }
        private void updateConversationDetails(ConversationDetails details)
        {
            editConversation.Visibility = details.Author == Globals.me ? Visibility.Visible : Visibility.Collapsed;
            banContent.Visibility = Globals.isAuthor ? Visibility.Visible : Visibility.Collapsed;
            bannedContentManagement.Visibility = banContent.Visibility;
        }

        private void JoinConversation(string jid)
        {
            submissionList.Clear();
        }

        private void receiveSubmission(MeTLLib.DataTypes.TargettedSubmission submission)
        {
            if (string.IsNullOrEmpty(submission.target) || submission.target != "bannedcontent")
                return;

            if (!IHaveThisSubmission(submission))
            {
                submissionList.Add(submission);
                Commands.RequerySuggested(Commands.ViewBannedContent);
            }
        }

        private bool IHaveThisSubmission(MeTLLib.DataTypes.TargettedSubmission submission)
        {
            if (submissionList.Where(s => s.time == submission.time && s.author == submission.author && s.url == submission.url).ToList().Count > 0)
                return true;
            return false;
        }

        private void OnBanContentchanged(object sender, ExecutedRoutedEventArgs e)
        {
            var banMode = banContent.IsChecked ?? false;
            Commands.BanhammerActive.Execute(banMode);
            if (banMode)
            {
                Commands.SetInkCanvasMode.Execute("Select");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.langellu.jobs;

import com.fasterxml.jackson.annotation.JsonProperty;

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

public class JobConfiguration {

    @JsonProperty("quartz")
    private Map<String, String> quartzConfiguration = new HashMap<>();

    public Map<String, String> getQuartzConfiguration() {
        return quartzConfiguration;
    }

    public void setQuartzConfiguration(Map<String, String> quartzConfiguration) {
        this.quartzConfiguration = quartzConfiguration;
    }
}


text:
if Rails.env.production?
    CarrierWave.configure do |config|
        config.fog_credentials = {
            :provider => 'AWS',
            :aws_access_key_id => ENV['S3_ACCESS_KEY'],
            :aws_secret_access_key => ENV['S3_SECRET_KEY']
        }

        config.fog_directory = ENV['S3_BUCKET']
    end
end


text:
class Button
 {typedef int Boolean;
  enum {off, on};

  public:
    Button(Display* display, Drawable& drawable,
           const char* const label, const XFontStruct* const,
           XColor& foreground, XColor& backGround,
           const int upperLeftX, const int upperLeftY,
           const int borderWidth=5);
    Button(Display* display, Drawable& drawable,
           const char* const label, const XFontStruct* const,
           XColor& foreground, XColor& backGround,
           const int upperLeftX, const int upperLeftY,
           XColor& upperBorder, XColor& lowerBorder,
           const int borderWidth=5);
    ~Button();
    Button& PressButton();
    Button& ReleaseButton();
    const Button& DrawButton() const;
    Boolean PointerOnButton(const XButtonEvent&) const;
    Boolean PointerOnButton(const XPointerMovedEvent&) const;
    Boolean ButtonPressed() const;
    const int ButtonWidth() const;
    const int ButtonHeight() const;

  private:
    Button(const Button&);
    Button& operator=(const Button&);
    void CreateButton(const char* const label, const XFontStruct* const fontInfo,
                      XColor& foreground, XColor& background,
                      XColor& topBorderColor, XColor& bottomBorderColor);
    void FindColorChange(const int colorValue, int& minChange, Boolean& lowSideMin);

    static const int borderPercentVariance;

    Display* display;

    Drawable& drawable;

    Pixmap buttonUp,
           buttonDown;

    GC buttonGC;

    int upperLeftX,
        upperLeftY,
        borderWidth,
        buttonWidth,
        buttonHeight;

    Boolean buttonPressed;
 };

const int Button::borderPercentVariance=25;

inline void Button::CreateButton(const char* const label, const XFontStruct* const fontInfo,
                                 XColor& fg, XColor& bg,
                                 XColor& topBorderColor, XColor& bottomBorderColor)
 {int screen=DefaultScreen(display),
      foreground=XAllocColor(display,DefaultColormap(display,screen),&fg)
                ? fg.pixel
                : WhitePixel(display,screen),
      background=XAllocColor(display,DefaultColormap(display,screen),&bg)
                ? bg.pixel
                : BlackPixel(display,screen),
      topBorder=XAllocColor(display,DefaultColormap(display,screen),&topBorderColor)
               ? topBorderColor.pixel
               : WhitePixel(display,screen),
      bottomBorder=XAllocColor(display,DefaultColormap(display,screen),&bottomBorderColor)
                  ? bottomBorderColor.pixel
                  : BlackPixel(display,screen);
  buttonUp=XCreatePixmap(display,drawable,buttonWidth,buttonHeight,
                         DefaultDepth(display,screen));
  buttonDown=XCreatePixmap(display,drawable,buttonWidth,buttonHeight,
                           DefaultDepth(display,screen));
  buttonGC=XCreateGC(display,drawable,NULL,0);
  XSetForeground(display,buttonGC,background);
  XSetBackground(display,buttonGC,background);
  XSetGraphicsExposures(display,buttonGC,FALSE);
  XFillRectangle(display,buttonUp,buttonGC,borderWidth,borderWidth,
                 buttonWidth-borderWidth-1,buttonHeight-borderWidth-1);
  XFillRectangle(display,buttonDown,buttonGC,borderWidth,borderWidth,
                 buttonWidth-borderWidth-1,buttonHeight-borderWidth-1);
  XSetLineAttributes(display,buttonGC,1,LineSolid,CapButt,JoinMiter);
  XPoint points[7];
  points[0].x=0;                       points[0].y=0;
  points[1].x=buttonWidth-1;           points[1].y=0;
  points[2].x=buttonWidth-borderWidth; points[2].y=borderWidth-1;
  points[3].x=borderWidth-1;           points[3].y=borderWidth-1;
  points[4].x=borderWidth-1;           points[4].y=buttonHeight-borderWidth;
  points[5].x=0;                       points[5].y=buttonHeight-1;
  points[6]=points[0];
  XSetForeground(display,buttonGC,topBorder);
  XFillPolygon(display,buttonUp,buttonGC,points,7,Nonconvex,CoordModeOrigin);
  XDrawLines(display,buttonUp,buttonGC,points,7,CoordModeOrigin);
  XFillPolygon(display,buttonDown,buttonGC,points,7,Nonconvex,CoordModeOrigin);
  XDrawLines(display,buttonDown,buttonGC,points,7,CoordModeOrigin);
  points[0].x=0;                       points[0].y=buttonHeight-1;
  points[1].x=buttonWidth-1;           points[1].y=buttonHeight-1;
  points[2].x=buttonWidth-1;           points[2].y=0;
  points[3].x=buttonWidth-borderWidth; points[3].y=borderWidth-1;
  points[4].x=buttonWidth-borderWidth; points[4].y=buttonHeight-borderWidth;
  points[5].x=borderWidth-1;           points[5].y=buttonHeight-borderWidth;
  points[6]=points[0];
  XSetForeground(display,buttonGC,bottomBorder);
  XFillPolygon(display,buttonUp,buttonGC,points,7,Nonconvex,CoordModeOrigin);
  XDrawLines(display,buttonUp,buttonGC,points,7,CoordModeOrigin);
  XFillPolygon(display,buttonDown,buttonGC,points,7,Nonconvex,CoordModeOrigin);
  XDrawLines(display,buttonDown,buttonGC,points,7,CoordModeOrigin);
  points[0].x=0;             points[0].y=0;
  points[1].x=buttonWidth-1; points[1].y=0;
  points[2].x=buttonWidth-1; points[2].y=buttonHeight-1;
  points[3].x=0;             points[3].y=buttonHeight-1;
  points[4]=points[0];
  XSetForeground(display,buttonGC,BlackPixel(display,screen));
  XDrawLines(display,buttonUp,buttonGC,points,5,CoordModeOrigin);
  points[0].x=1;             points[0].y=1;
  points[1].x=buttonWidth-2; points[1].y=1;
  points[2].x=buttonWidth-2; points[2].y=buttonHeight-2;
  points[3].x=1;             points[3].y=buttonHeight-2;
  points[4]=points[0];
  XSetLineAttributes(display,buttonGC,3,LineSolid,CapButt,JoinMiter);
  XDrawLines(display,buttonDown,buttonGC,points,5,CoordModeOrigin);
  XSetForeground(display,buttonGC,foreground);
  XSetFont(display,buttonGC,fontInfo->fid);
  int direction,
      ascent,
      descent;
  XCharStruct charInfo;
  XTextExtents((XFontStruct*)fontInfo,label,1,&direction,&ascent,&descent,&charInfo);
  XDrawImageString(display,buttonUp,buttonGC,
                   borderWidth+3-charInfo.lbearing,borderWidth+3+fontInfo->max_bounds.ascent,
                   label,strlen(label));
  XDrawImageString(display,buttonDown,buttonGC,
                   borderWidth+3-charInfo.lbearing,borderWidth+3+fontInfo->max_bounds.ascent,
                   label,strlen(label));
 }

inline void Button::FindColorChange(const int colorValue, int& minChange, Boolean& lowSideMin)
 {if (colorValue<65535-colorValue)
   {if (colorValue<minChange)
     {minChange=colorValue;
      lowSideMin=on;
     }
   }
  else
    if (65535-colorValue<minChange)
     {minChange=65535-colorValue;
      lowSideMin=off;
     }
 }

inline Button::Button(Display* disp, Drawable& draw,
                      const char* const label, const XFontStruct* const fontInfo,
                      XColor& fg, XColor& bg,
                      const int x, const int y,
		                  const int borderSize): display(disp),
                                             drawable(draw),
                                             upperLeftX(x),
                                             upperLeftY(y),
                                             borderWidth(borderSize>3 ? borderSize
                                                                      : 3),
                                             buttonWidth(XTextWidth((XFontStruct*)fontInfo,
                                                                    label,strlen(label))+6
                                                         +2*borderSize),
                                             buttonHeight(fontInfo->max_bounds.ascent
                                                         +fontInfo->max_bounds.descent+6
                                                         +2*borderSize),
                                             buttonPressed(off)
 {int minChange=65535;
  Boolean lowSideMin;
  FindColorChange(bg.red,minChange,lowSideMin);
  FindColorChange(bg.green,minChange,lowSideMin);
  FindColorChange(bg.blue,minChange,lowSideMin);
  int redChange,
      greenChange,
      blueChange;
  if (lowSideMin)
   {redChange=(bg.red+50)*borderPercentVariance/100;
    greenChange=(bg.green+50)*borderPercentVariance/100;
    blueChange=(bg.blue+50)*borderPercentVariance/100;
   }
  else
   {redChange=(65535-bg.red+50)*borderPercentVariance/100;
    greenChange=(65535-bg.green+50)*borderPercentVariance/100;
    blueChange=(65535-bg.blue+50)*borderPercentVariance/100;
   }
  XColor topBorderColor={0,
                         bg.red+redChange,
                         bg.green+greenChange,
                         bg.blue+blueChange,
                         DoRed|DoGreen|DoBlue},
	 bottomBorderColor={0,
                            bg.red-redChange,
                            bg.green-greenChange,
                            bg.blue-blueChange,
                            DoRed|DoGreen|DoBlue};
  CreateButton(label,fontInfo,fg,bg,topBorderColor,bottomBorderColor);
 }

inline Button::Button(Display* disp, Drawable& draw,
                      const char* const label, const XFontStruct* const fontInfo,
                      XColor& fg, XColor& bg,
                      const int x, const int y,
                      XColor& topBorderColor, XColor& bottomBorderColor,
		                  const int borderSize): display(disp),
                                             drawable(draw),
                                             upperLeftX(x),
                                             upperLeftY(y),
                                             borderWidth(borderSize>3 ? borderSize
                                                                      : 3),
                                             buttonWidth(XTextWidth((XFontStruct*)fontInfo,
                                                                    label,strlen(label))+6
                                                         +2*borderSize),
                                             buttonHeight(fontInfo->max_bounds.ascent
                                                          +fontInfo->max_bounds.descent+6
                                                          +2*borderSize),
                                             buttonPressed(off)
 {CreateButton(label,fontInfo,fg,bg,topBorderColor,bottomBorderColor);
 }

inline Button::~Button()
 {XFreeGC(display,buttonGC);
  XFreePixmap(display,buttonDown);
  XFreePixmap(display,buttonUp);
 }

inline Button& Button::PressButton()
 {XCopyArea(display,
            buttonDown,
            drawable,
            buttonGC,
            0,0,
	          buttonWidth,buttonHeight,
            upperLeftX,upperLeftY);
  buttonPressed=on;
  return *this;
 }

inline Button& Button::ReleaseButton()
 {XCopyArea(display,
            buttonUp,
            drawable,
            buttonGC,
            0,0,
	          buttonWidth,buttonHeight,
            upperLeftX,upperLeftY);
  buttonPressed=off;
  return *this;
 }

inline const Button& Button::DrawButton() const
 {if (buttonPressed)
    XCopyArea(display,
              buttonDown,
              drawable,
              buttonGC,
              0,0,
	            buttonWidth,buttonHeight,
              upperLeftX,upperLeftY);
  else
    XCopyArea(display,
              buttonUp,
              drawable,
              buttonGC,
              0,0,
	            buttonWidth,buttonHeight,
              upperLeftX,upperLeftY);
  return *this;
 }

inline Button::Boolean Button::PointerOnButton(const XButtonEvent& event) const
 {return event.x>=upperLeftX && event.x<upperLeftX+buttonWidth &&
         event.y>=upperLeftY && event.y<upperLeftY+buttonHeight;
 }

inline Button::Boolean Button::PointerOnButton(const XPointerMovedEvent& event) const
 {return event.x>=upperLeftX && event.x<upperLeftX+buttonWidth &&
         event.y>=upperLeftY && event.y<upperLeftY+buttonHeight;
 }

inline Button::Boolean Button::ButtonPressed() const
 {return buttonPressed;
 }

inline const int Button::ButtonWidth() const
 {return buttonWidth;
 }

inline const int Button::ButtonHeight() const
 {return buttonHeight;
 }

#endif


text:
void timestatus(int samp_rate,long frameNum,long totalframes, int framesize);

#endif


text:
class Menu:
    def __init__(self):
        pass

    def menu_index(self):
        print("====Menu====")
        print("1.ʵʱ²éѯ")
        print("2.ˢƱ")
        print("============")

    def menu_first_index(self):
        pass

    def menu_second_index(self):
        pass

    def choose(self):
        while True:
            try:
                self.choose = input()
                self.choose = int(self.choose)
                break;
            except ValueError as e:
                print("Plesse Input Right Choose! Try Again.")
        return self.choose

if __name__ == '__main__':
    Menu = Menu()
    Menu.menu_index()
    Menu.choose()


text:
layout: post
title: Peter North - Driving Passion 1
titleinfo: pornvd
desc: Watch Peter North - Driving Passion 1. Pornhub is the ultimate xxx porn and sex site.
---

Peter North - Driving Passion 1

Watch Peter North - Driving Passion 1. Pornhub is the ultimate xxx porn and sex site.


text:
            RDF Turtle Editor checks conformance of RDF data with referenced web ontologies together with RDF syntax and semantic validation.

Features

RDF turtle syntax highlighting

Live RDF turtle syntax validation

Checks conformance of RDF document with Web Ontologies

Parses prefixed ontologies and adds as part of auto-completion

Makes newly defined terms in current document part of auto-completion

Parses prefixed ontologies in both rdf+xml and turtle format

Semantic validation of a term in a triplet i.e. should it be a Predicate or a Concept

...and many more

Acknowledgements

        This work builds on the efforts of many people; a few mentions are

Linkeddata team for [rdflib.js] used for document parsing

Contributors behind [ace editor] that rdfturtleditor extends to incorporate turtle format specifications

[Prefix.cc] that is used to fetch popular prefixes for prefix auto-completion

        and last but not least to technical leads of this work without whom the work would have been completed one month earlier (Yes they challenge in good ways!) :)

In case help is needed!

        Software has to travel the road to maturity, there are no shortcuts. So if you find issues or are not clear about something, below are some pointers

Open issues on GitHUB

Contact: Hammad Aslam Khan


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hort. brit. ed. 2:371. 1830 (G. Don, Gen. hist. 4:270. 1837)

#### Original name
null

### Remarks
null


text:
var debug = require('debug')('server:models:SubmittedFile');
var config = require('../includes/config.js');

var Promise = require('bluebird');

var exec = Promise.promisify(require('child_process').exec);
var fs = Promise.promisifyAll(require('fs'));
var mv = require('mv');

var imageSize = Promise.promisify(require('image-size'));
var md5file = Promise.promisify(require('md5-file'));
var shortId = require('shortid');

var HTTPError = require('node-http-error');

function SubmittedFile() {
	this.tmpPath = 'tmp/' + Date.now().toString() + '_' + Math.random().toString();
}

//remove file from temporary location
SubmittedFile.prototype.unlink = function () {
	debug('SubmittedFile.prototype.unlink');

	return fs.unlinkAsync(this.tmpPath);
};

//check image mime type using `file` command
SubmittedFile.prototype.checkType = function () {
	debug('SubmittedFile.prototype.checkType');

	return exec('file --mime-type ' + this.tmpPath)
	.then(function (stdout) {
		//parse mime from the output
		var mime = stdout.match(/.*: (.*)/)[1];

		debug('`file`', stdout, mime);

		//check if file type is allowed
		if( ! config.upload.acceptedTypes[mime] ) {
			debug('file type not accepted');
			throw new HTTPError(415, 'file type not accepted');
		}

		return config.upload.acceptedTypes[mime];
	})
	.catch(function (err) {
		debug('error', err);
		throw err;
	});
};

//check if file dimensions exceed max allowed
SubmittedFile.prototype.checkDims = function() {
	debug('SubmittedFile.prototype.checkDims');

	//get image size and calculate area
	return imageSize(this.tmpPath)
	.then(function (dimensions) {
		var mp = dimensions.width * dimensions.height;

		if( mp > config.upload.maxDims ) {
			throw new HTTPError(413, 'file dimensions too big');
		}

		return {
			width: dimensions.width,
			height: dimensions.height
		};
	})
	.catch(function (err) {
		debug('error', err);
		throw err;
	});
};

//calculate file md5 and check if it already exists in db
SubmittedFile.prototype.checkMD5 = function(imageModel) {
	debug('SubmittedFile.prototype.checkMD5');

	var fileMd5;

	return md5file(this.tmpPath)
	.then(function (md5) {
		fileMd5 = md5;
		return imageModel.findOne({md5: md5});
	})
	.then(function (image) {
		if( ! image ) {
			return fileMd5;
		}

		image.duplicate = true;
		return image;
	})
	.catch(function (err) {
		debug('error', err);
		throw err;
	});
};

//do file checks for acceptance and save if valid
SubmittedFile.prototype.fileChecks = function(imageModel) {
	debug('SubmittedFile.prototype.fileChecks');

	var self = this;

	//image data to save
	var image = {};

	return this.checkType()
	.then(function (type) {
		image.type = type;

		return self.checkDims();
	})
	.then(function (dimensions) {
		image.size = dimensions;

		return fs.statAsync(self.tmpPath);
	})
	.then(function (fileStats) {
		image.fileSize = fileStats.size;

		if( image.fileSize > config.upload.sizeLimit ) {
			throw new HTTPError(413, 'file too big');
		}

		return self.checkMD5(imageModel);
	})
	.then(function (imageOrMd5) {
		if( typeof imageOrMd5 === 'object' ) {
			//duplicate found, remove tmp file and return image
			self.unlink();
			image = imageOrMd5;
			return image;
		}

		image.permalink = shortId.generate();
		image.md5 = imageOrMd5;
		image.path = 'images/' + image.permalink;
		image.fileName = image.permalink + '.' + image.type;

		image.originalFileName = self.originalFileName;
		image.url = self.url;
		image.uploaderIP = self.uploaderIP;

		//move file from tmp to its own folder
		return Promise.fromNode(function (callback) {
			return mv(self.tmpPath, image.path + '/' + image.fileName, {mkdirp: true}, callback);
		})
		//save
		.then(function () {
			return imageModel.create(image);
		});
	})
	.catch(function (err) {
		debug('error', err);
		self.unlink();
		throw err;
	});
};

module.exports = SubmittedFile;


text:
"""
Plotter 3D

The Plotter 3D plots data in 3D. It has options for setting a title and legend,
plotting 3D points or 3D Gaussians, and clipping data based off axis limits.

This is used to plot the 3D trajectories, including the trajectory samples,
policy samples, and the linear Gaussian controllers.
"""
import numpy as np
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D

class Plotter3D:
    def __init__(self, fig, gs, num_plots, rows=None, cols=None):
        if cols is None:
            cols = int(np.floor(np.sqrt(num_plots)))
        if rows is None:
            rows = int(np.ceil(float(num_plots)/cols))
        assert num_plots <= rows*cols, 'Too many plots to put into gridspec.'

        self._fig = fig
        self._gs = gridspec.GridSpecFromSubplotSpec(8, 1, subplot_spec=gs)
        self._gs_legend = self._gs[0:1, 0]
        self._gs_plot   = self._gs[1:8, 0]

        self._ax_legend = plt.subplot(self._gs_legend)
        self._ax_legend.get_xaxis().set_visible(False)
        self._ax_legend.get_yaxis().set_visible(False)

        self._gs_plots = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=self._gs_plot)
        self._axarr = [plt.subplot(self._gs_plots[i], projection='3d') for i in range(num_plots)]
        self._lims = [None for i in range(num_plots)]
        self._plots = [[] for i in range(num_plots)]

        for ax in self._axarr:
            ax.tick_params(pad=0)
            ax.locator_params(nbins=5)
            for item in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()):
                item.set_fontsize(10)

        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend

    def set_title(self, i, title):
        self._axarr[i].set_title(title)
        self._axarr[i].title.set_fontsize(10)

    def add_legend(self, linestyle, marker, color, label):
        self._ax_legend.plot([], [], linestyle=linestyle, marker=marker,
                color=color, label=label)
        self._ax_legend.legend(ncol=2, mode='expand', fontsize=10)

    def plot(self, i, xs, ys, zs, linestyle='-', linewidth=1.0, marker=None,
            markersize=5.0, markeredgewidth=1.0, color='black', alpha=1.0, label=''):
        # Manually clip at xlim, ylim, zlim (MPL doesn't support axis limits for 3D plots)
        if self._lims[i]:
            xlim, ylim, zlim = self._lims[i]
            xs[np.any(np.c_[xs < xlim[0], xs > xlim[1]], axis=1)] = np.nan
            ys[np.any(np.c_[ys < ylim[0], ys > ylim[1]], axis=1)] = np.nan
            zs[np.any(np.c_[zs < zlim[0], zs > zlim[1]], axis=1)] = np.nan

        # Create and add plot
        plot = self._axarr[i].plot(xs, ys, zs=zs, linestyle=linestyle,
                linewidth=linewidth, marker=marker, markersize=markersize,
                markeredgewidth=markeredgewidth, color=color, alpha=alpha,
                label=label)[0]
        self._plots[i].append(plot)

    def plot_3d_points(self, i, points, linestyle='-', linewidth=1.0,
            marker=None, markersize=5.0, markeredgewidth=1.0, color='black',
            alpha=1.0, label=''):
        self.plot(i, points[:, 0], points[:, 1], points[:, 2],
                linestyle=linestyle, linewidth=linewidth, marker=marker,
                markersize=markersize, markeredgewidth=markeredgewidth,
                color=color, alpha=alpha, label=label)

    def plot_3d_gaussian(self, i, mu, sigma, edges=100, linestyle='-.',
            linewidth=1.0, color='black', alpha=0.1, label=''):
        """
        Plots ellipses in the xy plane representing the Gaussian distributions
        specified by mu and sigma.
        Args:
            mu    - Tx3 mean vector for (x, y, z)
            sigma - Tx3x3 covariance matrix for (x, y, z)
            edges - the number of edges to use to construct each ellipse
        """
        p = np.linspace(0, 2*np.pi, edges)
        xy_ellipse = np.c_[np.cos(p), np.sin(p)]
        T = mu.shape[0]

        sigma_xy = sigma[:, 0:2, 0:2]
        u, s, v = np.linalg.svd(sigma_xy)

        for t in range(T):
            xyz = np.repeat(mu[t, :].reshape((1, 3)), edges, axis=0)
            xyz[:, 0:2] += np.dot(xy_ellipse, np.dot(np.diag(
                    np.sqrt(s[t, :])), u[t, :, :].T))
            self.plot_3d_points(i, xyz, linestyle=linestyle,
                    linewidth=linewidth, color=color, alpha=alpha, label=label)

    def set_lim(self, i, xlim, ylim, zlim):
        """
        Sets the xlim, ylim, and zlim for plot i
        WARNING: limits must be set before adding data to plots
        Args:
            xlim - a tuple of (x_start, x_end)
            ylim - a tuple of (y_start, y_end)
            zlim - a tuple of (z_start, z_end)
        """
        self._lims[i] = [xlim, ylim, zlim]

    def clear(self, i):
        for plot in self._plots[i]:
            plot.remove()
        self._plots[i] = []

    def clear_all(self):
        for i in range(len(self._plots)):
            self.clear(i)

    def draw(self):
        for ax in self._axarr:
            ax.draw_artist(ax.patch)
        for i in range(len(self._plots)):
            for plot in self._plots[i]:
                self._axarr[i].draw_artist(plot)
        self._fig.canvas.draw()
        self._fig.canvas.flush_events()   # Fixes bug with Qt4Agg backend


text:
require_relative 'core/api'

module Wavefront
  #
  # Manage and query Wavefront maintenance windows
  #
  class MaintenanceWindow < CoreApi
    def update_keys
      %i[id reason title startTimeInSeconds endTimeInSeconds
         relevantCustomerTags relevantHostTags relevantHostNames]
    end

    # GET /api/v2/maintenancewindow
    # Get all maintenance windows for a customer.
    #
    # @param offset [Integer] window at which the list begins
    # @param limit [Integer] the number of window to return
    #
    def list(offset = 0, limit = 100)
      api.get('', offset: offset, limit: limit)
    end

    # POST /api/v2/maintenancewindow
    # Create a maintenance window.
    #
    # We used to validate input here but do not any more.
    #
    # @param body [Hash] a hash of parameters describing the window.
    #   Please refer to the Wavefront Swagger docs for key:value
    #   information
    # @return [Wavefront::Response]
    #
    def create(body)
      raise ArgumentError unless body.is_a?(Hash)

      api.post('', body, 'application/json')
    end

    # DELETE /api/v2/maintenancewindow/id
    # Delete a specific maintenance window.
    #
    # @param id [String, Integer] ID of the maintenance window
    # @return [Wavefront::Response]
    #
    def delete(id)
      wf_maintenance_window_id?(id)
      api.delete(id)
    end

    # GET /api/v2/maintenancewindow/id
    # Get a specific maintenance window.
    #
    # @param id [String, Integer] ID of the maintenance window
    # @return [Wavefront::Response]
    #
    def describe(id)
      wf_maintenance_window_id?(id)
      api.get(id)
    end

    # PUT /api/v2/maintenancewindow/id
    # Update a specific maintenance window.
    #
    # @param id [String] a Wavefront maintenance window ID
    # @param body [Hash] key-value hash of the parameters you wish
    #   to change
    # @param modify [true, false] if true, use {#describe()} to get
    #   a hash describing the existing object, and modify that with
    #   the new body. If false, pass the new body straight through.
    # @return [Wavefront::Response]

    def update(id, body, modify = true)
      wf_maintenance_window_id?(id)
      raise ArgumentError unless body.is_a?(Hash)

      return api.put(id, body, 'application/json') unless modify

      api.put(id, hash_for_update(describe(id).response, body),
              'application/json')
    end

    # Windows currently open.
    # @return [Wavefront::Response]
    #
    def ongoing
      windows_in_state(:ongoing)
    end

    # Get the windows which will be open in the next so-many hours
    # @param hours [Numeric] how many hours to look ahead
    # @return [Wavefront::Response]
    #
    def pending(hours = 24)
      cutoff = Time.now.to_i + hours * 3600

      ret = windows_in_state(:pending)

      return if opts[:noop]

      ret.tap do |r|
        r.response.items.delete_if { |w| w.startTimeInSeconds > cutoff }
      end
    end

    # This method mimics the similarly named method from the v1 SDK,
    # which called the 'GET /api/alert/maintenancewindow/summary'
    # path.
    # @return [Wavefront::Response]
    #
    def summary
      ret = pending

      items = { UPCOMING: ret.response.items,
                CURRENT: ongoing.response.items }

      ret.response.items = items
      ret
    end

    # Return all maintenance windows in the given state. At the time
    # of writing valid states are ONGOING, PENDING, and ENDED.
    # @param state [Symbol]
    # @return [Wavefront::Response]
    #
    def windows_in_state(state)
      require_relative 'search'
      wfs = Wavefront::Search.new(creds, opts)
      query = { key: 'runningState', value: state, matchingMethod: 'EXACT' }
      wfs.search(:maintenancewindow, query, limit: :all, offset: PAGE_SIZE)
    end
  end
end


text:
package webmention

import (
	"bufio"
	"bytes"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/google/go-cmp/cmp"
)

func testServer() (*http.ServeMux, *httptest.Server, func()) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	cleanup := func() {
		server.Close()
	}
	return mux, server, cleanup
}

func TestClient_SendWebmention(t *testing.T) {
	mux, server, cleanup := testServer()
	defer cleanup()

	source, target := "S", "T"

	mux.HandleFunc("/endpoint", func(w http.ResponseWriter, r *http.Request) {
		if got := r.PostFormValue("source"); got != source {
			t.Errorf("request contained source: %v, want %v", got, source)
		}
		if got := r.PostFormValue("target"); got != target {
			t.Errorf("request contained target: %v, want %v", got, target)
		}
	})

	client := New(nil)
	resp, err := client.SendWebmention(server.URL+"/endpoint", source, target)
	resp.Body.Close()
	if err != nil {
		t.Errorf("SendWebmention returned error: %v", err)
	}

	// ensure 404 response is returned as error
	resp, err = client.SendWebmention(server.URL+"/bad", "", "")
	resp.Body.Close()
	if err == nil {
		t.Errorf("SendWebmention did not return expected error")
	}
}

func TestClient_DiscoverEndpoint(t *testing.T) {
	mux, server, cleanup := testServer()
	defer cleanup()
	client := New(nil)

	// valid request with link
	mux.HandleFunc("/good", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `<link href="/endpoint" rel="webmention">`)
	})

	want := server.URL + "/endpoint" // want absolute URL
	if got, err := client.DiscoverEndpoint(server.URL + "/good"); err != nil {
		t.Errorf("DiscoverEndpoint(%q) returned error: %v", server.URL+"/good", err)
	} else if got != want {
		t.Errorf("DiscoverEndpoint(%q) returned %v, want %v", server.URL+"/good", got, want)
	}

	// valid request with no link
	mux.HandleFunc("/nolink", func(w http.ResponseWriter, r *http.Request) {
	})

	want = ""
	if got, err := client.DiscoverEndpoint(server.URL + "/nolink"); err != ErrNoEndpointFound {
		t.Errorf("DiscoverEndpoint(%q) returned error: %v", server.URL+"/nolink", err)
	} else if got != want {
		t.Errorf("DiscoverEndpoint(%q) returned %v, want %v", server.URL+"/nolink", got, want)
	}

	// empty endpoint is a valid relative URL pointing to the page itself
	mux.HandleFunc("/empty", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `<link href="" rel="webmention">`)
	})

	want = server.URL + "/empty" // want absolute URL
	if got, err := client.DiscoverEndpoint(server.URL + "/empty"); err != nil {
		t.Errorf("DiscoverEndpoint(%q) returned error: %v", server.URL+"/empty", err)
	} else if got != want {
		t.Errorf("DiscoverEndpoint(%q) returned %v, want %v", server.URL+"/empty", got, want)
	}

	// relative endpoint behind a redirect
	mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("location", "redirect/relative")
		w.WriteHeader(http.StatusFound)
	})
	mux.HandleFunc("/redirect/relative", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("link", "<endpoint>; rel=webmention")
		w.WriteHeader(http.StatusOK)
	})

	want = server.URL + "/redirect/endpoint"
	if got, err := client.DiscoverEndpoint(server.URL + "/redirect"); err != nil {
		t.Errorf("DiscoverEndpoint(%q) returned error: %v", server.URL+"/redirect", err)
	} else if got != want {
		t.Errorf("DiscoverEndpoint(%q) returned %v, want %v", server.URL+"/redirect", got, want)
	}

	// ensure 404 response is returned as error
	if _, err := client.DiscoverEndpoint(server.URL + "/bad"); err == nil {
		t.Errorf("DiscoverEndpoint(%q) did not return expected error", server.URL+"/bad")
	}
}

func TestExtractEndpoint(t *testing.T) {
	tests := []struct {
		resp string // raw response header and body
		want string // wanted endpoint URL
	}{
		{
			`Link: </endpoint>; rel="webmention"

`,
			"/endpoint",
		},
		{
			`
<link href="/endpoint" rel="webmention">`,
			"/endpoint",
		},
		{
			`Link: </endpoint1>; rel="webmention"

<link href="/endpoint2" rel="webmention">`,
			"/endpoint1",
		},
	}

	for _, tt := range tests {
		raw := "HTTP/1.1 200 OK\n" + tt.resp
		resp, err := http.ReadResponse(bufio.NewReader(bytes.NewBufferString(raw)), nil)
		if err != nil {
			t.Errorf("error reading response %q: %v", raw, err)
		}

		if got, err := extractEndpoint(resp); err != nil {
			t.Errorf("extractEndpoint(%q) returned error: %v", raw, err)
		} else if got != tt.want {
			t.Errorf("extractEndpoint(%q) returned %v, want %v", raw, got, tt.want)
		}
	}
}

func TestDiscoverLinks(t *testing.T) {
	mux, server, cleanup := testServer()
	defer cleanup()
	client := New(nil)

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `
<link href="/a">

`)
	})

	// no selector
	got, err := client.DiscoverLinks(server.URL, "")
	if err != nil {
		t.Errorf("DiscoverLinks returned error: %v", err)
	}
	want := []string{server.URL + "/a", "http://example.com/"}
	if !cmp.Equal(got, want) {
		t.Errorf("DiscoverLinks returned %v, want %v", got, want)
	}

	// with selector
	got, err = client.DiscoverLinks(server.URL, "body")
	if err != nil {
		t.Errorf("DiscoverLinks returned error: %v", err)
	}
	want = []string{"http://example.com/"}
	if !cmp.Equal(got, want) {
		t.Errorf("DiscoverLinks returned %v, want %v", got, want)
	}
}


text:
require 'faker'
require 'json'
require 'pmap'

def gen(number, force_array = false, &block)
  max = if number.is_a?(Range)
        number.last < Float::INFINITY ? number.last : 3
      else
        number
      end
  min = number.is_a?(Range) ? number.first : number

  res = (rand((max - min) + 1) + min).times.map(&block).compact
  return if res.empty?
  #$stderr.puts "#{number}, #{res.inspect}" if max == 1
  max > 1 || force_array ? res : res.first
end

def gen_identifier(number = 1..1)
  tpls = [
    { use: 'official', label: 'BSN', system: 'urn:oid:2.16.840.1.113883.2.4.6.3', value: '123123' },
    { use: "official", label:"SSN", system:"urn:oid:2.16.840.1.113883.2.4.6.7", value:"123456789" }]

  gen(number) do
    tpls.sample.merge value: (1000000 + rand(1000000)).to_s, use: %w(usual  official  temp  secondary).sample
  end
end

def gen_boolean(number = 1..1)
  gen(number) { [true, false].sample }
end
alias :gen_active :gen_boolean

def gen_integer(number = 1..1)
  gen(number) { rand(100) }
end

def gen_uri(number = 1..1)
  gen(number) { Faker::Internet.url }
end

def gen_string(number = 1..1)
  gen(number) { Faker::Lorem.word }
end

def gen_text(number = 1..1)
  gen(number) { Faker::Lorem.paragraphs }
end

def gen_datetime(number = 1..1)
  datetime_min = Time.new(2000)
  datetime_max = Time.new(2010)

  gen(number) do
    Time.at((datetime_max.to_f - datetime_min.to_f) * rand + datetime_min.to_f)
  end
end
alias :gen_date :gen_datetime
alias :gen_dateTime :gen_datetime
alias :gen_instant :gen_datetime

def gen_period(number = 1..1)
  gen(number) do
    res = {}
    res[:start] = gen(0..1) { gen_datetime } # Starting time with inclusive boundary
    res[:end]   = gen(0..1) { gen_datetime } # End time with inclusive boundary, if not ongoing

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end

def gen_codeable_concept(number = 1..1)
  gen(number) do
    res = {}
    res[:coding] = gen_coding(0..Float::INFINITY) # Coding Code defined by a terminology system
    res[:text] = gen(0..1) { Faker::Lorem.sentence } # Plain text representation of the concept

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end
alias :gen_communication :gen_codeable_concept
alias :gen_maritalStatus :gen_codeable_concept

def gen_coding(number = 1..1)
  gen(number) do
    res = {}
    res[:system] = gen_uri(0..1) # Identity of the terminology system
    res[:version] = gen_string(0..1) # Version of the system - if relevant
    res[:code] = gen_code(0..1) # Symbol in syntax defined by the system
    res[:display] = gen_string(0..1) # Representation defined by the system
    res[:primary] = gen_boolean(0..1) # If this code was chosen directly by the user
    res[:valueSet] = gen_valueSet(0..1) # Set this coding was chosen from

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end

def gen_valueset(number = 1..1)
  gen(number, true) do
    res = {}
    res[:identifier] = gen_string(0..1) # Logical id to reference this value set
    res[:version] = gen_string(0..1) # Logical id for this version of the value set
    res[:name] = gen_string(1..1) # Informal name for this value set
    res[:publisher] = gen_string(0..1) # Name of the publisher (Organization or individual)
    res[:telecom] = gen_contact(0..Float::INFINITY) # Contact information of the publisher</telecom>
    res[:description] = gen_text(1..1) # Human language description of the value set
    res[:copyright] = gen_string(0..1) # About the value set or its content
    res[:status] = gen_code(1..1, restrictions: %w(draft active retired))
    res[:experimental] = gen_boolean(0..1) # If for testing purposes, not real usage
    res[:extensible] = gen_boolean(0..1) # Whether this is intended to be used with an extensible binding
    res[:date] = gen_date(0..1) # Date for given status
    res[:define] = gen(0..1) do # When value set defines its own codes
      res[:system] = gen_uri(1..1) # URI to identify the code system
      res[:version] = gen_string(0..1) # Version of this system
      res[:caseSensitive] = gen_boolean(0..1) # If code comparison is case sensitive
      res[:concept] = gen(0..Float::INFINITY) do # Concepts in the code system
        res[:code] = gen_code(1..1) # Code that identifies concept
        res[:abstract] = gen_boolean(0..1) # If this code is not for use as a real concept
        res[:display] = gen_string(0..1) # Text to Display to the user
        res[:definition] = gen_text(0..1) # Formal Definition
        # <concept><!-- 0..* Content as for ValueSet.define.concept Child Concepts (is-a / contains) </concept>
      end
    end
    res[:compose] = gen(0..1) do # When value set includes codes from elsewhere
      res[:import] = gen_uri{0..Float::INFINITY} # Import the contents of another value set
      res[:include] = gen(0..Float::INFINITY) do # Include one or more codes from a code system
        res[:system] = gen_uri(1..1) # The system the codes come from
        res[:version] = gen_string(0..1) # Specific version of the code system referred to
        res[:code] = gen_code(0..Float::INFINITY) # Code or concept from system
        res[:filter] = gen(0..Float::INFINITY) do # Select codes/concepts by their properties (including relationships)
          res[:property] = gen_code(1..1) # A property defined by the code system
          res[:op] = gen_code(1..1, restrictions: %w(is-a is-not-a regex in not in))
          res[:value] = gen_code(1..1) # Code from the system, or regex criteria
        end
      end
      # <exclude><!-- ?? 0..Float::INFINITY Content as for ValueSet.compose.include Explicitly exclude codes </exclude>
    end
    res[:expansion] = gen(0..1) do # When value set is an expansion
      res[:identifier] = gen_identifier(0..1) # Identifier Uniquely identifies this expansion </identifier>
      res[:timestamp] = gen_instant(1..1) # Time valueset expansion happened
      res[:contains] = gen(0..Float::INFINITY) do # Codes in the value set
        res[:system] = gen_uri(0..1) # System value for the code
        res[:code] = gen_code(0..1) # Code - if blank, this is not a choosable code
        res[:display] = gen_string(0..1) # User display for the concept
        # <contains><!-- 0..Float::INFINITY Content as for ValueSet.expansion.contains Codes contained in this concept </contains>
      end
    end

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end
alias :gen_valueSet :gen_valueset

def gen_category(number = 1..1)
  gen(3) do
    { scheme: Faker::Internet.url('http://hl7.org/fhir/tag/'), term: Faker::Internet.url, label: Faker::Lorem.sentence }
  end
end

def gen_HumanName(number = 1..1)
  gen(number) do
    {
      use: %w(usual  official  temp  nickname  anonymous  old  maiden).sample,
      text: Faker::Name.name,
      family: gen(2) { Faker::Name.last_name },
      given: gen(2) { Faker::Name.first_name },
      prefix: gen(1, true) { Faker::Name.prefix }
    }
  end
end
alias :gen_name :gen_HumanName

def gen_telecom(number = 1..1)
  gen(number) do
    [
      {
        system: %w(phone fax).sample,
        value: Faker::PhoneNumber.cell_phone,
        use: %w(home  work  temp  old  mobile).sample
      },
      {
        system: 'email',
        value: Faker::Internet.email,
        use: %w(home  work  temp  old  mobile).sample
      }
    ].sample
  end
end

def gen_gender(number)
  gen(number) do
    {
      coding: [{ system: 'http://hl7.org/fhir/v3/AdministrativeGender', code: %w(M F).sample, display: %w(Male Female).sample }] # bug
    }
  end
end

def gen_birthDate(number = 1..1)
  gen(number) { Time.at(rand * Time.now.to_i) }
end

def gen_deceasedBoolean(number = 1..1)
  rand % 100 == 0
end

def gen_address(number = 2)
  gen(number) do
    res = { use: %w(home work temp old).sample,
      line: [Faker::Address.street_address],
      city: Faker::Address.city,
      zip: Faker::Address.zip,
      state: Faker::Address.state
    }
    res[:text] = [res[:line].join("\n"), res[:state], res[:zip]].join(", ")
    res
  end
end

def gen_contact(number = 1..1)
  gen(number) do
    res = {}

    res[:system] = gen_code(0..1, restrictions: %w(phone fax email url))
    res[:value] = gen(0..1) { Faker::Lorem.sentence } # The actual contact details
    res[:use] = gen_code(0..1, restrictions: %w(home work temp old mobile)) # purpose of this address
    res[:period] = gen_period(0..1) # Period Time period when the contact was/is in use

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end

def gen_code(number = 1, opts = {})
  restrictions = opts[:restrictions]
  if !restrictions.is_a?(Array)
    restrictions = [restrictions]
  end
  if restrictions.empty?
    restrictions = Faker::Lorem.words
  end

  gen(number) do
    restrictions.sample
  end
end

def gen_attachment(number = 1..1)
  gen(number) do
    res = {}
    res[:contentType] = gen_code(1..1) # Mime type of the content, with charset etc.
    res[:language] = gen_code(0..1) # Human language of the content (BCP-47)
    # <data value="[base64Binary]"/><!-- 0..1 Data inline, base64ed -->
    res[:url] = gen_uri(0..1) # Uri where the data can be found
    res[:size] = gen_integer(0..1) # Number of bytes of content (if url provided)
    # <hash value="[base64Binary]"/><!-- 0..1 Hash of the data (sha-1, base64ed ) -->
    res[:title] = gen_string(0..1) # Label to display in place of the data

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end
alias :gen_photo :gen_attachment

def gen_location(number = 1..1)
  gen(number) do
    res = {}
    res[:identifier] = gen_identifier(0..1) # Unique code or number identifying the location to its users
    res[:name] = gen(0..1) { Faker::Lorem.word } # Name of the location as used by humans
    res[:description] = gen(0..1) { Faker::Lorem.paragraphs } # Description of the Location, which helps in finding or referencing the place
    res[:type] = gen_codeable_concept(0..1) # Indicates the type of function performed at the location
    res[:telecom] = gen_contact(0..Float::INFINITY) # Contact details of the location
    res[:address] = gen_address(0..1) # Physical location
    res[:physicalType] = gen_codeable_concept(0..1) # Physical form of the location
    res[:position] = gen_position(0..1) # The absolute geographic location
    # SystemStackError: stack level too deep
    # res[:managingOrganization] = gen_organization(0..1) # The organization that is responsible for the provisioning and upkeep of the location
    res[:status] = gen_code(0..1, restrictions: %w(active suspended inactive))
    # SystemStackError: stack level too deep
    # res[:partOf] = gen_location(0..1) # Another Location which this Location is physically part of
    res[:mode] = gen_code(0..1, restrictions: %w(instance kind))

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end

def gen_position(number = 1..1)
  gen(number) do
    res = {}
    res[:longitude] = gen(1..1) { Faker::Address.longitude } # Longitude as expressed in KML
    res[:latitude] = gen(1..1) { Faker::Address.latitude } # Latitude as expressed in KML
    res[:altitude] = gen(0..1) { rand * 100 } # Altitude as expressed in KML

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end

def gen_organization(number = 1..1)
  gen(number) do
    res = {}
    res[:identifier] = gen_identifier(0..Float::INFINITY) # Identifier Identifies this organization  across multiple systems
    res[:name] = gen(0..1) { Faker::Company.name } # Name used for the organization
    res[:type] = gen_codeable_concept(0..1) # Kind of organization
    res[:telecom] = gen_contact(0..Float::INFINITY) # Contact A contact detail for the organization
    res[:address] = gen_address(0..Float::INFINITY) # Address An address for the organization </address>
    res[:partOf] = gen_organization(0..1) # The organization of which this organization forms a part
    res[:contact] = gen(0..Float::INFINITY) do # Contact for the organization for a certain purpose
      contact = {}
      contact[:purpose] = gen_codeable_concept(0..1) # The type of contact
      contact[:name] = gen_HumanName(0..1) # A name associated with the contact
      contact[:telecom] = gen_contact(0..Float::INFINITY) # Contact details (telephone, email, etc)  for a contact
      contact[:address] = gen_address(0..1) # Visiting or postal addresses for the contact
      contact[:gender] = gen_codeable_concept(0..1) # Gender for administrative purposes
      contact.delete_if { |_, v| !v }
      contact unless contact.empty?
    end
     res[:location] = gen_location(0..Float::INFINITY) # Location(s) the organization uses to provide services
     res[:active] = gen_active(0..1) # Whether the organization's record is still in active use

    res.delete_if { |_, v| !v }
    res unless res.empty?
  end
end
alias :gen_managingOrganization :gen_organization
alias :gen_careProvider :gen_organization

class Pager
  def initialize(number, ppm = true)
    @counter = 0
    @point = ppm ? number / 1000 : number / 100
    @line = @point * 20
  end

  def show
    @counter += 1
    if (@counter % @line).zero?
      $stderr.puts "  #{@counter}"
    elsif (@counter % @point).zero?
      $stderr.print '.'
    end
  end
end

def gen_patient(number)
  #pager = Pager.new(number)
  number.times.pmap do
    #pager.show
    res = { resourceType: 'Patient' }

    {
      identifier:           0..Float::INFINITY,
      category:             0..1, #wtf?
      name:                 0..Float::INFINITY,
      telecom:              0..Float::INFINITY,
      gender:               0..1,
      birthDate:            0..1,
      deceasedBoolean:      0..1,
      address:              0..Float::INFINITY,
      maritalStatus:        0..1,
      #photo:                0..Float::INFINITY,
      contact:              0..Float::INFINITY,
      communication:        0..Float::INFINITY,
      careProvider:         0..Float::INFINITY,
      managingOrganization: 0..1,
      active:               0..1
    }.each do |name, number|
      res[name] = send("gen_#{name}", number)
    end

    res.delete_if { |_, v| !v }
    unless res.empty?
      "SELECT fhir.insert_resource($DATA$#{JSON.pretty_generate(res)}$DATA$::json);"
    end
  end
end

gen_patient(ARGV[0].to_i).peach do |pt|
  puts pt
end
#puts JSON.pretty_generate(gen_patient(1000))


text:
/**
 * @file : spline_1d.h
 * @brief: piecewise smoothing spline class
 *       1. Model description: piecewise smoothing spline are made by pieces of
 *smoothing splines
 *          joint at knots;
 *       2. To guarantee smoothness, pieces value at knots should joint together
 *with
 *           same value, derivative, and etc. Higher the order, More smoothness
 *the piecewise spline;
 **/

#ifndef MODULES_PLANNING_MATH_SMOOTHING_SPLINE_SPLINE_1D_H_
#define MODULES_PLANNING_MATH_SMOOTHING_SPLINE_SPLINE_1D_H_

#include <vector>

#include "Eigen/Core"

#include "modules/planning/math/polynomial_xd.h"
#include "modules/planning/math/smoothing_spline/affine_constraint.h"
#include "modules/planning/math/smoothing_spline/spline_1d_seg.h"

namespace apollo {
namespace planning {

class Spline1d {
 public:
  Spline1d(const std::vector<double>& x_knots, const uint32_t order);

  // @brief: given x return f(x) value, derivative, second order derivative and
  // the third order;
  double operator()(const double x) const;
  double Derivative(const double x) const;
  double SecondOrderDerivative(const double x) const;
  double ThirdOrderDerivative(const double x) const;

  // @brief: set spline segments
  bool SetSplineSegs(const Eigen::MatrixXd& param_matrix, const uint32_t order);

  const std::vector<double>& x_knots() const;
  uint32_t spline_order() const;

 private:
  uint32_t FindIndex(const double x) const;

 private:
  std::vector<Spline1dSeg> splines_;
  std::vector<double> x_knots_;
  uint32_t spline_order_;
};

}  // namespace planning
}  // namespace apollo

#endif  // MODULES_PLANNING_MATH_SMOOTHING_SPLINE_SPLINE_1D_H_


text:
package com.lemon.base.dao;

import java.io.Serializable;
import java.util.Map;

public interface IBaseSqlDao extends Serializable {
	//public Map<String, Object> queryMap(String sql);

}


text:
package org.elasticsoftware.elasticactors.serialization.reactivestreams;

import org.elasticsoftware.elasticactors.messaging.reactivestreams.SubscribeMessage;
import org.elasticsoftware.elasticactors.serialization.MessageSerializer;
import org.elasticsoftware.elasticactors.serialization.protobuf.Reactivestreams;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author Joost van de Wijgerd
 */
public final class SubscribeMessageSerializer implements MessageSerializer<SubscribeMessage> {
    @Override
    public ByteBuffer serialize(SubscribeMessage message) throws IOException {
        Reactivestreams.SubscribeMessage.Builder builder = Reactivestreams.SubscribeMessage.newBuilder();
        builder.setMessageName(message.getMessageName());
        builder.setSubscriberRef(message.getSubscriberRef().toString());
        return ByteBuffer.wrap(builder.build().toByteArray());
    }
}


text:
@implementation BEMRemotePushNotificationHandler

+ (BEMRemotePushNotificationHandler*) instance {
    static dispatch_once_t once;
    static id sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
        // when we create a new instance, we use it to register for notifications
        // this should mean that we register only once for notifications, which should mean
        // that we should stop getting duplicate notifications
        [sharedInstance registerForNotifications];
    });
    return sharedInstance;
}

- (void)registerForNotifications {
    [[NSNotificationCenter defaultCenter] addObserverForName:CFCTransitionNotificationName object:nil queue:nil
                                                  usingBlock:^(NSNotification *note) {
                                                      [self handleNotifications:note];
                                                  }];
}

- (id) init {
    self = [super init];
    self.silentPushHandlerList = [[NSMutableArray alloc] init];
    return self;
}

- (void)notifyAllHandlers:(UIBackgroundFetchResult) result {
    for (SilentPushCompletionHandler handler in self.silentPushHandlerList) {
        handler(result);
    }
    [self.silentPushHandlerList removeAllObjects];
}

- (void)handleNotifications:(NSNotification*)note {
    @synchronized([BEMRemotePushNotificationHandler instance]) {
        if ([note.object isEqualToString:CFCTransitionRecievedSilentPush]) {
            // We are the silent push handler, so we store the handler block, and run the
            // periodic tasks, but don't do anything else
            [BEMRemotePushNotificationHandler performPeriodicActivity];
            NSDictionary* userInfo = note.userInfo;
            SilentPushCompletionHandler newHandler = [userInfo objectForKey:@"handler"];
            if (newHandler != NULL) {
                [self.silentPushHandlerList addObject:newHandler];
                [LocalNotificationManager addNotification:[NSString stringWithFormat:@"Added SILENT_PUSH handler block %@ to list, new size = %lu", newHandler, (unsigned long)[self.silentPushHandlerList count]]];
            }
        }
    }
    if ([self.silentPushHandlerList count] > 0) {
        [LocalNotificationManager addNotification:[NSString stringWithFormat:
                                                   @"Received notification %@ while processing silent push notification", note.object] showUI:FALSE];
        // we only care about notifications when we are processing a silent remote push notification
        if ([note.object isEqualToString:CFCTransitionRecievedSilentPush]) {
            // We are the silent push handler, so we store the handler block, but don't do anything else.
            [LocalNotificationManager addNotification:[NSString stringWithFormat:@"Handler block has already been set, ignoring SILENT_PUSH in the silent push handler"]];
            // Note: Do NOT call the handler here since the state machine may not have quiesced.
            // We want to wait until we know that the state machine has finished handling it.
            // _silentPushHandler(UIBackgroundFetchResultNewData);
        } else if ([note.object isEqualToString:CFCTransitionNOP]) {
            // Next, we think of what the possible responses to the silent push are
            // One option is that the state machine wants to ignore it, possibly because it is not in ONGOING STATE
            // Let us assume that we will return NOP in that case
            [LocalNotificationManager addNotification:[NSString stringWithFormat:@"Remote push state machine ignored the silent push, fetch result = new data"] showUI:FALSE];
            [self notifyAllHandlers:UIBackgroundFetchResultNewData];
        } else if ([note.object isEqualToString:CFCTransitionTripEndDetected]) {
            // Otherwise, if it is in OngoingTrip, it will try to see whether the trip has ended. If it hasn't,
            // let us assume that we will return a NOP, which is already handled.
            // If it has, then it will return a TripEndDetected and start creating the geofence.
            // Once the geofence is created, we will get a TripEnded, and we want to
            // wait until that point, so we DON'T return here.
            [LocalNotificationManager addNotification:[NSString stringWithFormat:
                                                       @"Detected trip end, waiting until geofence is created to return from silent push"]];
        } else if ([note.object isEqualToString:CFCTransitionTripEnded]) {
            // Trip has now ended, so we can push and clear data
                    [LocalNotificationManager addNotification:[NSString stringWithFormat:
                                                       @"Trip ended, waiting until data is pushed to return from the silent push"]];
        } else if ([note.object isEqualToString:CFCTransitionDataPushed]) {
            [LocalNotificationManager addNotification:[NSString stringWithFormat:
                                                       @"Data pushed, fetch result = new data"] showUI:FALSE];
            [self notifyAllHandlers:UIBackgroundFetchResultNewData];
        } else if ([note.object isEqualToString:CFCTransitionTripRestarted]) {
            // The other option from TripEndDetected is that the trip is restarted instead of ended.
            // In that case, we still want to finish the handler
            [self notifyAllHandlers:UIBackgroundFetchResultNewData];
        } else {
            // Some random transition. Might as well call the handler and return
            [self notifyAllHandlers:UIBackgroundFetchResultNewData];
        }
    } else {
        // Not processing a silent remote push notification
        NSLog(@"Ignoring silent push notification");
    }
}

+ (void) performPeriodicActivity
{
    [TripDiarySettingsCheck checkSettingsAndPermission];
    [BEMRemotePushNotificationHandler validateAndCleanupState];
}

+ (void) validateAndCleanupState
{
    NSUInteger currState = [TripDiaryStateMachine instance].currState;
    if (currState == kStartState) {
        [LocalNotificationManager addNotification:[NSString stringWithFormat:
                                                   @"Still in start state, sending initialize..."] showUI:TRUE];
        [[NSNotificationCenter defaultCenter] postNotificationName:CFCTransitionNotificationName
                                                            object:CFCTransitionInitialize];
    } else {
        [LocalNotificationManager addNotification:[NSString stringWithFormat:
                                                   @"In valid state %@, nothing to do...", [TripDiaryStateMachine getStateName:currState]] showUI:FALSE];
    }
}

@end


text:
=========================
Creare una chiave esterna
=========================

--------
Premessa
--------

Nel database di Accreditamenti abbiamo due grandi entità. Una è Congresso e
l'altra si chiama Accreditamento. Queste due entità sono legate tra loro. In
particolare un congresso può avere molti accreditamenti, ed un accreditamento
appartiene ad un solo congresso.

---------------------------------------
Cosa fare per relazionare le due entità
---------------------------------------

Per relazionare le due entità dovremo seguire una serie di passaggi.

#. Modificare l'entità Accreditamento (in questo caso figlio)
#. Modificare l'entità Congresso (in questo caso padre)
#. Completare le entità
#. Creare la nuova migration

----------------------------------
Modificare l'entità Accreditamento
----------------------------------

Vanno caricate le annotation:

::

    use Doctrine\ORM\Mapping\ManyToOne;
    use Doctrine\ORM\Mapping\JoinColumn;

e collegate le entità

::

    /**
     * @ManyToOne(targetEntity="Congresso", inversedBy="accreditamenti")
     * @JoinColumn(name="congresso_id", referencedColumnName="id")
     */
    private $congresso;

-----------------------------
Modificare l'entità Congresso
-----------------------------

Va caricata la nuova annotation

::

    use Doctrine\ORM\Mapping\OneToMany;

e collegate le due entità

::

    /**
     * @OneToMany(targetEntity="Accreditamento", mappedBy="congresso")
     */
    private $accreditamenti;

--------------------
Completare le entità
--------------------

Abbiamo aggiunto dei campi, ma mancano ancora i getter, i setter, ... ma
sopratutto __toString. Quando visualizzeremo un form per gli Accreditamenti
il campo congresso_id generato, mostrerà automaticamente una select con tutti i
congressi inseriti. Ma per funzionare correttamente, Congresso necessita di un
metodo __toString.

-----------------------------------------
Creare gli accessori (getter ed i setter)
-----------------------------------------

    $ php app/console doctrine:generate:entities AccreditamentiCongressiBundle:NOME_ENTITA

    $ php app/console doctrine:generate:entities AccreditamentiCongressiBundle:Congresso
    $ php app/console doctrine:generate:entities AccreditamentiCongressiBundle:Accreditamento
    $ php app/console doctrine:generate:entities AccreditamentiCongressiBundle:QuestionarioEcm

----------
__toString
----------

L'entità "padre" deve contenere un __toString perchè verrà visualizzato nelle
<option /> della  <select />.

::

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

-------------------------
Creare la nuova migration
-------------------------

Dopo aver modificato le due entità, possiamo lanciare la migration.

::

    $ php app/console doctrine:migrations:diff
    $ php app/console doctrine:migrations:migrate

A questo punto il database sarà allineato alle entitrà.


text:
require "rubysl/ipaddr/ipaddr"
require "rubysl/ipaddr/version"


text:
<?php

class Papi_Lib_Core_Taxonomy_Test extends WP_UnitTestCase {

	public function setUp() {
		parent::setUp();

		if ( ! papi_supports_term_meta() ) {
			$this->markTestSkipped( 'Term metadata is not supported' );
		}
	}

	public function test_papi_get_term_id() {
		$this->assertSame( 1, papi_get_term_id( 1 ) );
		$this->assertSame( 1, papi_get_term_id( '1' ) );

		$term_id = $this->factory->term->create();

		$term = get_term( $term_id );
		$this->assertSame( $term_id, papi_get_term_id( $term ) );

		$_GET['term_id'] = $term_id;
		$this->assertSame( $term_id, papi_get_term_id() );
		$this->assertSame( $term_id, papi_get_term_id( null ) );
		unset( $_GET['term_id'] );

		$_GET['tag_ID'] = $term_id;
		$this->assertSame( $term_id, papi_get_term_id() );
		$this->assertSame( $term_id, papi_get_term_id( null ) );
		unset( $_GET['tag_ID'] );
	}

	public function test_papi_get_term_id_wp_query() {
		$term_id = $this->factory->term->create( ['slug' => 'category_test'] );
		$term = get_term_by( 'slug', 'category_test', 'post_tag' );
		$this->go_to( get_term_link( $term ) );
		$this->assertSame( $term_id, papi_get_term_id() );
	}

	public function test_papi_get_taxonomy() {
		$this->assertSame( '', papi_get_taxonomy() );

		$_GET['taxonomy'] = 'post_tag';
		$this->assertSame( 'post_tag', papi_get_taxonomy() );
		$this->assertSame( 'post_tag', papi_get_taxonomy( null ) );
		unset( $_GET['taxonomy'] );

		$_GET['term_id'] = $this->factory->term->create();
		$this->assertSame( get_term( $_GET['term_id'] )->taxonomy, papi_get_taxonomy() );
		unset( $_GET['term_id'] );
	}

	public function test_papi_get_taxonomy_label() {
		$this->assertSame( 'Categories', papi_get_taxonomy_label( 'category', 'name' ) );
		$this->assertSame( 'Fake', papi_get_taxonomy_label( 'Fake', 'name', 'Fake' ) );
	}

	public function test_papi_supports_term_meta() {
		if ( function_exists( 'get_term_meta' ) ) {
			$this->assertTrue( papi_supports_term_meta() );
		} else {
			$this->assertFalse( papi_supports_term_meta() );
		}
	}
}