/*
 * Copyright (c) Dominick Baier, Brock Allen.  All rights reserved.
 * see license.txt
 */

using System;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IdentityModel.Metadata;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Xml;
using Thinktecture.IdentityModel.Constants;
using Thinktecture.IdentityServer.Repositories;

namespace Thinktecture.IdentityServer.Protocols.FederationMetadata
{
    /// <summary>
    /// Handler for dynamic generation of the WS-Federation metadata document
    /// </summary>
    public class WSFederationMetadataGenerator
    {
        Endpoints _endpoints;

        [Import]
        public IConfigurationRepository ConfigurationRepository { get; set; }

        [Import]
        public IUserRepository UserRepository { get; set; }

        [Import]
        public IClaimsRepository ClaimsRepository { get; set; }

        public WSFederationMetadataGenerator(Endpoints endpoints)
        {
            _endpoints = endpoints;
            Container.Current.SatisfyImportsOnce(this);
        }

        //Builds federation metadata for using Id Srv as an IdP using the wsfed endpoint
        public string Generate()
        {
            var tokenServiceDescriptor = GetTokenServiceDescriptor(_endpoints.WSFederation.AbsoluteUri);
            return GenerateMetadata(tokenServiceDescriptor);
        }

        //Builds federation metadata for using Id Srv as an RP using the HRD endpoint
        public string GenerateRelyingPartyMetadata()
        {
            var tokenServiceDescriptor = GetTokenServiceDescriptor(_endpoints.WSFederationHRD.AbsoluteUri);
            var appServiceDescriptor = GetApplicationServiceDescriptor();

            return GenerateMetadata(tokenServiceDescriptor, appServiceDescriptor);
        }

        private string GenerateMetadata(params RoleDescriptor[] roles)
        {
            var id = new EntityId(ConfigurationRepository.Global.IssuerUri);
            var entity = new EntityDescriptor(id);
            entity.SigningCredentials = new X509SigningCredentials(ConfigurationRepository.Keys.SigningCertificate);

            foreach (var roleDescriptor in roles)
            {
                entity.RoleDescriptors.Add(roleDescriptor);
            }

            var ser = new MetadataSerializer();
            var sb = new StringBuilder(512);

            ser.WriteMetadata(XmlWriter.Create(new StringWriter(sb), new XmlWriterSettings { OmitXmlDeclaration = true }), entity);
            return sb.ToString();
        }

        private SecurityTokenServiceDescriptor GetTokenServiceDescriptor(string passiveRequestorEndpoint)
        {
            var tokenService = new SecurityTokenServiceDescriptor();
            tokenService.ServiceDescription = ConfigurationRepository.Global.SiteName;
            tokenService.Keys.Add(GetSigningKeyDescriptor());

            tokenService.PassiveRequestorEndpoints.Add(new EndpointReference(passiveRequestorEndpoint));

            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml11TokenProfile11));
            tokenService.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml2TokenProfile11));

            ClaimsRepository.GetSupportedClaimTypes().ToList().ForEach(claimType => tokenService.ClaimTypesOffered.Add(new DisplayClaim(claimType)));
            tokenService.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            if (ConfigurationRepository.WSTrust.Enabled && ConfigurationRepository.WSTrust.EnableMessageSecurity)
            {
                var addressMessageUserName = new EndpointAddress(_endpoints.WSTrustMessageUserName, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(addressMessageUserName.Uri.AbsoluteUri));

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    var addressMessageCertificate = new EndpointAddress(_endpoints.WSTrustMessageCertificate, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(addressMessageCertificate.Uri.AbsoluteUri));
                }
            }
            if (ConfigurationRepository.WSTrust.Enabled && ConfigurationRepository.WSTrust.EnableMixedModeSecurity)
            {
                var addressMixedUserName = new EndpointAddress(_endpoints.WSTrustMixedUserName, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(addressMixedUserName.Uri.AbsoluteUri));

                if (ConfigurationRepository.WSTrust.EnableClientCertificateAuthentication)
                {
                    var addressMixedCertificate = new EndpointAddress(_endpoints.WSTrustMixedCertificate, null, null, CreateMetadataReader(_endpoints.WSTrustMex), null);
                    tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(addressMixedCertificate.Uri.AbsoluteUri));
                }
            }

            if (tokenService.SecurityTokenServiceEndpoints.Count == 0)
                tokenService.SecurityTokenServiceEndpoints.Add(new EndpointReference(_endpoints.WSFederation.AbsoluteUri));

            return tokenService;
        }

        private ApplicationServiceDescriptor GetApplicationServiceDescriptor()
        {
            var appDescriptor = new ApplicationServiceDescriptor();

            appDescriptor.ServiceDescription = ConfigurationRepository.Global.SiteName;
            appDescriptor.Keys.Add(GetSigningKeyDescriptor());

            appDescriptor.PassiveRequestorEndpoints.Add(new EndpointReference(_endpoints.WSFederationHRD.AbsoluteUri));
            appDescriptor.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml11TokenProfile11));
            appDescriptor.TokenTypesOffered.Add(new Uri(TokenTypes.OasisWssSaml2TokenProfile11));

            ClaimsRepository.GetSupportedClaimTypes().ToList().ForEach(claimType => appDescriptor.ClaimTypesOffered.Add(new DisplayClaim(claimType)));
            appDescriptor.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            return appDescriptor;
        }

        private KeyDescriptor GetSigningKeyDescriptor()
        {
            var certificate = ConfigurationRepository.Keys.SigningCertificate;

            var clause = new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>();
            var key = new KeyDescriptor(new SecurityKeyIdentifier(clause));
            key.Use = KeyType.Signing;

            return key;
        }

        private XmlDictionaryReader CreateMetadataReader(Uri mexAddress)
        {
            var metadataSet = new MetadataSet();
            var metadataReference = new MetadataReference(new EndpointAddress(mexAddress), AddressingVersion.WSAddressing10);
            var metadataSection = new MetadataSection(MetadataSection.MetadataExchangeDialect, null, metadataReference);
            metadataSet.MetadataSections.Add(metadataSection);

            var sb = new StringBuilder();
            var w = new StringWriter(sb, CultureInfo.InvariantCulture);
            var writer = XmlWriter.Create(w);

            metadataSet.WriteTo(writer);
            writer.Flush();
            w.Flush();

            var input = new StringReader(sb.ToString());
            var reader = new XmlTextReader(input);
            return XmlDictionaryReader.CreateDictionaryReader(reader);
        }
    }
}

{'repo_name': 'IdentityServer/IdentityServer2', 'stars': '412', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -6005964636832680622, 'source_dataset': 'data'}


{'repo_name': 'QuickBlox/quickblox-ios-sdk', 'stars': '353', 'repo_language': 'Swift', 'file_name': 'Contents.json', 'mime_type': 'text/plain', 'hash': -1568669579932447999, 'source_dataset': 'data'}


/* LzmaUtil.c -- Test application for LZMA compression
2015-11-08 : Igor Pavlov : Public domain */

#include "../../Precomp.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../../Alloc.h"
#include "../../7zFile.h"
#include "../../7zVersion.h"
#include "../../LzmaDec.h"
#include "../../LzmaEnc.h"

const char *kCantReadMessage = "Can not read input file";
const char *kCantWriteMessage = "Can not write output file";
const char *kCantAllocateMessage = "Can not allocate memory";
const char *kDataErrorMessage = "Data error";

void PrintHelp(char *buffer)
{
  strcat(buffer, "\nLZMA Utility " MY_VERSION_COPYRIGHT_DATE "\n"
      "\nUsage:  lzma <e|d> inputFile outputFile\n"
             "  e: encode file\n"
             "  d: decode file\n");
}

int PrintError(char *buffer, const char *message)
{
  strcat(buffer, "\nError: ");
  strcat(buffer, message);
  strcat(buffer, "\n");
  return 1;
}

int PrintErrorNumber(char *buffer, SRes val)
{
  sprintf(buffer + strlen(buffer), "\nError code: %x\n", (unsigned)val);
  return 1;
}

int PrintUserError(char *buffer)
{
  return PrintError(buffer, "Incorrect command");
}

#define IN_BUF_SIZE (1 << 16)
#define OUT_BUF_SIZE (1 << 16)

static SRes Decode2(CLzmaDec *state, ISeqOutStream *outStream, ISeqInStream *inStream,
    UInt64 unpackSize)
{
  int thereIsSize = (unpackSize != (UInt64)(Int64)-1);
  Byte inBuf[IN_BUF_SIZE];
  Byte outBuf[OUT_BUF_SIZE];
  size_t inPos = 0, inSize = 0, outPos = 0;
  LzmaDec_Init(state);
  for (;;)
  {
    if (inPos == inSize)
    {
      inSize = IN_BUF_SIZE;
      RINOK(inStream->Read(inStream, inBuf, &inSize));
      inPos = 0;
    }
    {
      SRes res;
      SizeT inProcessed = inSize - inPos;
      SizeT outProcessed = OUT_BUF_SIZE - outPos;
      ELzmaFinishMode finishMode = LZMA_FINISH_ANY;
      ELzmaStatus status;
      if (thereIsSize && outProcessed > unpackSize)
      {
        outProcessed = (SizeT)unpackSize;
        finishMode = LZMA_FINISH_END;
      }

      res = LzmaDec_DecodeToBuf(state, outBuf + outPos, &outProcessed,
        inBuf + inPos, &inProcessed, finishMode, &status);
      inPos += inProcessed;
      outPos += outProcessed;
      unpackSize -= outProcessed;

      if (outStream)
        if (outStream->Write(outStream, outBuf, outPos) != outPos)
          return SZ_ERROR_WRITE;

      outPos = 0;

      if (res != SZ_OK || (thereIsSize && unpackSize == 0))
        return res;

      if (inProcessed == 0 && outProcessed == 0)
      {
        if (thereIsSize || status != LZMA_STATUS_FINISHED_WITH_MARK)
          return SZ_ERROR_DATA;
        return res;
      }
    }
  }
}

static SRes Decode(ISeqOutStream *outStream, ISeqInStream *inStream)
{
  UInt64 unpackSize;
  int i;
  SRes res = 0;

  CLzmaDec state;

  /* header: 5 bytes of LZMA properties and 8 bytes of uncompressed size */
  unsigned char header[LZMA_PROPS_SIZE + 8];

  /* Read and parse header */

  RINOK(SeqInStream_Read(inStream, header, sizeof(header)));

  unpackSize = 0;
  for (i = 0; i < 8; i++)
    unpackSize += (UInt64)header[LZMA_PROPS_SIZE + i] << (i * 8);

  LzmaDec_Construct(&state);
  RINOK(LzmaDec_Allocate(&state, header, LZMA_PROPS_SIZE, &g_Alloc));
  res = Decode2(&state, outStream, inStream, unpackSize);
  LzmaDec_Free(&state, &g_Alloc);
  return res;
}

static SRes Encode(ISeqOutStream *outStream, ISeqInStream *inStream, UInt64 fileSize, char *rs)
{
  CLzmaEncHandle enc;
  SRes res;
  CLzmaEncProps props;

  UNUSED_VAR(rs);

  enc = LzmaEnc_Create(&g_Alloc);
  if (enc == 0)
    return SZ_ERROR_MEM;

  LzmaEncProps_Init(&props);
  res = LzmaEnc_SetProps(enc, &props);

  if (res == SZ_OK)
  {
    Byte header[LZMA_PROPS_SIZE + 8];
    size_t headerSize = LZMA_PROPS_SIZE;
    int i;

    res = LzmaEnc_WriteProperties(enc, header, &headerSize);
    for (i = 0; i < 8; i++)
      header[headerSize++] = (Byte)(fileSize >> (8 * i));
    if (outStream->Write(outStream, header, headerSize) != headerSize)
      res = SZ_ERROR_WRITE;
    else
    {
      if (res == SZ_OK)
        res = LzmaEnc_Encode(enc, outStream, inStream, NULL, &g_Alloc, &g_Alloc);
    }
  }
  LzmaEnc_Destroy(enc, &g_Alloc, &g_Alloc);
  return res;
}

int main2(int numArgs, const char *args[], char *rs)
{
  CFileSeqInStream inStream;
  CFileOutStream outStream;
  char c;
  int res;
  int encodeMode;
  Bool useOutFile = False;

  FileSeqInStream_CreateVTable(&inStream);
  File_Construct(&inStream.file);

  FileOutStream_CreateVTable(&outStream);
  File_Construct(&outStream.file);

  if (numArgs == 1)
  {
    PrintHelp(rs);
    return 0;
  }

  if (numArgs < 3 || numArgs > 4 || strlen(args[1]) != 1)
    return PrintUserError(rs);

  c = args[1][0];
  encodeMode = (c == 'e' || c == 'E');
  if (!encodeMode && c != 'd' && c != 'D')
    return PrintUserError(rs);

  {
    size_t t4 = sizeof(UInt32);
    size_t t8 = sizeof(UInt64);
    if (t4 != 4 || t8 != 8)
      return PrintError(rs, "Incorrect UInt32 or UInt64");
  }

  if (InFile_Open(&inStream.file, args[2]) != 0)
    return PrintError(rs, "Can not open input file");

  if (numArgs > 3)
  {
    useOutFile = True;
    if (OutFile_Open(&outStream.file, args[3]) != 0)
      return PrintError(rs, "Can not open output file");
  }
  else if (encodeMode)
    PrintUserError(rs);

  if (encodeMode)
  {
    UInt64 fileSize;
    File_GetLength(&inStream.file, &fileSize);
    res = Encode(&outStream.s, &inStream.s, fileSize, rs);
  }
  else
  {
    res = Decode(&outStream.s, useOutFile ? &inStream.s : NULL);
  }

  if (useOutFile)
    File_Close(&outStream.file);
  File_Close(&inStream.file);

  if (res != SZ_OK)
  {
    if (res == SZ_ERROR_MEM)
      return PrintError(rs, kCantAllocateMessage);
    else if (res == SZ_ERROR_DATA)
      return PrintError(rs, kDataErrorMessage);
    else if (res == SZ_ERROR_WRITE)
      return PrintError(rs, kCantWriteMessage);
    else if (res == SZ_ERROR_READ)
      return PrintError(rs, kCantReadMessage);
    return PrintErrorNumber(rs, res);
  }
  return 0;
}

int MY_CDECL main(int numArgs, const char *args[])
{
  char rs[800] = { 0 };
  int res = main2(numArgs, args, rs);
  fputs(rs, stdout);
  return res;
}

{'repo_name': 'SOUI2/soui.backup', 'stars': '277', 'repo_language': 'C++', 'file_name': 'FAQ.txt', 'mime_type': 'text/plain', 'hash': 1993430408013001516, 'source_dataset': 'data'}


/* LIBGIMP - The GIMP Library
 * Copyright (C) 1995-1997 Peter Mattis and Spencer Kimball
 *
 * This library is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <string.h>

#include <gtk/gtk.h>

#include "libgimpbase/gimpbase.h"
#include "libgimpmath/gimpmath.h"

#include "gimpwidgetstypes.h"

#include "gimpruler.h"

/**
 * SECTION: gimpruler
 * @title: GimpRuler
 * @short_description: A ruler widget with configurable unit and orientation.
 *
 * A ruler widget with configurable unit and orientation.
 **/

#define MINIMUM_INCR                5
#define IMMEDIATE_REDRAW_THRESHOLD  20

enum
{
  PROP_0,
  PROP_ORIENTATION,
  PROP_UNIT,
  PROP_LOWER,
  PROP_UPPER,
  PROP_POSITION,
  PROP_MAX_SIZE
};

/* All distances below are in 1/72nd's of an inch. (According to
 * Adobe that's a point, but points are really 1/72.27 in.)
 */
struct _GimpRulerPrivate
{
  GtkOrientation   orientation;
  GimpUnit         unit;
  gdouble          lower;
  gdouble          upper;
  gdouble          position;
  gdouble          max_size;

  GdkWindow       *input_window;
  cairo_surface_t *backing_store;
  gboolean         backing_store_valid;
  GdkRectangle     last_pos_rect;
  guint            pos_redraw_idle_id;
  PangoLayout     *layout;

  GList           *track_widgets;
};

#define GET_PRIVATE(obj) (((GimpRuler *) (obj))->priv)

typedef struct
{
  const gdouble  ruler_scale[16];
  const gint     subdivide[5];
} RulerMetric;

static const RulerMetric ruler_metric_decimal =
{
  { 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000 },
  { 1, 5, 10, 50, 100 }
};

static const RulerMetric ruler_metric_inches =
{
  /* 12 inch = 1 foot; 36 inch = 1 yard; 72 inchs = 1 fathom */
  { 1, 2, 6, 12, 36, 72, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000 },

  /* Inches are divided by multiples of 2. */
  { 1, 2, 4, 8, 16 }
};

static const RulerMetric ruler_metric_feet =
{
  /* 3 feet = 1 yard; 6 feet = 1 fathom */
  { 1, 3, 6, 12, 36, 72, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000 },

  /* 1 foot = 12 inches, so let's divide up to 12, */
  { 1, 3, 6, 12,
  /* then divide the inch by 2. */
    24 }
};

static const RulerMetric ruler_metric_yards =
{
  /* 1 fathom = 2 yards. Should we go back to base-10 digits? */
  { 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000 },

  /* 1 yard = 3 feet = 36 inches. */
  { 1, 3, 6, 12, 36 }
};

static void          gimp_ruler_dispose               (GObject        *object);
static void          gimp_ruler_set_property          (GObject        *object,
                                                       guint           prop_id,
                                                       const GValue   *value,
                                                       GParamSpec     *pspec);
static void          gimp_ruler_get_property          (GObject        *object,
                                                       guint           prop_id,
                                                       GValue         *value,
                                                       GParamSpec     *pspec);

static void          gimp_ruler_realize               (GtkWidget      *widget);
static void          gimp_ruler_unrealize             (GtkWidget      *widget);
static void          gimp_ruler_map                   (GtkWidget      *widget);
static void          gimp_ruler_unmap                 (GtkWidget      *widget);
static void          gimp_ruler_size_allocate         (GtkWidget      *widget,
                                                       GtkAllocation  *allocation);
static void          gimp_ruler_get_preferred_width   (GtkWidget      *widget,
                                                       gint           *minimum_width,
                                                       gint           *natural_width);
static void          gimp_ruler_get_preferred_height  (GtkWidget      *widget,
                                                       gint           *minimum_height,
                                                       gint           *natural_height);
static void          gimp_ruler_style_updated         (GtkWidget      *widget);
static gboolean      gimp_ruler_motion_notify         (GtkWidget      *widget,
                                                       GdkEventMotion *event);
static gboolean      gimp_ruler_draw                  (GtkWidget      *widget,
                                                       cairo_t        *cr);

static void          gimp_ruler_draw_ticks            (GimpRuler      *ruler);
static GdkRectangle  gimp_ruler_get_pos_rect          (GimpRuler      *ruler,
                                                       gdouble         position);
static gboolean      gimp_ruler_idle_queue_pos_redraw (gpointer        data);
static void          gimp_ruler_queue_pos_redraw      (GimpRuler      *ruler);
static void          gimp_ruler_draw_pos              (GimpRuler      *ruler,
                                                       cairo_t        *cr);
static void          gimp_ruler_make_pixmap           (GimpRuler      *ruler);
static PangoLayout * gimp_ruler_get_layout            (GtkWidget      *widget,
                                                       const gchar    *text);
static const RulerMetric *
                     gimp_ruler_get_metric            (GimpUnit        unit);

G_DEFINE_TYPE_WITH_PRIVATE (GimpRuler, gimp_ruler, GTK_TYPE_WIDGET)

#define parent_class gimp_ruler_parent_class

static void
gimp_ruler_class_init (GimpRulerClass *klass)
{
  GObjectClass   *object_class = G_OBJECT_CLASS (klass);
  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);

  object_class->dispose              = gimp_ruler_dispose;
  object_class->set_property         = gimp_ruler_set_property;
  object_class->get_property         = gimp_ruler_get_property;

  widget_class->realize              = gimp_ruler_realize;
  widget_class->unrealize            = gimp_ruler_unrealize;
  widget_class->map                  = gimp_ruler_map;
  widget_class->unmap                = gimp_ruler_unmap;
  widget_class->get_preferred_width  = gimp_ruler_get_preferred_width;
  widget_class->get_preferred_height = gimp_ruler_get_preferred_height;
  widget_class->size_allocate        = gimp_ruler_size_allocate;
  widget_class->style_updated        = gimp_ruler_style_updated;
  widget_class->motion_notify_event  = gimp_ruler_motion_notify;
  widget_class->draw                 = gimp_ruler_draw;

  g_object_class_install_property (object_class,
                                   PROP_ORIENTATION,
                                   g_param_spec_enum ("orientation",
                                                      "Orientation",
                                                      "The orientation of the ruler",
                                                      GTK_TYPE_ORIENTATION,
                                                      GTK_ORIENTATION_HORIZONTAL,
                                                      GIMP_PARAM_READWRITE));

  g_object_class_install_property (object_class,
                                   PROP_UNIT,
                                   gimp_param_spec_unit ("unit",
                                                         "Unit",
                                                         "Unit of ruler",
                                                         TRUE, TRUE,
                                                         GIMP_UNIT_PIXEL,
                                                         GIMP_PARAM_READWRITE));

  g_object_class_install_property (object_class,
                                   PROP_LOWER,
                                   g_param_spec_double ("lower",
                                                        "Lower",
                                                        "Lower limit of ruler",
                                                        -G_MAXDOUBLE,
                                                        G_MAXDOUBLE,
                                                        0.0,
                                                        GIMP_PARAM_READWRITE));

  g_object_class_install_property (object_class,
                                   PROP_UPPER,
                                   g_param_spec_double ("upper",
                                                        "Upper",
                                                        "Upper limit of ruler",
                                                        -G_MAXDOUBLE,
                                                        G_MAXDOUBLE,
                                                        0.0,
                                                        GIMP_PARAM_READWRITE));

  g_object_class_install_property (object_class,
                                   PROP_POSITION,
                                   g_param_spec_double ("position",
                                                        "Position",
                                                        "Position of mark on the ruler",
                                                        -G_MAXDOUBLE,
                                                        G_MAXDOUBLE,
                                                        0.0,
                                                        GIMP_PARAM_READWRITE));

  g_object_class_install_property (object_class,
                                   PROP_MAX_SIZE,
                                   g_param_spec_double ("max-size",
                                                        "Max Size",
                                                        "Maximum size of the ruler",
                                                        -G_MAXDOUBLE,
                                                        G_MAXDOUBLE,
                                                        0.0,
                                                        GIMP_PARAM_READWRITE));

  gtk_widget_class_set_css_name (widget_class, "GimpRuler");
}

static void
gimp_ruler_init (GimpRuler *ruler)
{
  GimpRulerPrivate *priv;

  ruler->priv = gimp_ruler_get_instance_private (ruler);

  priv = ruler->priv;

  gtk_widget_set_has_window (GTK_WIDGET (ruler), FALSE);

  priv->orientation = GTK_ORIENTATION_HORIZONTAL;
  priv->unit        = GIMP_UNIT_PIXEL;
}

static void
gimp_ruler_dispose (GObject *object)
{
  GimpRuler        *ruler = GIMP_RULER (object);
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);

  while (priv->track_widgets)
    gimp_ruler_remove_track_widget (ruler, priv->track_widgets->data);

  if (priv->pos_redraw_idle_id)
    {
      g_source_remove (priv->pos_redraw_idle_id);
      priv->pos_redraw_idle_id = 0;
    }

  G_OBJECT_CLASS (parent_class)->dispose (object);
}

static void
gimp_ruler_set_property (GObject      *object,
                         guint         prop_id,
                         const GValue *value,
                         GParamSpec   *pspec)
{
  GimpRuler        *ruler = GIMP_RULER (object);
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);

  switch (prop_id)
    {
    case PROP_ORIENTATION:
      priv->orientation = g_value_get_enum (value);
      gtk_widget_queue_resize (GTK_WIDGET (ruler));
      break;

    case PROP_UNIT:
      gimp_ruler_set_unit (ruler, g_value_get_int (value));
      break;

    case PROP_LOWER:
      gimp_ruler_set_range (ruler,
                            g_value_get_double (value),
                            priv->upper,
                            priv->max_size);
      break;
    case PROP_UPPER:
      gimp_ruler_set_range (ruler,
                            priv->lower,
                            g_value_get_double (value),
                            priv->max_size);
      break;

    case PROP_POSITION:
      gimp_ruler_set_position (ruler, g_value_get_double (value));
      break;

    case PROP_MAX_SIZE:
      gimp_ruler_set_range (ruler,
                            priv->lower,
                            priv->upper,
                            g_value_get_double (value));
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
gimp_ruler_get_property (GObject    *object,
                         guint       prop_id,
                         GValue     *value,
                         GParamSpec *pspec)
{
  GimpRuler        *ruler = GIMP_RULER (object);
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);

  switch (prop_id)
    {
    case PROP_ORIENTATION:
      g_value_set_enum (value, priv->orientation);
      break;

    case PROP_UNIT:
      g_value_set_int (value, priv->unit);
      break;

    case PROP_LOWER:
      g_value_set_double (value, priv->lower);
      break;

    case PROP_UPPER:
      g_value_set_double (value, priv->upper);
      break;

    case PROP_POSITION:
      g_value_set_double (value, priv->position);
      break;

    case PROP_MAX_SIZE:
      g_value_set_double (value, priv->max_size);
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

/**
 * gimp_ruler_new:
 * @orientation: the ruler's orientation.
 *
 * Creates a new ruler.
 *
 * Returns: a new #GimpRuler widget.
 *
 * Since: 2.8
 **/
GtkWidget *
gimp_ruler_new (GtkOrientation orientation)
{
  return g_object_new (GIMP_TYPE_RULER,
                       "orientation", orientation,
                       NULL);
}

static void
gimp_ruler_update_position (GimpRuler *ruler,
                            gdouble    x,
                            gdouble    y)
{
  GimpRulerPrivate *priv = GET_PRIVATE (ruler);
  GtkAllocation     allocation;
  gdouble           lower;
  gdouble           upper;

  gtk_widget_get_allocation (GTK_WIDGET (ruler), &allocation);
  gimp_ruler_get_range (ruler, &lower, &upper, NULL);

  if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
    {
      gimp_ruler_set_position (ruler,
                               lower +
                               (upper - lower) * x / allocation.width);
    }
  else
    {
      gimp_ruler_set_position (ruler,
                               lower +
                               (upper - lower) * y / allocation.height);
    }
}

/* Returns TRUE if a translation should be done */
static gboolean
gtk_widget_get_translation_to_window (GtkWidget *widget,
                                      GdkWindow *window,
                                      int       *x,
                                      int       *y)
{
  GdkWindow *w, *widget_window;

  if (! gtk_widget_get_has_window (widget))
    {
      GtkAllocation allocation;

      gtk_widget_get_allocation (widget, &allocation);

      *x = -allocation.x;
      *y = -allocation.y;
    }
  else
    {
      *x = 0;
      *y = 0;
    }

  widget_window = gtk_widget_get_window (widget);

  for (w = window;
       w && w != widget_window;
       w = gdk_window_get_effective_parent (w))
    {
      gdouble px, py;

      gdk_window_coords_to_parent (w, *x, *y, &px, &py);

      *x += px;
      *y += py;
    }

  if (w == NULL)
    {
      *x = 0;
      *y = 0;
      return FALSE;
    }

  return TRUE;
}

static void
gimp_ruler_event_to_widget_coords (GtkWidget *widget,
                                   GdkWindow *window,
                                   gdouble    event_x,
                                   gdouble    event_y,
                                   gint      *widget_x,
                                   gint      *widget_y)
{
  gint tx, ty;

  if (gtk_widget_get_translation_to_window (widget, window, &tx, &ty))
    {
      event_x += tx;
      event_y += ty;
    }

  *widget_x = event_x;
  *widget_y = event_y;
}

static gboolean
gimp_ruler_track_widget_motion_notify (GtkWidget      *widget,
                                       GdkEventMotion *mevent,
                                       GimpRuler      *ruler)
{
  gint widget_x;
  gint widget_y;
  gint ruler_x;
  gint ruler_y;

  widget = gtk_get_event_widget ((GdkEvent *) mevent);

  gimp_ruler_event_to_widget_coords (widget, mevent->window,
                                     mevent->x, mevent->y,
                                     &widget_x, &widget_y);

  if (gtk_widget_translate_coordinates (widget, GTK_WIDGET (ruler),
                                        widget_x, widget_y,
                                        &ruler_x, &ruler_y))
    {
      gimp_ruler_update_position (ruler, ruler_x, ruler_y);
    }

  return FALSE;
}

/**
 * gimp_ruler_add_track_widget:
 * @ruler: a #GimpRuler
 * @widget: the track widget to add
 *
 * Adds a "track widget" to the ruler. The ruler will connect to
 * GtkWidget:motion-notify-event: on the track widget and update its
 * position marker accordingly. The marker is correctly updated also
 * for the track widget's children, regardless of whether they are
 * ordinary children of off-screen children.
 *
 * Since: 2.8
 */
void
gimp_ruler_add_track_widget (GimpRuler *ruler,
                             GtkWidget *widget)
{
  GimpRulerPrivate *priv;

  g_return_if_fail (GIMP_IS_RULER (ruler));
  g_return_if_fail (GTK_IS_WIDGET (ruler));

  priv = GET_PRIVATE (ruler);

  g_return_if_fail (g_list_find (priv->track_widgets, widget) == NULL);

  priv->track_widgets = g_list_prepend (priv->track_widgets, widget);

  g_signal_connect (widget, "motion-notify-event",
                    G_CALLBACK (gimp_ruler_track_widget_motion_notify),
                    ruler);
  g_signal_connect_swapped (widget, "destroy",
                            G_CALLBACK (gimp_ruler_remove_track_widget),
                            ruler);
}

/**
 * gimp_ruler_remove_track_widget:
 * @ruler: a #GimpRuler
 * @widget: the track widget to remove
 *
 * Removes a previously added track widget from the ruler. See
 * gimp_ruler_add_track_widget().
 *
 * Since: 2.8
 */
void
gimp_ruler_remove_track_widget (GimpRuler *ruler,
                                GtkWidget *widget)
{
  GimpRulerPrivate *priv;

  g_return_if_fail (GIMP_IS_RULER (ruler));
  g_return_if_fail (GTK_IS_WIDGET (ruler));

  priv = GET_PRIVATE (ruler);

  g_return_if_fail (g_list_find (priv->track_widgets, widget) != NULL);

  priv->track_widgets = g_list_remove (priv->track_widgets, widget);

  g_signal_handlers_disconnect_by_func (widget,
                                        gimp_ruler_track_widget_motion_notify,
                                        ruler);
  g_signal_handlers_disconnect_by_func (widget,
                                        gimp_ruler_remove_track_widget,
                                        ruler);
}

/**
 * gimp_ruler_set_unit:
 * @ruler: a #GimpRuler
 * @unit:  the #GimpUnit to set the ruler to
 *
 * This sets the unit of the ruler.
 *
 * Since: 2.8
 */
void
gimp_ruler_set_unit (GimpRuler *ruler,
                     GimpUnit   unit)
{
  GimpRulerPrivate *priv;

  g_return_if_fail (GIMP_IS_RULER (ruler));

  priv = GET_PRIVATE (ruler);

  if (priv->unit != unit)
    {
      priv->unit = unit;
      g_object_notify (G_OBJECT (ruler), "unit");

      priv->backing_store_valid = FALSE;
      gtk_widget_queue_draw (GTK_WIDGET (ruler));
    }
}

/**
 * gimp_ruler_get_unit:
 * @ruler: a #GimpRuler
 *
 * Returns: (transfer none): the unit currently used in the @ruler widget.
 *
 * Since: 2.8
 **/
GimpUnit
gimp_ruler_get_unit (GimpRuler *ruler)
{
  g_return_val_if_fail (GIMP_IS_RULER (ruler), 0);

  return GET_PRIVATE (ruler)->unit;
}

/**
 * gimp_ruler_set_position:
 * @ruler: a #GimpRuler
 * @position: the position to set the ruler to
 *
 * This sets the position of the ruler.
 *
 * Since: 2.8
 */
void
gimp_ruler_set_position (GimpRuler *ruler,
                         gdouble    position)
{
  GimpRulerPrivate *priv;

  g_return_if_fail (GIMP_IS_RULER (ruler));

  priv = GET_PRIVATE (ruler);

  if (priv->position != position)
    {
      GdkRectangle rect;
      gint xdiff, ydiff;

      priv->position = position;
      g_object_notify (G_OBJECT (ruler), "position");

      rect = gimp_ruler_get_pos_rect (ruler, priv->position);

      xdiff = rect.x - priv->last_pos_rect.x;
      ydiff = rect.y - priv->last_pos_rect.y;

      /*
       * If the position has changed far enough, queue a redraw immediately.
       * Otherwise, we only queue a redraw in a low priority idle handler, to
       * allow for other things (like updating the canvas) to run.
       *
       * TODO: This might not be necessary any more in GTK3 with the frame
       *       clock. Investigate this more after the port to GTK3.
       */
      if (priv->last_pos_rect.width  != 0 &&
          priv->last_pos_rect.height != 0 &&
          (ABS (xdiff) > IMMEDIATE_REDRAW_THRESHOLD ||
           ABS (ydiff) > IMMEDIATE_REDRAW_THRESHOLD))
        {
          if (priv->pos_redraw_idle_id)
            {
              g_source_remove (priv->pos_redraw_idle_id);
              priv->pos_redraw_idle_id = 0;
            }

          gimp_ruler_queue_pos_redraw (ruler);
        }
      else if (! priv->pos_redraw_idle_id)
        {
          priv->pos_redraw_idle_id =
            g_idle_add_full (G_PRIORITY_LOW,
                             gimp_ruler_idle_queue_pos_redraw,
                             ruler, NULL);
        }
    }
}

/**
 * gimp_ruler_get_position:
 * @ruler: a #GimpRuler
 *
 * Returns: the current position of the @ruler widget.
 *
 * Since: 2.8
 **/
gdouble
gimp_ruler_get_position (GimpRuler *ruler)
{
  g_return_val_if_fail (GIMP_IS_RULER (ruler), 0.0);

  return GET_PRIVATE (ruler)->position;
}

/**
 * gimp_ruler_set_range:
 * @ruler: a #GimpRuler
 * @lower: the lower limit of the ruler
 * @upper: the upper limit of the ruler
 * @max_size: the maximum size of the ruler used when calculating the space to
 * leave for the text
 *
 * This sets the range of the ruler.
 *
 * Since: 2.8
 */
void
gimp_ruler_set_range (GimpRuler *ruler,
                      gdouble    lower,
                      gdouble    upper,
                      gdouble    max_size)
{
  GimpRulerPrivate *priv;

  g_return_if_fail (GIMP_IS_RULER (ruler));

  priv = GET_PRIVATE (ruler);

  g_object_freeze_notify (G_OBJECT (ruler));
  if (priv->lower != lower)
    {
      priv->lower = lower;
      g_object_notify (G_OBJECT (ruler), "lower");
    }
  if (priv->upper != upper)
    {
      priv->upper = upper;
      g_object_notify (G_OBJECT (ruler), "upper");
    }
  if (priv->max_size != max_size)
    {
      priv->max_size = max_size;
      g_object_notify (G_OBJECT (ruler), "max-size");
    }
  g_object_thaw_notify (G_OBJECT (ruler));

  priv->backing_store_valid = FALSE;
  gtk_widget_queue_draw (GTK_WIDGET (ruler));
}

/**
 * gimp_ruler_get_range:
 * @ruler: a #GimpRuler
 * @lower: (out) (optional): location to store lower limit of the ruler,
 *                           or %NULL
 * @upper: (out) (optional): location to store upper limit of the ruler,
 *                           or %NULL
 * @max_size: (out) (optional): location to store the maximum size of the ruler
 *                              used when calculating the space to leave for
 *                              the text, or %NULL.
 *
 * Retrieves values indicating the range and current position of a #GimpRuler.
 * See gimp_ruler_set_range().
 *
 * Since: 2.8
 **/
void
gimp_ruler_get_range (GimpRuler *ruler,
                      gdouble   *lower,
                      gdouble   *upper,
                      gdouble   *max_size)
{
  GimpRulerPrivate *priv;

  g_return_if_fail (GIMP_IS_RULER (ruler));

  priv = GET_PRIVATE (ruler);

  if (lower)
    *lower = priv->lower;
  if (upper)
    *upper = priv->upper;
  if (max_size)
    *max_size = priv->max_size;
}

static void
gimp_ruler_realize (GtkWidget *widget)
{
  GimpRuler        *ruler = GIMP_RULER (widget);
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);
  GtkAllocation     allocation;
  GdkWindowAttr     attributes;
  gint              attributes_mask;

  GTK_WIDGET_CLASS (gimp_ruler_parent_class)->realize (widget);

  gtk_widget_get_allocation (widget, &allocation);

  attributes.window_type = GDK_WINDOW_CHILD;
  attributes.x           = allocation.x;
  attributes.y           = allocation.y;
  attributes.width       = allocation.width;
  attributes.height      = allocation.height;
  attributes.wclass      = GDK_INPUT_ONLY;
  attributes.event_mask  = (gtk_widget_get_events (widget) |
                            GDK_EXPOSURE_MASK              |
                            GDK_POINTER_MOTION_MASK);

  attributes_mask = GDK_WA_X | GDK_WA_Y;

  priv->input_window = gdk_window_new (gtk_widget_get_window (widget),
                                       &attributes, attributes_mask);
  gdk_window_set_user_data (priv->input_window, ruler);

  gimp_ruler_make_pixmap (ruler);
}

static void
gimp_ruler_unrealize (GtkWidget *widget)
{
  GimpRuler        *ruler = GIMP_RULER (widget);
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);

  g_clear_pointer (&priv->backing_store, cairo_surface_destroy);
  priv->backing_store_valid = FALSE;

  g_clear_object (&priv->layout);

  g_clear_pointer (&priv->input_window, gdk_window_destroy);

  GTK_WIDGET_CLASS (gimp_ruler_parent_class)->unrealize (widget);
}

static void
gimp_ruler_map (GtkWidget *widget)
{
  GimpRulerPrivate *priv = GET_PRIVATE (widget);

  GTK_WIDGET_CLASS (parent_class)->map (widget);

  if (priv->input_window)
    gdk_window_show (priv->input_window);
}

static void
gimp_ruler_unmap (GtkWidget *widget)
{
  GimpRulerPrivate *priv = GET_PRIVATE (widget);

  if (priv->input_window)
    gdk_window_hide (priv->input_window);

  GTK_WIDGET_CLASS (parent_class)->unmap (widget);
}

static void
gimp_ruler_size_allocate (GtkWidget     *widget,
                          GtkAllocation *allocation)
{
  GimpRuler        *ruler = GIMP_RULER (widget);
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);
  GtkAllocation     widget_allocation;
  gboolean          resized;

  gtk_widget_get_allocation (widget, &widget_allocation);

  resized = (widget_allocation.width  != allocation->width ||
             widget_allocation.height != allocation->height);

  GTK_WIDGET_CLASS (parent_class)->size_allocate (widget, allocation);

  if (gtk_widget_get_realized (widget))
    {
      gdk_window_move_resize (priv->input_window,
                              allocation->x, allocation->y,
                              allocation->width, allocation->height);

      if (resized)
        gimp_ruler_make_pixmap (ruler);
    }
}

static void
gimp_ruler_size_request (GtkWidget      *widget,
                         GtkRequisition *requisition)
{
  GimpRulerPrivate *priv    = GET_PRIVATE (widget);
  GtkStyleContext  *context = gtk_widget_get_style_context (widget);
  PangoLayout      *layout;
  PangoRectangle    ink_rect;
  GtkBorder         border;
  gint              size;

  layout = gimp_ruler_get_layout (widget, "0123456789");
  pango_layout_get_pixel_extents (layout, &ink_rect, NULL);

  size = 2 + ink_rect.height * 1.7;

  gtk_style_context_get_border (context, 0, &border);

  requisition->width  = border.left + border.right;
  requisition->height = border.top + border.bottom;

  if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
    {
      requisition->width  += 1;
      requisition->height += size;
    }
  else
    {
      requisition->width  += size;
      requisition->height += 1;
    }
}

static void
gimp_ruler_get_preferred_width (GtkWidget *widget,
                                gint      *minimum_width,
                                gint      *natural_width)
{
  GtkRequisition requisition;

  gimp_ruler_size_request (widget, &requisition);

  *minimum_width = *natural_width = requisition.width;
}

static void
gimp_ruler_get_preferred_height (GtkWidget *widget,
                                 gint      *minimum_height,
                                 gint      *natural_height)
{
  GtkRequisition requisition;

  gimp_ruler_size_request (widget, &requisition);

  *minimum_height = *natural_height = requisition.height;
}

static void
gimp_ruler_style_updated (GtkWidget *widget)
{
  GimpRulerPrivate *priv = GET_PRIVATE (widget);

  GTK_WIDGET_CLASS (gimp_ruler_parent_class)->style_updated (widget);

  priv->backing_store_valid = FALSE;

  g_clear_object (&priv->layout);
}

static gboolean
gimp_ruler_motion_notify (GtkWidget      *widget,
                          GdkEventMotion *event)
{
  GimpRuler *ruler = GIMP_RULER (widget);

  gimp_ruler_update_position (ruler, event->x, event->y);

  return FALSE;
}

static gboolean
gimp_ruler_draw (GtkWidget *widget,
                 cairo_t   *cr)
{
  GimpRuler        *ruler   = GIMP_RULER (widget);
  GimpRulerPrivate *priv    = GET_PRIVATE (ruler);
  GtkStyleContext  *context = gtk_widget_get_style_context (widget);
  GtkAllocation     allocation;

  gtk_widget_get_allocation (widget, &allocation);
  gtk_render_background (context, cr, 0, 0, allocation.width, allocation.height);
  gtk_render_frame (context, cr, 0, 0, allocation.width, allocation.height);

  if (! priv->backing_store_valid)
    gimp_ruler_draw_ticks (ruler);

  cairo_set_source_surface (cr, priv->backing_store, 0, 0);
  cairo_paint (cr);

  gimp_ruler_draw_pos (ruler, cr);

  return FALSE;
}

static void
gimp_ruler_draw_ticks (GimpRuler *ruler)
{
  GtkWidget         *widget  = GTK_WIDGET (ruler);
  GtkStyleContext   *context = gtk_widget_get_style_context (widget);
  GimpRulerPrivate  *priv    = GET_PRIVATE (ruler);
  GtkAllocation      allocation;
  GtkBorder          border;
  GdkRGBA            color;
  cairo_t           *cr;
  gint               i;
  gint               width, height;
  gint               length, ideal_length;
  gdouble            lower, upper;  /* Upper and lower limits, in ruler units */
  gdouble            increment;     /* Number of pixels per unit */
  gint               scale;         /* Number of units per major unit */
  gdouble            start, end, cur;
  gchar              unit_str[32];
  gint               digit_height;
  gint               digit_offset;
  gint               text_size;
  gint               pos;
  gdouble            max_size;
  GimpUnit           unit;
  PangoLayout       *layout;
  PangoRectangle     logical_rect, ink_rect;
  const RulerMetric *ruler_metric;

  if (! gtk_widget_is_drawable (widget))
    return;

  gtk_widget_get_allocation (widget, &allocation);
  gtk_style_context_get_border (context, 0, &border);

  layout = gimp_ruler_get_layout (widget, "0123456789");
  pango_layout_get_extents (layout, &ink_rect, &logical_rect);

  digit_height = PANGO_PIXELS (ink_rect.height) + 2;
  digit_offset = ink_rect.y;

  if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
    {
      width  = allocation.width;
      height = allocation.height - (border.top + border.bottom);
    }
  else
    {
      width  = allocation.height;
      height = allocation.width - (border.top + border.bottom);
    }

  cr = cairo_create (priv->backing_store);

  cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR);
  cairo_paint (cr);
  cairo_set_operator (cr, CAIRO_OPERATOR_OVER);

  gtk_style_context_get_color (context, gtk_widget_get_state_flags (widget),
                               &color);
  gdk_cairo_set_source_rgba (cr, &color);

  if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
    {
      cairo_rectangle (cr,
                       border.left,
                       height + border.top,
                       allocation.width - (border.left + border.right),
                       1);
    }
  else
    {
      cairo_rectangle (cr,
                       height + border.left,
                       border.top,
                       1,
                       allocation.height - (border.top + border.bottom));
    }

  gimp_ruler_get_range (ruler, &lower, &upper, &max_size);

  if ((upper - lower) == 0)
    goto out;

  increment = (gdouble) width / (upper - lower);

  /* determine the scale
   *   use the maximum extents of the ruler to determine the largest
   *   possible number to be displayed.  Calculate the height in pixels
   *   of this displayed text. Use this height to find a scale which
   *   leaves sufficient room for drawing the ruler.
   *
   *   We calculate the text size as for the vruler instead of
   *   actually measuring the text width, so that the result for the
   *   scale looks consistent with an accompanying vruler.
   */
  scale = ceil (max_size);
  g_snprintf (unit_str, sizeof (unit_str), "%d", scale);
  text_size = strlen (unit_str) * digit_height + 1;

  unit = gimp_ruler_get_unit (ruler);

  ruler_metric = gimp_ruler_get_metric (unit);

  for (scale = 0; scale < G_N_ELEMENTS (ruler_metric->ruler_scale); scale++)
    if (ruler_metric->ruler_scale[scale] * fabs (increment) > 2 * text_size)
      break;

  if (scale == G_N_ELEMENTS (ruler_metric->ruler_scale))
    scale = G_N_ELEMENTS (ruler_metric->ruler_scale) - 1;

  /* drawing starts here */
  length = 0;
  for (i = G_N_ELEMENTS (ruler_metric->subdivide) - 1; i >= 0; i--)
    {
      gdouble subd_incr;

      /* hack to get proper subdivisions at full pixels */
      if (unit == GIMP_UNIT_PIXEL && scale == 1 && i == 1)
        subd_incr = 1.0;
      else
        subd_incr = ((gdouble) ruler_metric->ruler_scale[scale] /
                     (gdouble) ruler_metric->subdivide[i]);

      if (subd_incr * fabs (increment) <= MINIMUM_INCR)
        continue;

      /* don't subdivide pixels */
      if (unit == GIMP_UNIT_PIXEL && subd_incr < 1.0)
        continue;

      /* Calculate the length of the tickmarks. Make sure that
       * this length increases for each set of ticks
       */
      ideal_length = height / (i + 1) - 1;
      if (ideal_length > ++length)
        length = ideal_length;

      if (lower < upper)
        {
          start = floor (lower / subd_incr) * subd_incr;
          end   = ceil  (upper / subd_incr) * subd_incr;
        }
      else
        {
          start = floor (upper / subd_incr) * subd_incr;
          end   = ceil  (lower / subd_incr) * subd_incr;
        }

      for (cur = start; cur <= end; cur += subd_incr)
        {
          pos = ROUND ((cur - lower) * increment);

          if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
            {
              cairo_rectangle (cr,
                               pos, height + border.top - length,
                               1,   length);
            }
          else
            {
              cairo_rectangle (cr,
                               height + border.left - length, pos,
                               length,                        1);
            }

          /* draw label */
          if (i == 0)
            {
              g_snprintf (unit_str, sizeof (unit_str), "%d", (int) cur);

              if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
                {
                  pango_layout_set_text (layout, unit_str, -1);
                  pango_layout_get_extents (layout, &logical_rect, NULL);

                  cairo_move_to (cr,
                                 pos + 2,
                                 border.top + PANGO_PIXELS (logical_rect.y - digit_offset));
                  pango_cairo_show_layout (cr, layout);
                }
              else
                {
                  gint j;

                  for (j = 0; j < (int) strlen (unit_str); j++)
                    {
                      pango_layout_set_text (layout, unit_str + j, 1);
                      pango_layout_get_extents (layout, NULL, &logical_rect);

                      cairo_move_to (cr,
                                     border.left + 1,
                                     pos + digit_height * j + 2 + PANGO_PIXELS (logical_rect.y - digit_offset));
                      pango_cairo_show_layout (cr, layout);
                    }
                }
            }
        }
    }

  cairo_fill (cr);

  priv->backing_store_valid = TRUE;

out:
  cairo_destroy (cr);
}

static GdkRectangle
gimp_ruler_get_pos_rect (GimpRuler *ruler,
                         gdouble    position)
{
  GtkWidget        *widget  = GTK_WIDGET (ruler);
  GtkStyleContext  *context = gtk_widget_get_style_context (widget);
  GimpRulerPrivate *priv    = GET_PRIVATE (ruler);
  GtkAllocation     allocation;
  GtkBorder         border;
  gint              width, height;
  gdouble           upper, lower;
  gdouble           increment;
  GdkRectangle      rect = { 0, };

  if (! gtk_widget_is_drawable (widget))
    return rect;

  gtk_widget_get_allocation (widget, &allocation);
  gtk_style_context_get_border (context, 0, &border);

  if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
    {
      width  = allocation.width;
      height = allocation.height - (border.top + border.bottom);

      rect.width = height / 2 + 2;
      rect.width |= 1;  /* make sure it's odd */
      rect.height = rect.width / 2 + 1;
    }
  else
    {
      width  = allocation.width - (border.left + border.right);
      height = allocation.height;

      rect.height = width / 2 + 2;
      rect.height |= 1;  /* make sure it's odd */
      rect.width = rect.height / 2 + 1;
    }

  gimp_ruler_get_range (ruler, &lower, &upper, NULL);

  if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
    {
      increment = (gdouble) width / (upper - lower);

      rect.x = ROUND ((position - lower) * increment) + (border.left + border.right - rect.width) / 2 - 1;
      rect.y = (height + rect.height) / 2 + border.top;
    }
  else
    {
      increment = (gdouble) height / (upper - lower);

      rect.x = (width + rect.width) / 2 + border.left;
      rect.y = ROUND ((position - lower) * increment) + (border.top + border.bottom - rect.height) / 2 - 1;
    }

  return rect;
}

static gboolean
gimp_ruler_idle_queue_pos_redraw (gpointer data)
{
  GimpRuler        *ruler = data;
  GimpRulerPrivate *priv  = GET_PRIVATE (ruler);

  gimp_ruler_queue_pos_redraw (ruler);

  priv->pos_redraw_idle_id = 0;

  return G_SOURCE_REMOVE;
}

static void
gimp_ruler_queue_pos_redraw (GimpRuler *ruler)
{
  GimpRulerPrivate  *priv = GET_PRIVATE (ruler);
  const GdkRectangle rect = gimp_ruler_get_pos_rect (ruler, priv->position);
  GtkAllocation      allocation;

  gtk_widget_get_allocation (GTK_WIDGET(ruler), &allocation);

  gtk_widget_queue_draw_area (GTK_WIDGET (ruler),
                              rect.x + allocation.x,
                              rect.y + allocation.y,
                              rect.width,
                              rect.height);

  if (priv->last_pos_rect.width  != 0 &&
      priv->last_pos_rect.height != 0)
    {
      gtk_widget_queue_draw_area (GTK_WIDGET (ruler),
                                  priv->last_pos_rect.x + allocation.x,
                                  priv->last_pos_rect.y + allocation.y,
                                  priv->last_pos_rect.width,
                                  priv->last_pos_rect.height);

      priv->last_pos_rect.x      = 0;
      priv->last_pos_rect.y      = 0;
      priv->last_pos_rect.width  = 0;
      priv->last_pos_rect.height = 0;
    }
}

static void
gimp_ruler_draw_pos (GimpRuler *ruler,
                     cairo_t   *cr)
{
  GtkWidget        *widget  = GTK_WIDGET (ruler);
  GtkStyleContext  *context = gtk_widget_get_style_context (widget);
  GimpRulerPrivate *priv    = GET_PRIVATE (ruler);
  GdkRectangle      pos_rect;

  if (! gtk_widget_is_drawable (widget))
    return;

  pos_rect = gimp_ruler_get_pos_rect (ruler, gimp_ruler_get_position (ruler));

  if ((pos_rect.width > 0) && (pos_rect.height > 0))
    {
      GdkRGBA color;

      gtk_style_context_get_color (context, gtk_widget_get_state_flags (widget),
                                   &color);
      gdk_cairo_set_source_rgba (cr, &color);

      cairo_move_to (cr, pos_rect.x, pos_rect.y);

      if (priv->orientation == GTK_ORIENTATION_HORIZONTAL)
        {
          cairo_line_to (cr, pos_rect.x + pos_rect.width / 2.0,
                             pos_rect.y + pos_rect.height);
          cairo_line_to (cr, pos_rect.x + pos_rect.width,
                             pos_rect.y);
        }
      else
        {
          cairo_line_to (cr, pos_rect.x + pos_rect.width,
                             pos_rect.y + pos_rect.height / 2.0);
          cairo_line_to (cr, pos_rect.x,
                             pos_rect.y + pos_rect.height);
        }

      cairo_fill (cr);
    }

  if (priv->last_pos_rect.width  != 0 &&
      priv->last_pos_rect.height != 0)
    {
      gdk_rectangle_union (&priv->last_pos_rect,
                           &pos_rect,
                           &priv->last_pos_rect);
    }
  else
    {
      priv->last_pos_rect = pos_rect;
    }
}

static void
gimp_ruler_make_pixmap (GimpRuler *ruler)
{
  GtkWidget        *widget = GTK_WIDGET (ruler);
  GimpRulerPrivate *priv   = GET_PRIVATE (ruler);
  GtkAllocation     allocation;

  gtk_widget_get_allocation (widget, &allocation);

  if (priv->backing_store)
    cairo_surface_destroy (priv->backing_store);

  priv->backing_store =
    gdk_window_create_similar_surface (gtk_widget_get_window (widget),
                                       CAIRO_CONTENT_COLOR_ALPHA,
                                       allocation.width,
                                       allocation.height);

  priv->backing_store_valid = FALSE;
}

static PangoLayout *
gimp_ruler_get_layout (GtkWidget   *widget,
                       const gchar *text)
{
  GimpRulerPrivate *priv = GET_PRIVATE (widget);

  if (priv->layout)
    {
      pango_layout_set_text (priv->layout, text, -1);
      return priv->layout;
    }

  priv->layout = gtk_widget_create_pango_layout (widget, text);

  return priv->layout;
}

#define FACTOR_EPSILON  0.0000001
#define FACTOR_EQUAL(u, f) (ABS (f - gimp_unit_get_factor (u)) < FACTOR_EPSILON)

static const RulerMetric *
gimp_ruler_get_metric (GimpUnit unit)
{
  if (unit == GIMP_UNIT_INCH)
    {
      return  &ruler_metric_inches;
    }
  /* XXX: recognizing feet or yard unit this way definitely sucks.
   * Actually the subdvision and rule scale rules should probably become
   * settable values in unitrc instead of hardcoded rules.
   * This way, people would be able to set how they want a unit to be
   * shown (we could definitely imagine someone wanting to see inches
   * with base-10 divisions).
   */
  else if (FACTOR_EQUAL (unit, 0.083333))
    {
      return  &ruler_metric_feet;
    }
  else if (FACTOR_EQUAL (unit, 0.027778))
    {
      return  &ruler_metric_yards;
    }

  return &ruler_metric_decimal;
}

{'repo_name': 'GNOME/gimp', 'stars': '2424', 'repo_language': 'C', 'file_name': 'sr@latin.po', 'mime_type': 'text/x-po', 'hash': -769727415188777813, 'source_dataset': 'data'}


module Diakonos
  class Diakonos

    # @return [Integer] the number of replacements made
    def find_( options = {} )
      regexp_source, replacement = options.values_at( :regexp_source, :replacement )
      return  if regexp_source.nil? || regexp_source.empty?

      rs_array = regexp_source.newline_split
      regexps = Array.new
      exception_thrown = nil

      rs_array.each do |source|
        begin
          warning_verbosity = $VERBOSE
          $VERBOSE = nil
          regexps << Regexp.new(
            source,
            options[:case_sensitive] ? nil : Regexp::IGNORECASE
          )
          $VERBOSE = warning_verbosity
        rescue RegexpError => e
          if ! exception_thrown
            exception_thrown = e
            source = Regexp.escape( source )
            retry
          else
            raise e
          end
        end
      end

      if replacement == ASK_REPLACEMENT
        replacement = get_user_input( "Replace with: ", history: @rlh_search )
      end

      if exception_thrown && ! options[:quiet]
        set_iline "Searching literally; #{exception_thrown.message}"
      end

      # The execution order of the #find and the @last_search_regexps assignment is likely deliberate
      num_replacements = buffer_current.find(
        regexps,
        :direction          => options[:direction],
        :replacement        => replacement,
        :starting_row       => options[:starting_row],
        :starting_col       => options[:starting_col],
        :quiet              => options[:quiet],
        :show_context_after => @settings[ 'find.show_context_after' ],
        :starting           => true
      )
      @last_search_regexps = regexps

      num_replacements
    end

  end
end

{'repo_name': 'Pistos/diakonos', 'stars': '125', 'repo_language': 'Ruby', 'file_name': 'buffers.rb', 'mime_type': 'text/x-ruby', 'hash': -8672693299163410184, 'source_dataset': 'data'}


////
///  StreamHeaderCellPresenter.swift
//

import TimeAgoInWords

struct StreamHeaderCellPresenter {

    static func configure(
        _ cell: UICollectionViewCell,
        streamCellItem: StreamCellItem,
        streamKind: StreamKind,
        indexPath: IndexPath,
        currentUser: User?
    ) {
        guard let cell = cell as? StreamHeaderCell,
            let post = streamCellItem.jsonable as? Post
        else { return }

        let isGridView = streamCellItem.isGridView(streamKind: streamKind)

        switch streamKind {
        case .postDetail:
            cell.showUsername = false
        default:
            cell.showUsername = true
        }

        var author = post.author
        var repostedBy: User?

        cell.isGridView = isGridView
        cell.chevronHidden = true

        if let repostAuthor = post.repostAuthor {
            repostedBy = author
            author = repostAuthor
        }

        let isAuthor = currentUser?.isAuthorOf(post: post) ?? false
        let followButtonVisible = !isAuthor && streamKind.isDetail(post: post)

        var category: Category?
        if streamKind.showsCategory {
            category = post.category
        }

        let isSubmission: Bool
        if streamKind.showsSubmission,
            post.artistInviteId != nil
        {
            isSubmission = true
        }
        else {
            isSubmission = false
        }
        cell.setDetails(
            user: author,
            repostedBy: repostedBy,
            category: category,
            isSubmission: isSubmission
        )
        cell.followButtonVisible = followButtonVisible
        if isGridView {
            cell.timeStamp = ""
        }
        else {
            cell.timeStamp = post.createdAt.timeAgoInWords()
        }
        cell.layoutIfNeeded()
    }
}

{'repo_name': 'ello/ello-ios', 'stars': '726', 'repo_language': 'Swift', 'file_name': 'MainInterface.storyboard', 'mime_type': 'text/xml', 'hash': 4166797255546177624, 'source_dataset': 'data'}


<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.mashibing.springboot</groupId>
		<artifactId>dubbo01</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>oa-consumer</artifactId>

	<dependencies>
		<!-- API -->
		<dependency>
			<groupId>com.mashibing.springboot</groupId>
			<artifactId>api</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>

			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-starter-thymeleaf</artifactId>
			</dependency>

		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>com.spring4all</groupId>
			<artifactId>swagger-spring-boot-starter</artifactId>
		</dependency>

		<!-- 父子项目 继承的时候 如果在 父项目 还有爷爷项目 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.github.liyiorg</groupId>
			<artifactId>weixin-popular</artifactId>
		</dependency>
	</dependencies>
</project>

{'repo_name': 'bjmashibing/InternetArchitect', 'stars': '2606', 'repo_language': 'Java', 'file_name': 'org.eclipse.jdt.core.prefs', 'mime_type': 'text/plain', 'hash': -406899120686187628, 'source_dataset': 'data'}


// Copyright Sascha Ochsenknecht 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/detail/cmdline.hpp>
using namespace boost::program_options;
using boost::program_options::detail::cmdline;

#include <iostream>
#include <sstream>
#include <vector>
#include <cassert>
using namespace std;

#include "minitest.hpp"

// Test free function collect_unrecognized()
//
//  it collects the tokens of all not registered options. It can be used
//  to pass them to an own parser implementation

void test_unrecognize_cmdline()
{
   options_description desc;

   string content = "prg --input input.txt --optimization 4 --opt option";
   vector< string > tokens =  split_unix(content);

   cmdline cmd(tokens);
   cmd.set_options_description(desc);
   cmd.allow_unregistered();

   vector< option > opts = cmd.run();
   vector< string > result = collect_unrecognized(opts, include_positional);

   BOOST_CHECK_EQUAL(result.size(), 7);
   BOOST_CHECK_EQUAL(result[0], "prg");
   BOOST_CHECK_EQUAL(result[1], "--input");
   BOOST_CHECK_EQUAL(result[2], "input.txt");
   BOOST_CHECK_EQUAL(result[3], "--optimization");
   BOOST_CHECK_EQUAL(result[4], "4");
   BOOST_CHECK_EQUAL(result[5], "--opt");
   BOOST_CHECK_EQUAL(result[6], "option");
}

void test_unrecognize_config()
{

   options_description desc;

   string content  =
    " input = input.txt\n"
    " optimization = 4\n"
    " opt = option\n"
    ;

   stringstream ss(content);
   vector< option > opts = parse_config_file(ss, desc, true).options;
   vector< string > result = collect_unrecognized(opts, include_positional);

   BOOST_CHECK_EQUAL(result.size(), 6);
   BOOST_CHECK_EQUAL(result[0], "input");
   BOOST_CHECK_EQUAL(result[1], "input.txt");
   BOOST_CHECK_EQUAL(result[2], "optimization");
   BOOST_CHECK_EQUAL(result[3], "4");
   BOOST_CHECK_EQUAL(result[4], "opt");
   BOOST_CHECK_EQUAL(result[5], "option");
}

int main(int /*ac*/, char** /*av*/)
{
   test_unrecognize_cmdline();
   test_unrecognize_config();

   return 0;
}

{'repo_name': 'blackberry/Boost', 'stars': '135', 'repo_language': 'C++', 'file_name': 'embedding.html', 'mime_type': 'text/html', 'hash': -5084819461502917915, 'source_dataset': 'data'}


/*
 * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) 2008 Apple Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"

#if ENABLE(SVG_FONTS)
#include "SVGFontFaceElement.h"

#include "CSSFontFaceSrcValue.h"
#include "CSSParser.h"
#include "CSSPropertyNames.h"
#include "CSSStyleSheet.h"
#include "CSSValueKeywords.h"
#include "CSSValueList.h"
#include "Document.h"
#include "ElementIterator.h"
#include "FontCascade.h"
#include "Logging.h"
#include "SVGDocumentExtensions.h"
#include "SVGFontElement.h"
#include "SVGFontFaceSrcElement.h"
#include "SVGGlyphElement.h"
#include "SVGNames.h"
#include "StyleProperties.h"
#include "StyleResolver.h"
#include "StyleRule.h"
#include "StyleScope.h"
#include <math.h>
#include <wtf/IsoMallocInlines.h>

namespace WebCore {

WTF_MAKE_ISO_ALLOCATED_IMPL(SVGFontFaceElement);

using namespace SVGNames;

inline SVGFontFaceElement::SVGFontFaceElement(const QualifiedName& tagName, Document& document)
    : SVGElement(tagName, document)
    , m_fontFaceRule(StyleRuleFontFace::create(MutableStyleProperties::create(HTMLStandardMode)))
    , m_fontElement(nullptr)
{
    LOG(Fonts, "SVGFontFaceElement %p ctor", this);
    ASSERT(hasTagName(font_faceTag));
}

SVGFontFaceElement::~SVGFontFaceElement()
{
    LOG(Fonts, "SVGFontFaceElement %p dtor", this);
}

Ref<SVGFontFaceElement> SVGFontFaceElement::create(const QualifiedName& tagName, Document& document)
{
    return adoptRef(*new SVGFontFaceElement(tagName, document));
}

void SVGFontFaceElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    CSSPropertyID propertyId = cssPropertyIdForSVGAttributeName(name);
    if (propertyId > 0) {
        // FIXME: Parse using the @font-face descriptor grammars, not the property grammars.
        auto& properties = m_fontFaceRule->mutableProperties();
        bool valueChanged = properties.setProperty(propertyId, value);

        if (valueChanged) {
            // The above parser is designed for the font-face properties, not descriptors, and the properties accept the global keywords, but descriptors don't.
            // Rather than invasively modifying the parser for the properties to have a special mode, we can simply detect the error condition after-the-fact and
            // avoid it explicitly.
            if (auto parsedValue = properties.getPropertyCSSValue(propertyId)) {
                if (parsedValue->isGlobalKeyword())
                    properties.removeProperty(propertyId);
            }
        }

        rebuildFontFace();
        return;
    }

    SVGElement::parseAttribute(name, value);
}

unsigned SVGFontFaceElement::unitsPerEm() const
{
    const AtomicString& valueString = attributeWithoutSynchronization(units_per_emAttr);
    if (valueString.isEmpty())
        return FontMetrics::defaultUnitsPerEm;

    auto value = static_cast<unsigned>(ceilf(valueString.toFloat()));
    if (!value)
        return FontMetrics::defaultUnitsPerEm;

    return value;
}

int SVGFontFaceElement::xHeight() const
{
    return static_cast<int>(ceilf(attributeWithoutSynchronization(x_heightAttr).toFloat()));
}

int SVGFontFaceElement::capHeight() const
{
    return static_cast<int>(ceilf(attributeWithoutSynchronization(cap_heightAttr).toFloat()));
}

float SVGFontFaceElement::horizontalOriginX() const
{
    if (!m_fontElement)
        return 0.0f;

    // Spec: The X-coordinate in the font coordinate system of the origin of a glyph to be used when
    // drawing horizontally oriented text. (Note that the origin applies to all glyphs in the font.)
    // If the attribute is not specified, the effect is as if a value of "0" were specified.
    return m_fontElement->attributeWithoutSynchronization(horiz_origin_xAttr).toFloat();
}

float SVGFontFaceElement::horizontalOriginY() const
{
    if (!m_fontElement)
        return 0.0f;

    // Spec: The Y-coordinate in the font coordinate system of the origin of a glyph to be used when
    // drawing horizontally oriented text. (Note that the origin applies to all glyphs in the font.)
    // If the attribute is not specified, the effect is as if a value of "0" were specified.
    return m_fontElement->attributeWithoutSynchronization(horiz_origin_yAttr).toFloat();
}

float SVGFontFaceElement::horizontalAdvanceX() const
{
    if (!m_fontElement)
        return 0.0f;

    // Spec: The default horizontal advance after rendering a glyph in horizontal orientation. Glyph
    // widths are required to be non-negative, even if the glyph is typically rendered right-to-left,
    // as in Hebrew and Arabic scripts.
    return m_fontElement->attributeWithoutSynchronization(horiz_adv_xAttr).toFloat();
}

float SVGFontFaceElement::verticalOriginX() const
{
    if (!m_fontElement)
        return 0.0f;

    // Spec: The default X-coordinate in the font coordinate system of the origin of a glyph to be used when
    // drawing vertically oriented text. If the attribute is not specified, the effect is as if the attribute
    // were set to half of the effective value of attribute horiz-adv-x.
    const AtomicString& value = m_fontElement->attributeWithoutSynchronization(vert_origin_xAttr);
    if (value.isEmpty())
        return horizontalAdvanceX() / 2.0f;

    return value.toFloat();
}

float SVGFontFaceElement::verticalOriginY() const
{
    if (!m_fontElement)
        return 0.0f;

    // Spec: The default Y-coordinate in the font coordinate system of the origin of a glyph to be used when
    // drawing vertically oriented text. If the attribute is not specified, the effect is as if the attribute
    // were set to the position specified by the font's ascent attribute.
    const AtomicString& value = m_fontElement->attributeWithoutSynchronization(vert_origin_yAttr);
    if (value.isEmpty())
        return ascent();

    return value.toFloat();
}

float SVGFontFaceElement::verticalAdvanceY() const
{
    if (!m_fontElement)
        return 0.0f;

    // Spec: The default vertical advance after rendering a glyph in vertical orientation. If the attribute is
    // not specified, the effect is as if a value equivalent of one em were specified (see units-per-em).
    const AtomicString& value = m_fontElement->attributeWithoutSynchronization(vert_adv_yAttr);
       if (value.isEmpty())
        return 1.0f;

    return value.toFloat();
}

int SVGFontFaceElement::ascent() const
{
    // Spec: Same syntax and semantics as the 'ascent' descriptor within an @font-face rule. The maximum
    // unaccented height of the font within the font coordinate system. If the attribute is not specified,
    // the effect is as if the attribute were set to the difference between the units-per-em value and the
    // vert-origin-y value for the corresponding font.
    const AtomicString& ascentValue = attributeWithoutSynchronization(ascentAttr);
    if (!ascentValue.isEmpty())
        return static_cast<int>(ceilf(ascentValue.toFloat()));

    if (m_fontElement) {
        const AtomicString& vertOriginY = m_fontElement->attributeWithoutSynchronization(vert_origin_yAttr);
        if (!vertOriginY.isEmpty())
            return static_cast<int>(unitsPerEm()) - static_cast<int>(ceilf(vertOriginY.toFloat()));
    }

    // Match Batiks default value
    return static_cast<int>(ceilf(unitsPerEm() * 0.8f));
}

int SVGFontFaceElement::descent() const
{
    // Spec: Same syntax and semantics as the 'descent' descriptor within an @font-face rule. The maximum
    // unaccented depth of the font within the font coordinate system. If the attribute is not specified,
    // the effect is as if the attribute were set to the vert-origin-y value for the corresponding font.
    const AtomicString& descentValue = attributeWithoutSynchronization(descentAttr);
    if (!descentValue.isEmpty()) {
        // 14 different W3C SVG 1.1 testcases use a negative descent value,
        // where a positive was meant to be used  Including:
        // animate-elem-24-t.svg, fonts-elem-01-t.svg, fonts-elem-02-t.svg (and 11 others)
        int descent = static_cast<int>(ceilf(descentValue.toFloat()));
        return descent < 0 ? -descent : descent;
    }

    if (m_fontElement) {
        const AtomicString& vertOriginY = m_fontElement->attributeWithoutSynchronization(vert_origin_yAttr);
        if (!vertOriginY.isEmpty())
            return static_cast<int>(ceilf(vertOriginY.toFloat()));
    }

    // Match Batiks default value
    return static_cast<int>(ceilf(unitsPerEm() * 0.2f));
}

String SVGFontFaceElement::fontFamily() const
{
    return m_fontFaceRule->properties().getPropertyValue(CSSPropertyFontFamily);
}

SVGFontElement* SVGFontFaceElement::associatedFontElement() const
{
    ASSERT(parentNode() == m_fontElement);
    ASSERT(!parentNode() || is<SVGFontElement>(*parentNode()));
    return m_fontElement;
}

void SVGFontFaceElement::rebuildFontFace()
{
    if (!isConnected()) {
        ASSERT(!m_fontElement);
        return;
    }

    // we currently ignore all but the first src element, alternatively we could concat them
    auto srcElement = childrenOfType<SVGFontFaceSrcElement>(*this).first();

    bool describesParentFont = is<SVGFontElement>(*parentNode());
    RefPtr<CSSValueList> list;

    if (describesParentFont) {
        m_fontElement = downcast<SVGFontElement>(parentNode());

        list = CSSValueList::createCommaSeparated();
        list->append(CSSFontFaceSrcValue::createLocal(fontFamily()));
    } else {
        m_fontElement = nullptr;
        if (srcElement)
            list = srcElement->srcValue();
    }

    if (!list || !list->length())
        return;

    // Parse in-memory CSS rules
    m_fontFaceRule->mutableProperties().addParsedProperty(CSSProperty(CSSPropertySrc, list));

    if (describesParentFont) {
        // Traverse parsed CSS values and associate CSSFontFaceSrcValue elements with ourselves.
        RefPtr<CSSValue> src = m_fontFaceRule->properties().getPropertyCSSValue(CSSPropertySrc);
        CSSValueList* srcList = downcast<CSSValueList>(src.get());

        unsigned srcLength = srcList ? srcList->length() : 0;
        for (unsigned i = 0; i < srcLength; ++i) {
            if (auto item = makeRefPtr(downcast<CSSFontFaceSrcValue>(srcList->itemWithoutBoundsCheck(i))))
                item->setSVGFontFaceElement(this);
        }
    }

    document().styleScope().didChangeStyleSheetEnvironment();
}

Node::InsertedIntoAncestorResult SVGFontFaceElement::insertedIntoAncestor(InsertionType insertionType, ContainerNode& parentOfInsertedTree)
{
    SVGElement::insertedIntoAncestor(insertionType, parentOfInsertedTree);
    if (!insertionType.connectedToDocument) {
        ASSERT(!m_fontElement);
        return InsertedIntoAncestorResult::Done;
    }
    document().accessSVGExtensions().registerSVGFontFaceElement(*this);

    rebuildFontFace();
    return InsertedIntoAncestorResult::Done;
}

void SVGFontFaceElement::removedFromAncestor(RemovalType removalType, ContainerNode& oldParentOfRemovedTree)
{
    SVGElement::removedFromAncestor(removalType, oldParentOfRemovedTree);

    if (removalType.disconnectedFromDocument) {
        m_fontElement = nullptr;
        document().accessSVGExtensions().unregisterSVGFontFaceElement(*this);
        m_fontFaceRule->mutableProperties().clear();

        document().styleScope().didChangeStyleSheetEnvironment();
    } else
        ASSERT(!m_fontElement);
}

void SVGFontFaceElement::childrenChanged(const ChildChange& change)
{
    SVGElement::childrenChanged(change);
    rebuildFontFace();
}

} // namespace WebCore

#endif // ENABLE(SVG_FONTS)

{'repo_name': 'javafxports/openjdk-jfx', 'stars': '1025', 'repo_language': 'C++', 'file_name': 'Makefile-Debug.mk', 'mime_type': 'text/x-makefile', 'hash': 3969959830351614172, 'source_dataset': 'data'}


// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
sah{
    Currencies{
        RUB{
            "₽",
            "Арассыыйа солкуобайа",
        }
        USD{
            "US$",
            "АХШ дуоллара",
        }
    }
    Currencies%narrow{
        RUB{"₽"}
    }
    CurrencyPlurals{
        RUB{
            other{"Арассыыйа солкуобайа"}
        }
        USD{
            other{"АХШ дуоллара"}
        }
    }
    CurrencyUnitPatterns{
        other{"{0} {1}"}
    }
    Version{"2.1.47.82"}
}

{'repo_name': 'arangodb/arangodb', 'stars': '9984', 'repo_language': 'C++', 'file_name': 'test.jam', 'mime_type': 'text/x-java', 'hash': 4072448131008995759, 'source_dataset': 'data'}


/*-
 *   BSD LICENSE
 *
 *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
 *   All rights reserved.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This sample application is a simple multi-process application which
 * demostrates sharing of queues and memory pools between processes, and
 * using those queues/pools for communication between the processes.
 *
 * Application is designed to run with two processes, a primary and a
 * secondary, and each accepts commands on the commandline, the most
 * important of which is "send", which just sends a string to the other
 * process.
 */

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <termios.h>
#include <sys/queue.h>

#include <rte_common.h>
#include <rte_memory.h>
#include <rte_memzone.h>
#include <rte_launch.h>
#include <rte_eal.h>
#include <rte_per_lcore.h>
#include <rte_lcore.h>
#include <rte_debug.h>
#include <rte_atomic.h>
#include <rte_branch_prediction.h>
#include <rte_ring.h>
#include <rte_log.h>
#include <rte_mempool.h>
#include <cmdline_rdline.h>
#include <cmdline_parse.h>
#include <cmdline_socket.h>
#include <cmdline.h>
#include "mp_commands.h"

#define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1

static const char *_MSG_POOL = "MSG_POOL";
static const char *_SEC_2_PRI = "SEC_2_PRI";
static const char *_PRI_2_SEC = "PRI_2_SEC";
const unsigned string_size = 64;

struct rte_ring *send_ring, *recv_ring;
struct rte_mempool *message_pool;
volatile int quit = 0;

static int
lcore_recv(__attribute__((unused)) void *arg)
{
	unsigned lcore_id = rte_lcore_id();

	printf("Starting core %u\n", lcore_id);
	while (!quit){
		void *msg;
		if (rte_ring_dequeue(recv_ring, &msg) < 0){
			usleep(5);
			continue;
		}
		printf("core %u: Received '%s'\n", lcore_id, (char *)msg);
		rte_mempool_put(message_pool, msg);
	}

	return 0;
}

int
main(int argc, char **argv)
{
	const unsigned flags = 0;
	const unsigned ring_size = 64;
	const unsigned pool_size = 1024;
	const unsigned pool_cache = 32;
	const unsigned priv_data_sz = 0;

	int ret;
	unsigned lcore_id;

	ret = rte_eal_init(argc, argv);
	if (ret < 0)
		rte_exit(EXIT_FAILURE, "Cannot init EAL\n");

	if (rte_eal_process_type() == RTE_PROC_PRIMARY){
		send_ring = rte_ring_create(_PRI_2_SEC, ring_size, rte_socket_id(), flags);
		recv_ring = rte_ring_create(_SEC_2_PRI, ring_size, rte_socket_id(), flags);
		message_pool = rte_mempool_create(_MSG_POOL, pool_size,
				string_size, pool_cache, priv_data_sz,
				NULL, NULL, NULL, NULL,
				rte_socket_id(), flags);
	} else {
		recv_ring = rte_ring_lookup(_PRI_2_SEC);
		send_ring = rte_ring_lookup(_SEC_2_PRI);
		message_pool = rte_mempool_lookup(_MSG_POOL);
	}
	if (send_ring == NULL)
		rte_exit(EXIT_FAILURE, "Problem getting sending ring\n");
	if (recv_ring == NULL)
		rte_exit(EXIT_FAILURE, "Problem getting receiving ring\n");
	if (message_pool == NULL)
		rte_exit(EXIT_FAILURE, "Problem getting message pool\n");

	RTE_LOG(INFO, APP, "Finished Process Init.\n");

	/* call lcore_recv() on every slave lcore */
	RTE_LCORE_FOREACH_SLAVE(lcore_id) {
		rte_eal_remote_launch(lcore_recv, NULL, lcore_id);
	}

	/* call cmd prompt on master lcore */
	struct cmdline *cl = cmdline_stdin_new(simple_mp_ctx, "\nsimple_mp > ");
	if (cl == NULL)
		rte_exit(EXIT_FAILURE, "Cannot create cmdline instance\n");
	cmdline_interact(cl);
	cmdline_stdin_exit(cl);

	rte_eal_mp_wait_lcore();
	return 0;
}

{'repo_name': 'scylladb/dpdk', 'stars': '147', 'repo_language': 'C++', 'file_name': 'doxy-api-index.md', 'mime_type': 'text/plain', 'hash': -3118916741005558592, 'source_dataset': 'data'}


/*
 * This file is part of the MicroPython project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Fabian Vogt
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

#include "py/mpstate.h"
#include "py/gc.h"

#if MICROPY_EMIT_NATIVE || (MICROPY_PY_FFI && MICROPY_FORCE_PLAT_ALLOC_EXEC)

#if defined(__OpenBSD__) || defined(__MACH__)
#define MAP_ANONYMOUS MAP_ANON
#endif

// The memory allocated here is not on the GC heap (and it may contain pointers
// that need to be GC'd) so we must somehow trace this memory.  We do it by
// keeping a linked list of all mmap'd regions, and tracing them explicitly.

typedef struct _mmap_region_t {
    void *ptr;
    size_t len;
    struct _mmap_region_t *next;
} mmap_region_t;

void mp_unix_alloc_exec(size_t min_size, void **ptr, size_t *size) {
    // size needs to be a multiple of the page size
    *size = (min_size + 0xfff) & (~0xfff);
    *ptr = mmap(NULL, *size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (*ptr == MAP_FAILED) {
        *ptr = NULL;
    }

    // add new link to the list of mmap'd regions
    mmap_region_t *rg = m_new_obj(mmap_region_t);
    rg->ptr = *ptr;
    rg->len = min_size;
    rg->next = MP_STATE_VM(mmap_region_head);
    MP_STATE_VM(mmap_region_head) = rg;
}

void mp_unix_free_exec(void *ptr, size_t size) {
    munmap(ptr, size);

    // unlink the mmap'd region from the list
    for (mmap_region_t **rg = (mmap_region_t**)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) {
        if ((*rg)->ptr == ptr) {
            mmap_region_t *next = (*rg)->next;
            m_del_obj(mmap_region_t, *rg);
            *rg = next;
            return;
        }
    }
}

void mp_unix_mark_exec(void) {
    for (mmap_region_t *rg = MP_STATE_VM(mmap_region_head); rg != NULL; rg = rg->next) {
        gc_collect_root(rg->ptr, rg->len / sizeof(mp_uint_t));
    }
}

#if MICROPY_FORCE_PLAT_ALLOC_EXEC
// Provide implementation of libffi ffi_closure_* functions in terms
// of the functions above. On a normal Linux system, this save a lot
// of code size.
void *ffi_closure_alloc(size_t size, void **code);
void ffi_closure_free(void *ptr);

void *ffi_closure_alloc(size_t size, void **code) {
    size_t dummy;
    mp_unix_alloc_exec(size, code, &dummy);
    return *code;
}

void ffi_closure_free(void *ptr) {
    (void)ptr;
    // TODO
}
#endif

#endif // MICROPY_EMIT_NATIVE || (MICROPY_PY_FFI && MICROPY_FORCE_PLAT_ALLOC_EXEC)

{'repo_name': 'micropython/micropython-esp32', 'stars': '550', 'repo_language': 'C', 'file_name': 'perf.h', 'mime_type': 'text/x-c', 'hash': 1906741512288875130, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: f89da95e9d5f4438b8a17587d0824ff4
timeCreated: 1517757928
licenseType: Pro
MonoImporter:
  externalObjects: {}
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'UnityTechnologies/AngryBots2', 'stars': '105', 'repo_language': 'C#', 'file_name': 'AudioManager.asset', 'mime_type': 'text/plain', 'hash': 4638740946802823678, 'source_dataset': 'data'}


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace ZendTest\Db\Sql;

use PHPUnit\Framework\TestCase;
use Zend\Db\Adapter\ParameterContainer;
use Zend\Db\Adapter\StatementContainer;
use Zend\Db\Sql\Combine;
use Zend\Db\Sql\Predicate\Expression;
use Zend\Db\Sql\Select;

class CombineTest extends TestCase
{
    /**
     * @var Combine
     */
    protected $combine;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->combine = new Combine;
    }

    public function testRejectsInvalidStatement()
    {
        $this->expectException('Zend\Db\Sql\Exception\InvalidArgumentException');

        $this->combine->combine('foo');
    }

    public function testGetSqlString()
    {
        $this->combine
                ->union(new Select('t1'))
                ->intersect(new Select('t2'))
                ->except(new Select('t3'))
                ->union(new Select('t4'));

        self::assertEquals(
            // @codingStandardsIgnoreStart
            '(SELECT "t1".* FROM "t1") INTERSECT (SELECT "t2".* FROM "t2") EXCEPT (SELECT "t3".* FROM "t3") UNION (SELECT "t4".* FROM "t4")',
            // @codingStandardsIgnoreEnd
            $this->combine->getSqlString()
        );
    }

    public function testGetSqlStringWithModifier()
    {
        $this->combine
                ->union(new Select('t1'))
                ->union(new Select('t2'), 'ALL');

        self::assertEquals(
            '(SELECT "t1".* FROM "t1") UNION ALL (SELECT "t2".* FROM "t2")',
            $this->combine->getSqlString()
        );
    }

    public function testGetSqlStringFromArray()
    {
        $this->combine->combine([
            [new Select('t1')],
            [new Select('t2'), Combine::COMBINE_INTERSECT, 'ALL'],
            [new Select('t3'), Combine::COMBINE_EXCEPT],
        ]);

        self::assertEquals(
            '(SELECT "t1".* FROM "t1") INTERSECT ALL (SELECT "t2".* FROM "t2") EXCEPT (SELECT "t3".* FROM "t3")',
            $this->combine->getSqlString()
        );

        $this->combine = new Combine();
        $this->combine->combine([
            new Select('t1'),
            new Select('t2'),
            new Select('t3'),
        ]);

        self::assertEquals(
            '(SELECT "t1".* FROM "t1") UNION (SELECT "t2".* FROM "t2") UNION (SELECT "t3".* FROM "t3")',
            $this->combine->getSqlString()
        );
    }

    public function testGetSqlStringEmpty()
    {
        self::assertNull($this->combine->getSqlString());
    }

    public function testPrepareStatementWithModifier()
    {
        $select1 = new Select('t1');
        $select1->where(['x1' => 10]);
        $select2 = new Select('t2');
        $select2->where(['x2' => 20]);

        $this->combine->combine([
            $select1,
            $select2,
        ]);

        $adapter = $this->getMockAdapter();

        $statement = $this->combine->prepareStatement($adapter, new StatementContainer);
        self::assertInstanceOf('Zend\Db\Adapter\StatementContainerInterface', $statement);
        self::assertEquals(
            '(SELECT "t1".* FROM "t1" WHERE "x1" = ?) UNION (SELECT "t2".* FROM "t2" WHERE "x2" = ?)',
            $statement->getSql()
        );
    }

    public function testAlignColumns()
    {
        $select1 = new Select('t1');
        $select1->columns([
            'c0' => 'c0',
            'c1' => 'c1',
        ]);
        $select2 = new Select('t2');
        $select2->columns([
            'c1' => 'c1',
            'c2' => 'c2',
        ]);

        $this->combine
                ->union([$select1, $select2])
                ->alignColumns();

        self::assertEquals(
            [
                'c0' => 'c0',
                'c1' => 'c1',
                'c2' => new Expression('NULL'),
            ],
            $select1->getRawState('columns')
        );

        self::assertEquals(
            [
                'c0' => new Expression('NULL'),
                'c1' => 'c1',
                'c2' => 'c2',
            ],
            $select2->getRawState('columns')
        );
    }

    public function testGetRawState()
    {
        $select = new Select('t1');
        $this->combine->combine($select);
        self::assertSame(
            [
                'combine' => [
                    [
                        'select'   => $select,
                        'type'     => Combine::COMBINE_UNION,
                        'modifier' => '',
                    ],
                ],
                'columns' => [
                    '0' => '*',
                ],
            ],
            $this->combine->getRawState()
        );
    }

    /**
     *
     * @return \PHPUnit_Framework_MockObject_MockObject|\Zend\Db\Adapter\Adapter
     */
    protected function getMockAdapter()
    {
        $parameterContainer = new ParameterContainer();

        $mockStatement = $this->getMockBuilder('Zend\Db\Adapter\Driver\StatementInterface')->getMock();
        $mockStatement->expects($this->any())->method('getParameterContainer')
            ->will($this->returnValue($parameterContainer));

        $setGetSqlFunction = function ($sql = null) use ($mockStatement) {
            static $sqlValue;
            if ($sql) {
                $sqlValue = $sql;
                return $mockStatement;
            }
            return $sqlValue;
        };
        $mockStatement->expects($this->any())->method('setSql')->will($this->returnCallback($setGetSqlFunction));
        $mockStatement->expects($this->any())->method('getSql')->will($this->returnCallback($setGetSqlFunction));

        $mockDriver = $this->getMockBuilder('Zend\Db\Adapter\Driver\DriverInterface')->getMock();
        $mockDriver->expects($this->any())->method('formatParameterName')->will($this->returnValue('?'));
        $mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($mockStatement));

        return $this->getMockBuilder('Zend\Db\Adapter\Adapter')
            ->setMethods()
            ->setConstructorArgs([$mockDriver])
            ->getMock();
    }
}

{'repo_name': 'directus/directus', 'stars': '7061', 'repo_language': 'PHP', 'file_name': 'browserconfig.xml', 'mime_type': 'text/xml', 'hash': -5003837089970525396, 'source_dataset': 'data'}


//
//  TransposeMatrix.swift
//  LeetCodeTests
//
//  Created by Lex on 2018/7/8.
//  Copyright © 2018 Lex Tang. All rights reserved.
//

//  Given a matrix A, return the transpose of A.
//
//  The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
//
//  Example 1:
//
//  Input: [[1,2,3],[4,5,6],[7,8,9]]
//  Output: [[1,4,7],[2,5,8],[3,6,9]]

//  Example 2:
//
//  Input: [[1,2,3],[4,5,6]]
//  Output: [[1,4],[2,5],[3,6]]

import XCTest

func transpose(_ A: [[Int]]) -> [[Int]] {
    if A.isEmpty || A[0].isEmpty {
        return A
    }

    var result = [[Int]](repeating: [Int](repeating: 0, count: A.count), count: A[0].count)

    for i in 0..<A[0].count {
        for j in 0..<A.count {
            result[i][j] = A[j][i]
        }
    }
    return result
}

class TransposeMatrixTest: XCTestCase {

    func testTransposeMatrix() {
        XCTAssertEqual(transpose([[1,2,3],[4,5,6],[7,8,9]]), [[1,4,7],[2,5,8],[3,6,9]])
        XCTAssertEqual(transpose([[1,2,3],[4,5,6]]), [[1,4],[2,5],[3,6]])
    }

}

{'repo_name': 'lexrus/LeetCode.swift', 'stars': '343', 'repo_language': 'Swift', 'file_name': '13.swift', 'mime_type': 'text/plain', 'hash': -4903820099169445507, 'source_dataset': 'data'}


{'repo_name': 'umbraco/Umbraco-CMS', 'stars': '3016', 'repo_language': 'C#', 'file_name': 'azuregalleryrelease.ps1', 'mime_type': 'text/plain', 'hash': 1757654479732889365, 'source_dataset': 'data'}


{'repo_name': 'serphacker/serposcope', 'stars': '529', 'repo_language': 'JavaScript', 'file_name': 'project.properties', 'mime_type': 'text/plain', 'hash': 5538640233068343651, 'source_dataset': 'data'}


#This is required to workaround the python import bug where relative imports don't work if the module is imported as a main module.

import os
import sys

numberOfLevelsDeepInPackageHierarchy = 2
packageFilePath = os.path.abspath(__file__)
for level in range( numberOfLevelsDeepInPackageHierarchy + 1 ):
	packageFilePath = os.path.dirname( packageFilePath )
if packageFilePath not in sys.path:
	sys.path.insert( 0, packageFilePath )

{'repo_name': 'makerbot/ReplicatorG', 'stars': '381', 'repo_language': 'Python', 'file_name': 'Mac OS X-i386.properties', 'mime_type': 'text/plain', 'hash': -3902706508492257232, 'source_dataset': 'data'}


package org.gridkit.jvmtool;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExHelper {

    private static final Pattern TOKENIZER = Pattern.compile(
            "\\\\[(]"
            + "|\\[.*\\]"
            + "|\\\\Q.*\\\\E"
            + "|.");

    public static String uncapture(String pattern) {
        StringBuilder sb = new StringBuilder();
        Matcher m = TOKENIZER.matcher(pattern);
        int n = 0;
        while(m.find(n)) {
            String tkn = m.group();
            if ("(".equals(tkn)) {
                sb.append("(?:");
            } else {
                sb.append(tkn);
            }
            n = m.end();
        }
        return sb.toString();
    }
}

{'repo_name': 'aragozin/jvm-tools', 'stars': '2728', 'repo_language': 'Java', 'file_name': 'BTPackCliCheck.java', 'mime_type': 'text/x-java', 'hash': -5002991703740889611, 'source_dataset': 'data'}