text:
package com.greencatsoft.angularjs.internal

import com.greencatsoft.angularjs.{ Service, ServiceDefinition, ServiceWrapper, injectable }

import scala.reflect.macros.{blackbox => b}
import scala.scalajs.js
import scala.scalajs.js.UndefOr

object ServiceProxy {

  def bind[A <: Service](wrapper: ServiceWrapper[A], target: A) {
    try {
      wrapper.asInstanceOf[js.Dynamic].service = target.asInstanceOf[js.Object]
    } catch {
      case _: Throwable =>
    }
  }

  def unbind[A <: Service](wrapper: js.Object): Option[ServiceWrapper[A]] = {
    val target: UndefOr[Any] = wrapper.asInstanceOf[js.Dynamic].service

    target.toOption.filter(_.isInstanceOf[Service]) map {
      _ => wrapper.asInstanceOf[ServiceWrapper[A]]
    }
  }

  def identifier[A <: Service](c: b.Context)(implicit tag: c.WeakTypeTag[A]): Option[String] =
    identifierFromType(c)(tag.tpe)

  def identifierFromType(c: b.Context)(tpe: c.universe.Type): Option[String] = {
    import c.universe._

    def find(hierarchy: List[Symbol]): Option[String] = hierarchy match {
      case head :: tail =>
        val arg = head.typeSignature.typeSymbol.annotations.map(_.tree) collectFirst {
          case a if a.tpe =:= typeOf[injectable] =>
            a.children.tail
        }

        val value = arg collectFirst {
          case List(Literal(Constant(literal: String))) => literal
        }

        value match {
          case Some(s) => Some(s)
          case _ => find(tail)
        }
      case _ =>
        None
    }

    find(tpe.baseClasses)
  }

  def variableDependencies[A <: Service](c: b.Context)(implicit tag: c.WeakTypeTag[A]): Iterable[(String, c.universe.TypeSymbol, c.universe.MethodSymbol, Seq[c.universe.Type])] = {
    import c.universe._

    //    Should check if @inject annotation is present:
    //
    //    val members = tag.tpe.members filter {
    //      _.annotations.exists(_.tree.tpe =:= typeOf[inject])
    //    } collect {
    //      case m: MethodSymbol if m.isSetter => m
    //    }

    val setters = tag.tpe.members collect {
      case m: MethodSymbol if m.isSetter => m
    }

    val deps = setters map { s =>
      val tpe = s.paramLists.head.head.typeSignature
      val typeArgs = tpe.typeArgs
      val name = identifierFromType(c)(tpe.typeSymbol.typeSignature)

      name.toSeq map {
        (_, tpe.typeSymbol.asType, s, typeArgs)
      }
    }

    deps.flatten
  }

  def constantDependencies[A <: Service](c: b.Context)(implicit tag: c.WeakTypeTag[A]): Iterable[(String, c.universe.TypeSymbol, Seq[c.universe.Type])] = {
    import c.universe._

    val methods = tag.tpe.members collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor => m
    }

    val ctor = methods getOrElse {
      c.abort(c.enclosingPosition, s"The specified type '${tag.tpe}' does not have a suitable constructor.")
    }

    val arguments = ctor.paramLists.head map { arg =>
      (arg.name.toString, arg.typeSignature.dealias.typeSymbol.asType, arg.typeSignature.typeArgs)
    }

    arguments map {
      case (n, tpe, typeArgs) =>
        val name = identifierFromType(c)(tpe.typeSignature) getOrElse n

        (name, tpe.asType, typeArgs)
    }
  }

  def definitionFromObject[A <: Service](c: b.Context)(target: c.Expr[A])(implicit tag: c.WeakTypeTag[A]): c.Expr[ServiceDefinition[A]] = {
    newInstance [A](c)(Some (target))
  }

  def definitionFromClass[A <: Service](c: b.Context)(implicit tag: c.WeakTypeTag[A]): c.Expr[ServiceDefinition[A]] = {
    newInstance [A](c)(None)
  }

  private def newInstance[A <: Service](c: b.Context)(target: Option[c.Expr[A]])(implicit tag: c.WeakTypeTag[A]): c.Expr[ServiceDefinition[A]] = {
    import c.universe._

    val (instantiation, constDeps, constDepNames) = target match {
      case Some(t) => (q"$t", Nil, Nil)
      case None =>
        val deps = constantDependencies[A](c)
        val depNames = deps collect {
          case (name, _, _) => name
        }

        val args = deps.zipWithIndex collect {
          case ((_, argType, typeArgs), index) =>
            val argument = Ident(TermName(s"a$index"))

            if (argType.typeSignature.takesTypeArgs) {
              q"$argument.asInstanceOf[$argType[..$typeArgs]]"
            } else {
              q"$argument.asInstanceOf[$argType]"
            }
        }

        val expr = Apply(Select(
          New(Ident(tag.tpe.typeSymbol)), termNames.CONSTRUCTOR), args.toList)

        (expr, deps, depNames)
    }

    val varDeps = variableDependencies[A](c)
    val varDepNames = varDeps collect {
      case (name, _, _, _) => name
    }

    val offset = constDeps.size

    val assignments = varDeps.zipWithIndex collect {
      case ((_, argType, setter, typeArgs), index) =>
        val argument = Ident(TermName(s"a${index + offset}"))

        val value = if (argType.typeSignature.takesTypeArgs) {
          q"$argument.asInstanceOf[$argType[..$typeArgs]]"
        } else {
          q"$argument.asInstanceOf[$argType]"
        }

        Apply(Select(q"target", setter.asTerm), List(value))
    }

    val depNames = constDepNames ++ varDepNames

    val proxy = q"""{
      import scala.scalajs.js
      import scala.scalajs.js.UndefOr
      import scala.scalajs.js.JSConverters.JSRichOption

      import com.greencatsoft.angularjs.{ Initializable, Service, ServiceDefinition, ServiceWrapper }
      import com.greencatsoft.angularjs.internal.ServiceProxy

      val handler: js.ThisFunction20[js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any,
        js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, js.Any, UndefOr[js.Any]] =
        (t: js.Any, a0: js.Any, a1: js.Any, a2: js.Any, a3: js.Any, a4: js.Any, a5: js.Any, a6: js.Any, a7: js.Any, a8: js.Any, a9: js.Any,
        a10: js.Any, a11: js.Any, a12: js.Any, a13: js.Any, a14: js.Any, a15: js.Any, a16: js.Any, a17: js.Any, a18: js.Any, a19: js.Any) => {

        val target: Service = { ..$instantiation }

        ServiceProxy.bind(t.asInstanceOf[ServiceWrapper[Service]], target)

        ..$assignments

        target.initialize()

        val result = target match {
          case configurable: Function0[_] => configurable()
          case _ => null
        }

        Option(result).map(_.asInstanceOf[js.Any]).orUndefined
      }

      val proxy = js.Array[js.Any](..$depNames)

      proxy.push(handler)
      proxy.asInstanceOf[ServiceDefinition[${tag.tpe}]]
    }"""

    c.Expr[ServiceDefinition[A]](proxy)
  }
}


text:
Category Configuration
======================

Contains the configuration of a category.

The configuration of a Category is only part of the
:doc:`/configuration/questionnaire`.

.. seealso::
    :class:`configuration.configuration.QuestionnaireCategory`

+-----------------+----------------------------------------------------+
| Parent element: | :doc:`/configuration/section`                      |
+-----------------+----------------------------------------------------+
| Child element:  | :doc:`/configuration/subcategory`                  |
+-----------------+----------------------------------------------------+

Format
------

The basic format of the configuration is as follows::

  {
    # The keyword of the category.
    "keyword": "CAT_KEYWORD",

    # (optional)
    "view_options": {
      # Default: "default"
      "template": "TEMPLATE_NAME",

      # Default: false
      "use_raw_data": true,

      # Default: false
      "with_metadata": true,

      # Default: {}
      "additional_data": {
        "QUESTIONGROUP": ["KEY"]
      }
    },

    # A list of subcategories.
    "subcategories": [
      {
        # ...
      }
    ]
  }

.. seealso::
    For more information on the configuration of its child elements,
    please refer to their respective documentation:

    * :doc:`/configuration/subcategory`

    Also refer to the :ref:`configuration_questionnaire_example` of a
    Questionnaire configuration.

``keyword``
^^^^^^^^^^^

The keyword of the category.

``view_options``
^^^^^^^^^^^^^^^^

(Optional). An optional object containing configuration options for the
view representation of the category.

  * ``template``: An optional template name. Must be a valid file name
    with ``.html`` ending in folder ``templates/details/category/``.

  * ``use_raw_data``: An optional boolean indicating whether to add the
    raw category data to the template or not. These values can then be
    used for example for manual rendering of the category details.
    Defaults to ``False``.

    .. seealso::
      :func:`configuration.configuration.QuestionnaireCategory.get_raw_category_data`

  * ``with_metadata``: An optional boolean indicating whether to add the
    metadata of the current Questionnaire to the template or not.
    Defaults to ``False``.

  * ``additional_data``: An optional object containing the keywords of
    questiongroups and questions from which additional data is to be
    collected.

    Example::

      {
        "qg_1": ["key_1"]
      }

``form_options``
^^^^^^^^^^^^^^^^

  * ``helptext_length`` (int): Overwrite the default length (number of words) of
    the helptext shown initially (without the "See more" button).

  * ``numbering`` (str): An optional numbering of the category.

``subcategories``
^^^^^^^^^^^^^^^^^

A list of :doc:`/configuration/subcategory`.

redpajama_set_name: RedPajamaGithub


text:
import { IUpdateCommands } from './UpdateStoredProcedure';

/**
 * Update stored procedure functions.
 * @param id The document id for the document that should be updated.
 * @param updateCommands The updateCommands.
 */
export function updateFunc<T>(id: string, updateCommands: IUpdateCommands) {
    const collection: ICollection = getContext().getCollection();
    const collectionLink: string = collection.getSelfLink();
    const response: IResponse = getContext().getResponse();

    // Validate input.
    if (!id) {
        throw new Error('The id is undefined or null.');
    }
    if (!updateCommands) {
        throw new Error('The update command is undefined or null.');
    }

    tryQueryAndUpdate();

    /**
     * Recursively queries for a document by id.
     * Calls tryUpdate(document) as soon as the query returns a document.
     */
    function tryQueryAndUpdate() {
        const query: IParameterizedQuery = { query: 'SELECT * FROM root r WHERE r.id = @id', parameters: [{ name: '@id', value: id }] };

        const isAccepted: boolean = collection.queryDocuments(
            collectionLink, query, (err: IFeedCallbackError, documents: any[]) => {
                if (err) {
                    throw err;
                }

                if (documents.length > 0) {
                    // If the document is found, update it.
                    // There is no need to check for a continuation token since we are querying for a single document.
                    tryUpdate(documents[0]);
                } else {
                    // Else a document with the given id does not exist..
                    throw new Error('Document not found.');
                }
            });

        // If we hit execution bounds - throw an exception.
        // This is highly unlikely given that this is a query by id; but is included to serve as an example for larger queries.
        if (!isAccepted) {
            throw new Error('The stored procedure timed out.');
        }
    }

    /**
     * Updates the supplied document according to the update object passed in to the sproc.
     */
    function tryUpdate(document: IDocumentMeta) {

        // DocumentDB supports optimistic concurrency control via HTTP ETag.
        const requestOptions: IReplaceOptions = { etag: document._etag };

        // Update operators.
        set(document, updateCommands);
        pop(document, updateCommands);
        push(document, updateCommands);
        unshift(document, updateCommands);

        // Update the document.
        const isAccepted: boolean = collection.replaceDocument(document._self, document, requestOptions, (err, updatedDocument, responseOptions) => {
            if (err) {
                throw err;
            }
            // If we have successfully updated the document - return it in the response body.
            response.setBody(updatedDocument);
        });

        // If we hit execution bounds - throw an exception.
        if (!isAccepted) {
            throw new Error('The stored procedure timed out.');
        }
    }

    /**
     * The $set operator sets the value of a field.
     */
    function set(document: any, update: any) {
        let fields: string[];
        let i: number;

        if (update.$set) {
            fields = Object.keys(update.$set);
            for (i = 0; i < fields.length; i++) {
                document[fields[i]] = update.$set[fields[i]];
            }
        }
    }

    /**
     * The $pop operator removes the first or last item of an array.
     * Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.
     */
    function pop(document: any, update: any) {
        let fields: string[];
        let i: number;

        if (update.$pop) {
            fields = Object.keys(update.$pop);

            for (i = 0; i < fields.length; i++) {
                if (!Array.isArray(document[fields[i]])) {
                    // Validate the document field; throw an exception if it is not an array.
                    throw new Error('Bad $pop parameter - field in document must be an array.');
                } else {
                    // Otherwise, remove the last element from the array (have 0 default to javascript's pop()).
                    document[fields[i]].pop();
                }
            }
        }
    }

    /**
     * The $push operator adds an item to an array at the end.
     * @param document The document.
     * @param update The commands.
     */
    function push(document: any, update: any) {
        let fields: string[];
        let i: number;

        if (update.$push) {
            fields = Object.keys(update.$push);

            for (i = 0; i < fields.length; i++) {
                if (!Array.isArray(document[fields[i]])) {
                    // Validate the document field; throw an exception if it is not an array.
                    throw new Error('Bad $push parameter - field in document must be an array.');
                } else {
                    // Push the element in to the array.
                    document[fields[i]].push(update.$push[fields[i]]);
                }
            }
        }
    }

    /**
     * The $unshift operator adds an item to an array at the beginning.
     * @param document The document.
     * @param update The commands.
     */
    function unshift(document: any, update: any) {
        let fields: string[];
        let i: number;

        if (update.$unshift) {
            fields = Object.keys(update.$unshift);

            for (i = 0; i < fields.length; i++) {
                if (!Array.isArray(document[fields[i]])) {
                    // Validate the document field; throw an exception if it is not an array.
                    throw new Error('Bad $unshift parameter - field in document must be an array.');
                } else {
                    // Unshift the element in to the array.
                    document[fields[i]].unshift(update.$unshift[fields[i]]);
                }
            }
        }
    }
}


text:
package org.apache.nifi.processor;

import org.apache.nifi.controller.ControllerServiceLookup;
import org.apache.nifi.logging.ProcessorLog;

/**
 *

 * The ProcessorInitializationContext provides
 * {@link nifi.processor.Processor Processor}s access to objects that may be of
 * use throughout the life of the Processor.
 *

 */
public interface ProcessorInitializationContext {

    /**
     * Returns the unique identifier for this processor
     *
     * @return
     */
    String getIdentifier();

    /**
     * Returns a {@link ProcessorLog} that is tied to this processor that can be
     * used to log events
     *
     * @return
     */
    ProcessorLog getLogger();

    /**
     * Returns the {@link ControllerServiceLookup} which can be used to obtain
     * Controller Services
     *
     * @return
     */
    ControllerServiceLookup getControllerServiceLookup();
}


text:
@interface MOBProjectionEPSG5307 : MOBProjection

@end


text:
package mcjty.rftools.blocks.storage;

import mcjty.lib.container.ContainerFactory;
import mcjty.lib.container.GenericContainer;
import mcjty.lib.container.SlotDefinition;
import mcjty.lib.container.SlotType;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;

public class RemoteStorageContainer extends GenericContainer {
    public static final String CONTAINER_INVENTORY = "container";

    public static final int SLOT_STORAGE = 0;
    public static final int SLOT_LINKER = 4;

    private RemoteStorageTileEntity remoteStorageTileEntity;

    public static final ContainerFactory factory = new ContainerFactory() {
        @Override
        protected void setup() {
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 0, 43, 9, 1, 18, 1, 18);
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 1, 43, 36, 1, 18, 1, 18);
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 2, 120, 9, 1, 18, 1, 18);
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 3, 120, 36, 1, 18, 1, 18);

            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 4, 76, 9, 1, 18, 1, 18);
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 5, 76, 36, 1, 18, 1, 18);
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 6, 153, 9, 1, 18, 1, 18);
            addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, new ItemStack(ModularStorageSetup.storageModuleItem)), CONTAINER_INVENTORY, 7, 153, 36, 1, 18, 1, 18);

            layoutPlayerInventorySlots(10, 70);
        }
    };

    public RemoteStorageContainer(EntityPlayer player, RemoteStorageTileEntity containerInventory) {
        super(factory);
        remoteStorageTileEntity = containerInventory;
        addInventory(CONTAINER_INVENTORY, containerInventory);
        addInventory(ContainerFactory.CONTAINER_PLAYER, player.inventory);
        generateSlots();
    }

    @Override
    public ItemStack slotClick(int index, int button, int mode, EntityPlayer player) {
        if (index >= 0 && index < SLOT_LINKER && !player.worldObj.isRemote) {
            remoteStorageTileEntity.copyToModule(index);
        }
        return super.slotClick(index, button, mode, player);
    }
}


text:
module PermissionHelper

  def get_permission(group)
    @permission = (group.user_group_permissions & @current_user.user_group_permissions)[0] #TODO: update this to get all permissions instead of the first
  end

  def authorize_user_for_group
    @permission = (@group.user_group_permissions & @current_user.user_group_permissions)[0] #TODO: update this to get all permissions instead of the first
    redirect_to('/', notice: "User doesn't have permission to access the group") unless @permission
  end

  def user_can_post_tasks?
    redirect_to('/', notice: "You can't don't have permission to create a new task") unless @permission.user_can_post_tasks
  end

  def user_can_put_tasks?
    redirect_to('/', notice: "You can't don't have permission to edit a task") unless @permission.user_can_put_tasks
  end

  def user_is_admin?
    redirect_to('/', notice: "You don't have permission to administer the group") unless @permission.user_can_admin_group
  end

  def user_is_group_admin(group)
    get_permission(group)
    if @permission == nil
      return false
    end
    @permission.user_can_admin_group
  end

  def create_default_permission
    @user_group_permission = @group.user_group_permissions.build
    @user_group_permission.user_id = @current_user.id
    @user_group_permission.user_can_put_tasks = true
    @user_group_permission.user_can_post_tasks = true
    @user_group_permission.user_can_admin_group = true
    @user_group_permission.save
  end

end


text:
module Quickbooks
  module Model
    class BillLineItem < BaseModel

      #== Constants
      ACCOUNT_BASED_EXPENSE_LINE_DETAIL = 'AccountBasedExpenseLineDetail'

      xml_accessor :id, :from => 'Id', :as => Integer
      xml_accessor :line_num, :from => 'LineNum', :as => Integer
      xml_accessor :description, :from => 'Description'
      xml_accessor :amount, :from => 'Amount', :as => BigDecimal, :to_xml => to_xml_big_decimal
      xml_accessor :detail_type, :from => 'DetailType'

      #== Various detail types
      xml_accessor :account_based_expense_line_detail, :from => 'AccountBasedExpenseLineDetail', :as => AccountBasedExpenseLineDetail

      def account_based_expense_item?
        detail_type.to_s == ACCOUNT_BASED_EXPENSE_LINE_DETAIL
      end

    end
  end
end


text:
import _curry2 from "../privates/_curry2";
import takeFrom from "./takeFrom";

/**
 * A curried version of {@link module:lamb.takeFrom|takeFrom} that expects the number of elements
 * to retrieve to build a function waiting for the list to take the elements from.

 * See the note and examples for {@link module:lamb.takeFrom|takeFrom} about passing a
 * negative n.
 * @example
 * const take2 = _.take(2);
 *
 * take2([1, 2, 3, 4, 5]) // => [1, 2]
 *
 * @memberof module:lamb
 * @category Array
 * @function
 * @see {@link module:lamb.takeFrom|takeFrom}
 * @see {@link module:lamb.dropFrom|dropFrom}, {@link module:lamb.drop|drop}
 * @see {@link module:lamb.takeWhile|takeWhile}, {@link module:lamb.dropWhile|dropWhile}
 * @see {@link module:lamb.takeLastWhile|takeLastWhile}, {@link module:lamb.dropLastWhile|dropLastWhile}
 * @since 0.5.0
 * @param {Number} n
 * @returns {Function}
 */
var take = _curry2(takeFrom, true);

export default take;


text:
module DataModel
  class InteractionClaim < ::ActiveRecord::Base
    include Genome::Extensions::UUIDPrimaryKey

    has_many :interaction_claim_attributes, inverse_of: :interaction_claim
    has_many :interaction_claim_links, inverse_of: :interaction_claim
    belongs_to :gene_claim, inverse_of: :interaction_claims
    belongs_to :drug_claim, inverse_of: :interaction_claims
    belongs_to :source, inverse_of: :interaction_claims, counter_cache: true
    has_and_belongs_to_many :interaction_claim_types, :join_table => 'interaction_claim_types_interaction_claims'
    belongs_to :interaction
    has_and_belongs_to_many :publications

    def self.for_show
      eager_load(:interaction_claim_types, :interaction_claim_attributes, :source, :publications, :interaction_claim_links, :drug_claim, gene_claim: [:gene], interaction: [:gene, :drug])
    end

    def self.for_tsv
      includes(:source, :interaction_claim_types, :publications, drug_claim: [:drug], gene_claim: [:gene])
    end

    def drug
      self.drug_claim.drug
    end

    def gene
      self.gene_claim.gene
    end
  end
end


text:
cask 'teamdrive' do
  version '4.6.8.2441'
  sha256 'ea699840e05e47dda4b4d522978bf49374bfada0072e6185e59b3780cc3d1ecc'

  # s3-eu-west-1.amazonaws.com/s3download.teamdrive.net was verified as official when first introduced to the cask
  url "https://s3-eu-west-1.amazonaws.com/s3download.teamdrive.net/#{version.major_minor}.#{version.split('.').last}/TMDR/mac-10.14.6/Install-TeamDrive-#{version}_TMDR.dmg"
  appcast 'https://teamdrive.com/en/downloads/'
  name 'TeamDrive'
  homepage 'https://www.teamdrive.com/'

  installer script: {
                      executable: "Install-TeamDrive-#{version}_TMDR.app/Contents/MacOS/osx-x86_64",
                      args:       ['--unattendedmodeui', 'none', '--mode', 'unattended'],
                    }

  uninstall script: {
                      executable: '/Applications/TeamDrive/uninstall.app/Contents/MacOS/osx-x86_64',
                      args:       ['--mode', 'unattended'],
                    },
            signal: [
                      ['QUIT', 'com.teamdrive.teamdrive3'],
                      ['KILL', 'com.teamdrive.teamdrive3'],
                      ['QUIT', 'com.teamdrive.teamdrive3.FinderExt'],
                      ['KILL', 'com.teamdrive.teamdrive3.FinderExt'],
                      ['QUIT', 'com.teamdrive.teamdrive3.MenuExt'],
                      ['KILL', 'com.teamdrive.teamdrive3.MenuExt'],
                    ]
end


text:
/**
 * @module app
 * @copywrite 2013, "Magalhas" José Magalhães
 * @license MIT <http://opensource.org/licenses/MIT>
 */
var App = {};
define(["require", "i18n!nls/lang", "collection", "config", "model", "router", "view"],
    function (require, i18n, Collection, Config, Model, Router, View) {
  "use strict";
  /**
   * @namespace module:app~App
   * @mixes external:Backbone.Events
   */
  _.extend(App, Backbone.Events);
  App.Collection = Collection;
  App.Config = Config;
  App.Model = Model;
  App.Router = Router;
  App.View = View;
  /**
   * Tries to automatically detect the URL of the application and store it in
   * App.Config.URL.ROOT.
   * @memberof module:app~App
   * @private
   * @returns {module:app~App}
   */
  var detectUrls = function () {
    var path = window.location.pathname.split('/'),
      apiUrl,
      rootUrl;

    // If URL object is undefined
    !App.Config.URL && (App.Config.URL = {});

    if (!App.Config.URL.Root) {
      // Automatic detect the URL
      _.each(path, function (pathEntry, index) {
        if (index < path.length - 1) {
          rootUrl += pathEntry + '/';
        }
      });
      App.Config.URL.ROOT = rootUrl;
    }
    return App;
  };
  /**
   * Starts the application.
   * @returns {module:app~App}
   */
  App.initialize = function () {
    var self = this;
    detectUrls();
    require(["routers/main"], function (MainRouter) {
      // Instance the main router
      self.router = new MainRouter();
      // Start the application routing
      Backbone.history.start({pushState: false, root: App.Config.URL.ROOT});
    });
    return App;
  };
  /**
   * Translates a string.
   * @param {String} key The key to be translated.
   * @returns {String} The translated key or the key itself if no translation found.
   */
  App.i18n = function (key) {
    return i18n[key] || key;
  };
  /**
   * Parses a string such as "example/{1}/{2}", replacing {1} and {2}, etc, by the
   * variable arguments passed into the method.
   * @param {String} string The string to be parsed.
   * @param {...String} [arguments] to replace in the original string.
   * @returns {String} The parsed string.
   */
  App.parseString = function (string) {
    var i, length = arguments.length;
    for (i = 1; i < length; i += 1) {
      string = string.replace('{' + i + '}', arguments[i]);
    }
    return string;
  };
  return App;
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 21(8): 117 (1882)

#### Original name
Diatrypella placenta Rehm

### Remarks
null


text:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){
    ui->setupUi(this);
    connect(ui->cmdFetch,SIGNAL(clicked()),this,SLOT(fetch()));
    connect(ui->actionExit, SIGNAL(triggered()),this,SLOT(close()));
    connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(showAboutBox()));
    ui->statusBar->showMessage("Ready");
}

MainWindow::~MainWindow(){
    delete ui;
}

void MainWindow::fetch(){
    ui->cmdFetch->setText("Fetching...");
    ui->statusBar->showMessage("Downloading image urls...");
    QList<QString> list;
    list.append(QString("http://9gag.com/"));
    list.append(QString("http://www.lolhappens.com/"));
    list.append(QString("http://www.memecenter.com/"));
    list.append(QString("http://uberhumor.com/"));
    list.append(QString("http://porkystuff.com/"));
    m_pImgCtrl = new FileDownloader(QUrl(list[rand()%5]), this);
    connect(m_pImgCtrl, SIGNAL(downloaded()), SLOT(getImageUrl()));
    ui->cmdFetch->setEnabled(false);
}

void MainWindow::getImageUrl(){
    QString data = m_pImgCtrl->downloadedData();
    QRegExp rx("\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>");

    QStringList list;
    int pos = 0;
    while ((pos = rx.indexIn(data, pos)) != -1){
        list << rx.cap(1);
        pos += rx.matchedLength();
    }
    int randomNo = rand() % list.length();
    ui->statusBar->showMessage("Fetching Image");
    QUrl imageUrl(list[randomNo]);
    imageDownloader = new FileDownloader(imageUrl,this);
    connect(imageDownloader,SIGNAL(downloaded()), SLOT(loadImage()));
}

void MainWindow::loadImage(){
    QImage image;
    image = QImage::fromData(imageDownloader->downloadedData());
    ui->cmdFetch->setText("Fetch");
    ui->lblView->setPixmap(QPixmap::fromImage(image));
    ui->cmdFetch->setEnabled(true);
    ui->statusBar->showMessage("Ready");
}

void MainWindow::showAboutBox(){
    ab = new aboutBox;
    ab->show();
    ui->statusBar->showMessage("casc");

}


text:
<?php

namespace PHPExiftool\Driver\Tag\Microsoft;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class OtherAddress extends AbstractTag
{

    protected $Id = '{508161FA-313B-43D5-83A1-C1ACCF68622C} 100';

    protected $Name = 'OtherAddress';

    protected $FullName = 'Microsoft::Xtra';

    protected $GroupName = 'Microsoft';

    protected $g0 = 'QuickTime';

    protected $g1 = 'Microsoft';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Other Address';
}


text:
package org.apache.openwhisk.core.entity

import pureconfig._

import scala.concurrent.duration._
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import spray.json.JsNumber
import spray.json.JsValue
import spray.json.RootJsonFormat
import spray.json.deserializationError
import org.apache.openwhisk.core.ConfigKeys

/**
 * TimeLimit encapsulates a duration for an action. The duration must be within a
 * permissible range (currently [100 msecs, 5 minutes]).
 *
 * It is a value type (hence == is .equals, immutable and cannot be assigned null).
 * The constructor is private so that argument requirements are checked and normalized
 * before creating a new instance.
 *
 * @param duration the duration for the action, required not null
 */
protected[entity] class TimeLimit private (val duration: FiniteDuration) extends AnyVal {
  protected[core] def millis = duration.toMillis.toInt
  override def toString = duration.toString
}

case class TimeLimitConfig(max: FiniteDuration, min: FiniteDuration, std: FiniteDuration)

protected[core] object TimeLimit extends ArgNormalizer[TimeLimit] {
  val config = loadConfigOrThrow[TimeLimitConfig](ConfigKeys.timeLimit)

  protected[core] val MIN_DURATION: FiniteDuration = config.min
  protected[core] val MAX_DURATION: FiniteDuration = config.max
  protected[core] val STD_DURATION: FiniteDuration = config.std

  /** Gets TimeLimit with default duration */
  protected[core] def apply(): TimeLimit = TimeLimit(STD_DURATION)

  /**
   * Creates TimeLimit for duration, iff duration is within permissible range.
   *
   * @param duration the duration in milliseconds, must be within permissible range
   * @return TimeLimit with duration set
   * @throws IllegalArgumentException if duration does not conform to requirements
   */
  @throws[IllegalArgumentException]
  protected[core] def apply(duration: FiniteDuration): TimeLimit = {
    require(duration != null, s"duration undefined")
    require(
      duration >= MIN_DURATION,
      s"duration ${duration.toMillis} milliseconds below allowed threshold of ${MIN_DURATION.toMillis} milliseconds")
    require(
      duration <= MAX_DURATION,
      s"duration ${duration.toMillis} milliseconds exceeds allowed threshold of ${MAX_DURATION.toMillis} milliseconds")
    new TimeLimit(duration)
  }

  override protected[core] implicit val serdes = new RootJsonFormat[TimeLimit] {
    def write(t: TimeLimit) = JsNumber(t.millis)

    def read(value: JsValue) =
      Try {
        val JsNumber(ms) = value
        require(ms.isWhole, "time limit must be whole number")
        TimeLimit(Duration(ms.intValue, MILLISECONDS))
      } match {
        case Success(limit)                       => limit
        case Failure(e: IllegalArgumentException) => deserializationError(e.getMessage, e)
        case Failure(e: Throwable)                => deserializationError("time limit malformed", e)
      }
  }
}


text:
#include "comment_stripper_winpsdk.h"
#include <sstream>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

string strip_comment(const string& comment)
{
    string s(comment);

    // replace "//" with ""
    boost::erase_all(s, "//");

    // trim whitespace at either end (incl. newlines)
    boost::trim(s);

    // Where a comment spans multiple lines and one of those lines is empty,
    // without even a comment marker, then reduce the comment string to just
    // the text after the last blank line.
    {
        auto iLastBlankLine = boost::find_last(s, "\n\n");

        if (iLastBlankLine.end() != s.end())
        {
            string sLastComment(iLastBlankLine.end(), s.end());
            if (!sLastComment.empty())
                s.swap(sLastComment);
        }
    }

    // Find the MessageText: bit and grab the text after it.
    // If we can't find MessageText:, don't bother stripping.
    {
        auto iMsgTextMarker = boost::ifind_first(s, "messagetext:");

        if (iMsgTextMarker.end() != s.end())
        {
            string sMsgText(iMsgTextMarker.end(), s.end());
            if (!sMsgText.empty())
                s.swap(sMsgText);
        }
    }

    // trim whitespace at either end (incl. newlines)
    boost::trim(s);

    return s;
}

strip_comment_winpsdk::strip_comment_winpsdk(const string& comment) :
    m_stripped_comment(strip_comment(comment))
{ }


text:
"""
===================================
Demo of DBSCAN clustering algorithm
===================================

Finds core samples of high density and expands clusters from them.

"""
print(__doc__)

import numpy as np

from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler

##############################################################################
# Generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,
                            random_state=0)

X = StandardScaler().fit_transform(X)

##############################################################################
# Compute DBSCAN
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
core_samples = db.core_sample_indices_
labels = db.labels_

# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)

print('Estimated number of clusters: %d' % n_clusters_)
print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels))
print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels))
print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels))
print("Adjusted Rand Index: %0.3f"
      % metrics.adjusted_rand_score(labels_true, labels))
print("Adjusted Mutual Information: %0.3f"
      % metrics.adjusted_mutual_info_score(labels_true, labels))
print("Silhouette Coefficient: %0.3f"
      % metrics.silhouette_score(X, labels))

##############################################################################
# Plot result
import pylab as pl

# Black removed and is used for noise instead.
unique_labels = set(labels)
colors = pl.cm.Spectral(np.linspace(0, 1, len(unique_labels)))
for k, col in zip(unique_labels, colors):
    if k == -1:
        # Black used for noise.
        col = 'k'
        markersize = 6
    class_members = [index[0] for index in np.argwhere(labels == k)]
    cluster_core_samples = [index for index in core_samples
                            if labels[index] == k]
    for index in class_members:
        x = X[index]
        if index in core_samples and k != -1:
            markersize = 14
        else:
            markersize = 6
        pl.plot(x[0], x[1], 'o', markerfacecolor=col,
                markeredgecolor='k', markersize=markersize)

pl.title('Estimated number of clusters: %d' % n_clusters_)
pl.show()


text:
using System;
using System.Globalization;
using System.IO;
using System.Windows.Forms;

namespace SundayDirectory
{
    public partial class Form1 : Form
    {
        private string path;
        private string pathHari;
        private decimal tahun;
        public Form1()
        {
            InitializeComponent();
            TahunNumericUpDown1.Value = DateTime.Now.Year;
        }

        private void SelectDirButton_Click(object sender, EventArgs e)
        {
            // Show the dialog and get result.
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                path = folderBrowserDialog1.SelectedPath;
            }
        }

        private void RenameButton_Click(object sender, EventArgs e)
        {
            try
            {
                tahun = TahunNumericUpDown1.Value;
                DateTime awal = new DateTime((int)tahun,1,1);
                DateTime akhir = new DateTime((int)tahun, 12, 31);
                int i = 1;
                int tempMonth = awal.Month;
                bool cek = true;
                while (awal<=akhir)
                {
                    if (cek)
                    {
                        string Numtemp = i.ToString("00");
                        string bulan = awal.ToString("MMMM", CultureInfo.CreateSpecificCulture("id"));
                        bulan = path + "\\" + Numtemp + " - " + bulan;
                        Directory.CreateDirectory(bulan);
                        pathHari = bulan;
                        i++;
                        cek = false;
                        CreateFolderIfSunday(awal);
                    }
                    awal = awal.AddDays(1);

                    CreateFolderIfSunday(awal);

                    if (awal.Month > tempMonth)
                    {
                        tempMonth++;
                        cek = true;
                    }

                }
                MessageBox.Show("Selesai Membuat !");

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void CreateFolderIfSunday(DateTime awal)
        {
            if (awal.DayOfWeek == DayOfWeek.Sunday)
            {
                Directory.CreateDirectory(pathHari + "\\" + awal.Day.ToString("00") + " " + awal.ToString("MMMM", CultureInfo.CreateSpecificCulture("id")));
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AboutForm a = new AboutForm();
            a.ShowDialog();
        }
    }
}


text:
extern "C" {
struct _OVERLAPPED;

#if !defined( BOOST_NO_ANSI_APIS )
BOOST_SYMBOL_IMPORT boost::detail::winapi::HANDLE_ WINAPI
CreateFileA(
    boost::detail::winapi::LPCSTR_ lpFileName,
    boost::detail::winapi::DWORD_ dwDesiredAccess,
    boost::detail::winapi::DWORD_ dwShareMode,
    ::_SECURITY_ATTRIBUTES* lpSecurityAttributes,
    boost::detail::winapi::DWORD_ dwCreationDisposition,
    boost::detail::winapi::DWORD_ dwFlagsAndAttributes,
    boost::detail::winapi::HANDLE_ hTemplateFile);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
DeleteFileA(boost::detail::winapi::LPCSTR_ lpFileName);

struct _WIN32_FIND_DATAA;
BOOST_SYMBOL_IMPORT boost::detail::winapi::HANDLE_ WINAPI
FindFirstFileA(boost::detail::winapi::LPCSTR_ lpFileName, ::_WIN32_FIND_DATAA* lpFindFileData);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
FindNextFileA(boost::detail::winapi::HANDLE_ hFindFile, ::_WIN32_FIND_DATAA* lpFindFileData);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
MoveFileExA(
    boost::detail::winapi::LPCSTR_ lpExistingFileName,
    boost::detail::winapi::LPCSTR_ lpNewFileName,
    boost::detail::winapi::DWORD_ dwFlags);
#endif

BOOST_SYMBOL_IMPORT boost::detail::winapi::HANDLE_ WINAPI
CreateFileW(
    boost::detail::winapi::LPCWSTR_ lpFileName,
    boost::detail::winapi::DWORD_ dwDesiredAccess,
    boost::detail::winapi::DWORD_ dwShareMode,
    ::_SECURITY_ATTRIBUTES* lpSecurityAttributes,
    boost::detail::winapi::DWORD_ dwCreationDisposition,
    boost::detail::winapi::DWORD_ dwFlagsAndAttributes,
    boost::detail::winapi::HANDLE_ hTemplateFile);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
DeleteFileW(boost::detail::winapi::LPCWSTR_ lpFileName);

struct _WIN32_FIND_DATAW;
BOOST_SYMBOL_IMPORT boost::detail::winapi::HANDLE_ WINAPI
FindFirstFileW(boost::detail::winapi::LPCWSTR_ lpFileName, ::_WIN32_FIND_DATAW* lpFindFileData);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
FindNextFileW(boost::detail::winapi::HANDLE_ hFindFile, ::_WIN32_FIND_DATAW* lpFindFileData);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
MoveFileExW(
    boost::detail::winapi::LPCWSTR_ lpExistingFileName,
    boost::detail::winapi::LPCWSTR_ lpNewFileName,
    boost::detail::winapi::DWORD_ dwFlags);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
FindClose(boost::detail::winapi::HANDLE_ hFindFile);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
GetFileSizeEx(boost::detail::winapi::HANDLE_ hFile, ::_LARGE_INTEGER* lpFileSize);

#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WINXP

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
SetFileValidData(boost::detail::winapi::HANDLE_ hFile, boost::detail::winapi::LONGLONG_ ValidDataLength);

#endif

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
SetEndOfFile(boost::detail::winapi::HANDLE_ hFile);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
LockFile(
    boost::detail::winapi::HANDLE_ hFile,
    boost::detail::winapi::DWORD_ dwFileOffsetLow,
    boost::detail::winapi::DWORD_ dwFileOffsetHigh,
    boost::detail::winapi::DWORD_ nNumberOfBytesToLockLow,
    boost::detail::winapi::DWORD_ nNumberOfBytesToLockHigh);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
UnlockFile(
    boost::detail::winapi::HANDLE_ hFile,
    boost::detail::winapi::DWORD_ dwFileOffsetLow,
    boost::detail::winapi::DWORD_ dwFileOffsetHigh,
    boost::detail::winapi::DWORD_ nNumberOfBytesToUnlockLow,
    boost::detail::winapi::DWORD_ nNumberOfBytesToUnlockHigh);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
LockFileEx(
    boost::detail::winapi::HANDLE_ hFile,
    boost::detail::winapi::DWORD_ dwFlags,
    boost::detail::winapi::DWORD_ dwReserved,
    boost::detail::winapi::DWORD_ nNumberOfBytesToLockLow,
    boost::detail::winapi::DWORD_ nNumberOfBytesToLockHigh,
    ::_OVERLAPPED* lpOverlapped);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
UnlockFileEx(
    boost::detail::winapi::HANDLE_ hFile,
    boost::detail::winapi::DWORD_ dwReserved,
    boost::detail::winapi::DWORD_ nNumberOfBytesToUnlockLow,
    boost::detail::winapi::DWORD_ nNumberOfBytesToUnlockHigh,
    ::_OVERLAPPED* lpOverlapped);

BOOST_SYMBOL_IMPORT boost::detail::winapi::BOOL_ WINAPI
WriteFile(
    boost::detail::winapi::HANDLE_ hFile,
    boost::detail::winapi::LPCVOID_ lpBuffer,
    boost::detail::winapi::DWORD_ nNumberOfBytesToWrite,
    boost::detail::winapi::LPDWORD_ lpNumberOfBytesWritten,
    ::_OVERLAPPED* lpOverlapped);
}
#endif

namespace boost {
namespace detail {
namespace winapi {

#if !defined( BOOST_NO_ANSI_APIS )
using ::DeleteFileA;
using ::MoveFileExA;
#endif

using ::DeleteFileW;
using ::MoveFileExW;

using ::FindClose;

#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WINXP

using ::SetFileValidData;

#endif

using ::SetEndOfFile;
using ::LockFile;
using ::UnlockFile;

typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _OVERLAPPED {
    ULONG_PTR_ Internal;
    ULONG_PTR_ InternalHigh;
    union {
        struct {
            DWORD_ Offset;
            DWORD_ OffsetHigh;
        };
        PVOID_  Pointer;
    };
    HANDLE_    hEvent;
} OVERLAPPED_, *LPOVERLAPPED_;

#if !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE HANDLE_ CreateFileA(
    LPCSTR_ lpFileName,
    DWORD_ dwDesiredAccess,
    DWORD_ dwShareMode,
    SECURITY_ATTRIBUTES_* lpSecurityAttributes,
    DWORD_ dwCreationDisposition,
    DWORD_ dwFlagsAndAttributes,
    HANDLE_ hTemplateFile)
{
    return ::CreateFileA(
        lpFileName,
        dwDesiredAccess,
        dwShareMode,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes),
        dwCreationDisposition,
        dwFlagsAndAttributes,
        hTemplateFile);
}

typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _WIN32_FIND_DATAA {
    DWORD_ dwFileAttributes;
    FILETIME_ ftCreationTime;
    FILETIME_ ftLastAccessTime;
    FILETIME_ ftLastWriteTime;
    DWORD_ nFileSizeHigh;
    DWORD_ nFileSizeLow;
    DWORD_ dwReserved0;
    DWORD_ dwReserved1;
    CHAR_   cFileName[ 260 ]; // MAX_PATH
    CHAR_   cAlternateFileName[ 14 ];
#ifdef _MAC
    DWORD_ dwFileType;
    DWORD_ dwCreatorType;
    WORD_  wFinderFlags;
#endif
} WIN32_FIND_DATAA_, *PWIN32_FIND_DATAA_, *LPWIN32_FIND_DATAA_;

BOOST_FORCEINLINE HANDLE_ FindFirstFileA(LPCSTR_ lpFileName, WIN32_FIND_DATAA_* lpFindFileData)
{
    return ::FindFirstFileA(lpFileName, reinterpret_cast< ::_WIN32_FIND_DATAA* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ FindNextFileA(HANDLE_ hFindFile, WIN32_FIND_DATAA_* lpFindFileData)
{
    return ::FindNextFileA(hFindFile, reinterpret_cast< ::_WIN32_FIND_DATAA* >(lpFindFileData));
}
#endif

BOOST_FORCEINLINE HANDLE_ CreateFileW(
    LPCWSTR_ lpFileName,
    DWORD_ dwDesiredAccess,
    DWORD_ dwShareMode,
    SECURITY_ATTRIBUTES_* lpSecurityAttributes,
    DWORD_ dwCreationDisposition,
    DWORD_ dwFlagsAndAttributes,
    HANDLE_ hTemplateFile)
{
    return ::CreateFileW(
        lpFileName,
        dwDesiredAccess,
        dwShareMode,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes),
        dwCreationDisposition,
        dwFlagsAndAttributes,
        hTemplateFile);
}

typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _WIN32_FIND_DATAW {
    DWORD_ dwFileAttributes;
    FILETIME_ ftCreationTime;
    FILETIME_ ftLastAccessTime;
    FILETIME_ ftLastWriteTime;
    DWORD_ nFileSizeHigh;
    DWORD_ nFileSizeLow;
    DWORD_ dwReserved0;
    DWORD_ dwReserved1;
    WCHAR_  cFileName[ 260 ]; // MAX_PATH
    WCHAR_  cAlternateFileName[ 14 ];
#ifdef _MAC
    DWORD_ dwFileType;
    DWORD_ dwCreatorType;
    WORD_  wFinderFlags;
#endif
} WIN32_FIND_DATAW_, *PWIN32_FIND_DATAW_, *LPWIN32_FIND_DATAW_;

BOOST_FORCEINLINE HANDLE_ FindFirstFileW(LPCWSTR_ lpFileName, WIN32_FIND_DATAW_* lpFindFileData)
{
    return ::FindFirstFileW(lpFileName, reinterpret_cast< ::_WIN32_FIND_DATAW* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ FindNextFileW(HANDLE_ hFindFile, WIN32_FIND_DATAW_* lpFindFileData)
{
    return ::FindNextFileW(hFindFile, reinterpret_cast< ::_WIN32_FIND_DATAW* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ GetFileSizeEx(HANDLE_ hFile, LARGE_INTEGER_* lpFileSize)
{
    return ::GetFileSizeEx(hFile, reinterpret_cast< ::_LARGE_INTEGER* >(lpFileSize));
}

BOOST_FORCEINLINE BOOL_ LockFileEx(
    HANDLE_ hFile,
    DWORD_ dwFlags,
    DWORD_ dwReserved,
    DWORD_ nNumberOfBytesToLockLow,
    DWORD_ nNumberOfBytesToLockHigh,
    OVERLAPPED_* lpOverlapped)
{
    return ::LockFileEx(hFile, dwFlags, dwReserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh, reinterpret_cast< ::_OVERLAPPED* >(lpOverlapped));
}

BOOST_FORCEINLINE BOOL_ UnlockFileEx(
    HANDLE_ hFile,
    DWORD_ dwReserved,
    DWORD_ nNumberOfBytesToUnlockLow,
    DWORD_ nNumberOfBytesToUnlockHigh,
    OVERLAPPED_* lpOverlapped)
{
    return ::UnlockFileEx(hFile, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh, reinterpret_cast< ::_OVERLAPPED* >(lpOverlapped));
}

BOOST_FORCEINLINE BOOL_ WriteFile(
    HANDLE_ hFile,
    LPCVOID_ lpBuffer,
    DWORD_ nNumberOfBytesToWrite,
    LPDWORD_ lpNumberOfBytesWritten,
    OVERLAPPED_* lpOverlapped)
{
    return ::WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, reinterpret_cast< ::_OVERLAPPED* >(lpOverlapped));
};

#if !defined( BOOST_NO_ANSI_APIS )
BOOST_FORCEINLINE HANDLE_ create_file(
    LPCSTR_ lpFileName,
    DWORD_ dwDesiredAccess,
    DWORD_ dwShareMode,
    SECURITY_ATTRIBUTES_* lpSecurityAttributes,
    DWORD_ dwCreationDisposition,
    DWORD_ dwFlagsAndAttributes,
    HANDLE_ hTemplateFile)
{
    return ::CreateFileA(
        lpFileName,
        dwDesiredAccess,
        dwShareMode,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes),
        dwCreationDisposition,
        dwFlagsAndAttributes,
        hTemplateFile);
}

BOOST_FORCEINLINE BOOL_ delete_file(LPCSTR_ lpFileName)
{
    return ::DeleteFileA(lpFileName);
}

BOOST_FORCEINLINE HANDLE_ find_first_file(LPCSTR_ lpFileName, WIN32_FIND_DATAA_* lpFindFileData)
{
    return ::FindFirstFileA(lpFileName, reinterpret_cast< ::_WIN32_FIND_DATAA* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ find_next_file(HANDLE_ hFindFile, WIN32_FIND_DATAA_* lpFindFileData)
{
    return ::FindNextFileA(hFindFile, reinterpret_cast< ::_WIN32_FIND_DATAA* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ move_file(LPCSTR_ lpExistingFileName, LPCSTR_ lpNewFileName, DWORD_ dwFlags)
{
    return ::MoveFileExA(lpExistingFileName, lpNewFileName, dwFlags);
}
#endif

BOOST_FORCEINLINE HANDLE_ create_file(
    LPCWSTR_ lpFileName,
    DWORD_ dwDesiredAccess,
    DWORD_ dwShareMode,
    SECURITY_ATTRIBUTES_* lpSecurityAttributes,
    DWORD_ dwCreationDisposition,
    DWORD_ dwFlagsAndAttributes,
    HANDLE_ hTemplateFile)
{
    return ::CreateFileW(
        lpFileName,
        dwDesiredAccess,
        dwShareMode,
        reinterpret_cast< ::_SECURITY_ATTRIBUTES* >(lpSecurityAttributes),
        dwCreationDisposition,
        dwFlagsAndAttributes,
        hTemplateFile);
}

BOOST_FORCEINLINE BOOL_ delete_file(LPCWSTR_ lpFileName)
{
    return ::DeleteFileW(lpFileName);
}

BOOST_FORCEINLINE HANDLE_ find_first_file(LPCWSTR_ lpFileName, WIN32_FIND_DATAW_* lpFindFileData)
{
    return ::FindFirstFileW(lpFileName, reinterpret_cast< ::_WIN32_FIND_DATAW* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ find_next_file(HANDLE_ hFindFile, WIN32_FIND_DATAW_* lpFindFileData)
{
    return ::FindNextFileW(hFindFile, reinterpret_cast< ::_WIN32_FIND_DATAW* >(lpFindFileData));
}

BOOST_FORCEINLINE BOOL_ move_file(LPCWSTR_ lpExistingFileName, LPCWSTR_ lpNewFileName, DWORD_ dwFlags)
{
    return ::MoveFileExW(lpExistingFileName, lpNewFileName, dwFlags);
}

}
}
}

#endif // BOOST_DETAIL_WINAPI_FILE_MANAGEMENT_HPP


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright (c) 2015 IRCCloud, Ltd.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical">

    <TextView
        android:id="@+id/prompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="?messageTextColor"
        />

    <com.irccloud.android.IRCEditText
        android:id="@+id/textInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="?editTextTheme"
        android:inputType="text"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:ems="10">

        <requestFocus />
    </com.irccloud.android.IRCEditText>

</LinearLayout>


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

<title>Uses of Package org.apache.cassandra.streaming.messages (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.apache.cassandra.streaming.messages

Packages that use org.apache.cassandra.streaming.messages

Package
Description

org.apache.cassandra.streaming

org.apache.cassandra.streaming.compress

org.apache.cassandra.streaming.messages

Classes in org.apache.cassandra.streaming.messages used by org.apache.cassandra.streaming

Class and Description

FileMessageHeader

StreamingFileHeader is appended before sending actual data to describe what it's sending.

IncomingFileMessage

IncomingFileMessage is used to receive the part(or whole) of a SSTable data file.

OutgoingFileMessage

OutgoingFileMessage is used to transfer the part(or whole) of a SSTable data file.

StreamMessage

StreamMessage is an abstract base class that every messages in streaming protocol inherit.

Classes in org.apache.cassandra.streaming.messages used by org.apache.cassandra.streaming.compress

Class and Description

FileMessageHeader

StreamingFileHeader is appended before sending actual data to describe what it's sending.

Classes in org.apache.cassandra.streaming.messages used by org.apache.cassandra.streaming.messages

Class and Description

CompleteMessage

FileMessageHeader

StreamingFileHeader is appended before sending actual data to describe what it's sending.

IncomingFileMessage

IncomingFileMessage is used to receive the part(or whole) of a SSTable data file.

OutgoingFileMessage

OutgoingFileMessage is used to transfer the part(or whole) of a SSTable data file.

PrepareMessage

ReceivedMessage

RetryMessage

SessionFailedMessage

StreamInitMessage

StreamInitMessage is first sent from the node where StreamSession is started,
 to initiate corresponding StreamSession on the other side.

StreamMessage

StreamMessage is an abstract base class that every messages in streaming protocol inherit.

StreamMessage.Serializer

StreamMessage serializer

StreamMessage.Type

StreamMessage types

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
Python + Flask + neo4j on Heroku Example
========================================

I put this project together as an entry for the [Heroku neo4j challenge](http://neo4j-challenge.herokuapp.com/) and it should be fairly easy to get a feel for how to integrate neo4j into an app of your own or use as a base for a new app. Check out the [demo app](http://neo4j-python-example.herokuapp.com/) to see it in action.

The app is a simple data explorer with bookmarking ability to show off some of the features of neo4j. A subset of data from a [Stack Exchange CC data dump](http://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/), specifically [Programers Stack Exchange](http://programmers.stackexchange.com/), is used to populate a sample database. The bookmarking feature allows for weights to be added for later use in recomendations.

For more details about the the app check out the [wiki page](https://github.com/carsonmcdonald/Python-Flask-neo4j-Heroku-Example/wiki/App-Details).

I'm using the following stack on the server side:

* Python
* [Flask](http://flask.pocoo.org) web microframework
* [neo4j](http://neo4j.org/) graph database
* [py2neo](http://py2neo.org/) neo4j python library

I'm using the following stack on the client side:

* [handlebars.js]( http://handlebarsjs.com/) for templates
* [jquery](http://jquery.com/)
* [jquery address](http://www.asual.com/jquery/address/) for history support
* [underscore.js]( http://documentcloud.github.com/underscore/)
* [Twitter bootstrap](https://github.com/twitter/bootstrap)

If you find this code helpful take a minute and rate it on [Gensen](http://gensen.herokuapp.com/show/25). If you want to use this code as a base for another project take a look at the comments labeled "neo4j note" for hints on what might be most useful.

Deploying Localy
================

There are a few requirements for the app to run:

* neo4j needs to be installed and running. Following the [neo4j server guide](http://docs.neo4j.org/chunked/stable/server.html) should make that happen.
* [virtualenv](http://pypi.python.org/pypi/virtualenv) needs to be installed.

After verifing that requirements are ready the following should get things running:

    git clone git@github.com:carsonmcdonald/Python-Flask-neo4j-Heroku-Example.git
    cd Python-Flask-neo4j-Heroku-Example
    virtualenv venv --distribute
    source venv/bin/activate
    pip install -r requirements.txt
    # The following command will take a while to run but will produce output as it does
    python load.py
    # Once the load is complete the app is ready to run
    python app.py

You can also use [Foreman](http://blog.daviddollar.org/2011/05/06/introducing-foreman.html) to run locally.

Heroku Deployment
=================

    git clone git@github.com:carsonmcdonald/Python-Flask-neo4j-Heroku-Example.git
    cd Python-Flask-neo4j-Heroku-Example
    virtualenv venv --distribute
    source venv/bin/activate
    pip install -r requirements.txt
    heroku create --stack cedar
    heroku addons:add neo4j
    heroku scale web=0
    git push heroku master
    # This next step will take a while, maybe 30 minutes monitor it with the "heroku logs" command
    heroku run:detached python load.py
    # Once the load has completed
    heroku scale web=1

See the [Heroku Python howto](http://devcenter.heroku.com/articles/python) for more information.

License
=======

See the LICENSE file.


text:
"""

Created on Mon Dec 16 11:02:59 2013

Author: Josef Perktold
"""

from __future__ import print_function
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import statsmodels.nonparametric.api as npar
from statsmodels.sandbox.nonparametric import kernels
from statsmodels.distributions.mixture_rvs import mixture_rvs

# example from test_kde.py mixture of two normal distributions
np.random.seed(12345)
x = mixture_rvs([.25,.75], size=200, dist=[stats.norm, stats.norm],
                kwargs = (dict(loc=-1, scale=.5),dict(loc=1, scale=.5)))

x.sort() # not needed

kde = npar.KDEUnivariate(x)
kde.fit('gau')
ci = kde.kernel.density_confint(kde.density, len(x))

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.hist(x, bins=15, normed=True, alpha=0.25)
ax.plot(kde.support, kde.density, lw=2, color='red')
ax.fill_between(kde.support, ci[:,0], ci[:,1],
                    color='grey', alpha='0.7')
ax.set_title('Kernel Density Gaussian (bw = %4.2f)' % kde.bw)

# use all kernels directly

x_grid = np.linspace(np.min(x), np.max(x), 51)
x_grid = np.linspace(-3, 3, 51)

kernel_names = ['Biweight', 'Cosine', 'Epanechnikov', 'Gaussian',
                'Triangular', 'Triweight', #'Uniform',
                ]

fig = plt.figure()
for ii, kn in enumerate(kernel_names):
    ax = fig.add_subplot(2, 3, ii+1)   # without uniform
    ax.hist(x, bins=10, normed=True, alpha=0.25)
    #reduce bandwidth for Gaussian and Uniform which are to large in example
    if kn in ['Gaussian', 'Uniform']:
        args = (0.5,)
    else:
        args = ()
    kernel = getattr(kernels, kn)(*args)

    kde_grid = [kernel.density(x, xi) for xi in x_grid]
    confint_grid = kernel.density_confint(kde_grid, len(x))

    ax.plot(x_grid, kde_grid, lw=2, color='red', label=kn)
    ax.fill_between(x_grid, confint_grid[:,0], confint_grid[:,1],
                    color='grey', alpha='0.7')
    ax.legend(loc='upper left')

plt.show()


text:
import os, sys, traceback
def _genAll(verbose=1):
    from reportlab.lib.testutils import setOutDir
    setOutDir(__name__)
    from reportlab.lib.testutils import testsFolder
    topDir=os.path.dirname(testsFolder)
    L = [os.path.join(topDir,f) for f in (
            #'docs/reference/genreference.py',
            'docs/userguide/genuserguide.py',
            #'tools/docco/graphdocpy.py',
            )
        ]
    for f in ('src/rl_addons/pyRXP/docs/PyRXP_Documentation.rml',
            ):
        f = os.path.join(topDir,f)
        if os.path.isfile(f):
            L += [f]
            break
    for p in L:
        os.chdir(os.path.dirname(p))
        if p[-4:]=='.rml':
            try:
                from rlextra.rml2pdf.rml2pdf import main
                main(exe=0,fn=[os.path.basename(p)], quiet=not verbose, outDir=d)
            except:
                if verbose: traceback.print_exc()
        else:
            cmd = '"%s" %s %s' % (sys.executable,os.path.basename(p), not verbose and '-s' or '')
            if verbose: print(cmd)
            os.system(cmd)

"""Runs the manual-building scripts"""
if __name__=='__main__':
    #need a quiet mode for the test suite
    if '-s' in sys.argv:  # 'silent
        verbose = 0
    else:
        verbose = 1
    d = os.path.dirname(sys.argv[0])
    if not d:
        d = os.getcwd()
    elif not os.path.isabs(d):
        d = os.path.abspath(d)
    sys.path.insert(0,os.path.dirname(d))
    _genAll(verbose)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Localization.Bidi;
using OpenLiveWriter.Localization;

namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl
{
    internal partial class RadioCategorySelector : UserControl, ICategorySelector, IRtlAware
    {
        private readonly CategoryContext ctx;

        public RadioCategorySelector()
        {
            Debug.Assert(DesignMode);
            InitializeComponent();
        }

        public RadioCategorySelector(CategoryContext ctx)
        {
            // We set it here because we need it set before we naturalize height, which happens in the costructor (LoadCategories)
            this.Font = Res.DefaultFont;
            this.ctx = ctx;
            InitializeComponent();

            LoadCategories(false);
        }

        public void LoadCategories()
        {
            LoadCategories(true);
        }

        private void LoadCategories(bool doRtlFixup)
        {
            Controls.Clear();
            int y = DockPadding.Top;
            List<BlogPostCategory> categories = new List<BlogPostCategory>(ctx.Categories);
            if (categories.Count == 0)
                return;

            categories.Add(new BlogPostCategoryNone());
            categories.Sort();

            BlogPostCategory[] selected = ctx.SelectedCategories;

            foreach (BlogPostCategory cat in categories)
            {
                RadioButton radio = new RadioButton();
                Controls.Add(radio);
                radio.Text = HtmlUtils.UnEscapeEntities(cat.Name, HtmlUtils.UnEscapeMode.Default);
                radio.AccessibleName = cat.Name;
                radio.UseMnemonic = false;
                radio.Tag = cat;
                radio.AutoSize = true;
                radio.Location = new Point(DockPadding.Left, y);
                y = radio.Bottom;

                if (BlogPostCategoryNone.IsCategoryNone(cat))
                    radio.Checked = selected.Length == 0;
                else
                    radio.Checked = Array.IndexOf(selected, cat) >= 0;

                radio.CheckedChanged += radio_CheckedChanged;

            }

            if (doRtlFixup)
                BidiHelper.RtlLayoutFixup(this, true);
        }

        private void radio_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radio = ((RadioButton)sender);
            if (radio.Checked)
            {
                if (ContainsFocus)
                    radio.Focus();
                ctx.SelectedCategories = new BlogPostCategory[] { ((BlogPostCategory)radio.Tag) };
            }
            else
                ctx.SelectedCategories = new BlogPostCategory[0];
        }

        public void Filter(string criteria)
        {
            int y = DockPadding.Top;
            foreach (Control c in Controls)
            {
                if (criteria.Length == 0
                    || c.Text.ToLower(CultureInfo.CurrentCulture).StartsWith(criteria))
                {
                    c.Visible = true;
                    c.Top = y;
                    y += c.GetPreferredSize(Size.Empty).Height;
                }
                else
                    c.Visible = false;
            }
        }

        public void SelectCategory(BlogPostCategory category)
        {
            foreach (RadioButton radio in Controls)
            {
                if (category.Equals(radio.Tag))
                {
                    radio.Checked = true;
                    return;
                }
            }
        }

        private int SelectedIndex
        {
            get
            {
                for (int i = 0; i < Controls.Count; i++)
                    if (((RadioButton)Controls[i]).Checked)
                        return i;
                return -1;
            }
        }

        private List<RadioButton> VisibleControls
        {
            get
            {
                List<RadioButton> results = new List<RadioButton>();
                foreach (RadioButton radio in Controls)
                    if (radio.Visible)
                        results.Add(radio);
                return results;
            }
        }

        public void UpArrow()
        {
            MoveSelection(true);
        }

        public void DownArrow()
        {
            MoveSelection(false);
        }

        private void MoveSelection(bool up)
        {
            List<RadioButton> controls = VisibleControls;
            if (controls.Count == 0)
                return;

            int idx = SelectedIndex;
            if (idx >= 0)
                idx = controls.IndexOf((RadioButton)Controls[idx]);

            if (idx < 0)
                idx = up ? controls.Count : -1;

            if (idx == 0 && up)
                idx = controls.Count;

            idx += up ? -1 : 1;
            idx %= controls.Count;
            controls[idx].Checked = true;
            ScrollControlIntoView(controls[idx]);
            controls[idx].Focus();
        }

        void ICategorySelector.Enter()
        {
            FindForm().Close();
        }

        void ICategorySelector.CtrlEnter()
        {
            FindForm().Close();
        }

        #region IRtlAware Members

        public new void Layout()
        {
            foreach (RadioButton radio in VisibleControls)
            {
                radio.Left = Width - radio.Width - DockPadding.Left;
            }
        }

        #endregion
    }
}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _COMMANDS_H_
#define _COMMANDS_H_

/*- Types ------------------------------------------------------------------*/
enum {
	APP_COMMAND_ID_NETWORK_INFO = 0x01,
	APP_COMMAND_ID_IDENTIFY     = 0x10,
};

/*- Prototypes -------------------------------------------------------------*/
void APP_CommandsInit(void);
bool APP_CommandsPending(uint16_t addr);
void APP_CommandsByteReceived(uint8_t byte);

#endif /* _COMMANDS_H_ */


text:
"""Tree utils."""

from typing import Callable

from etils.etree import jax as etree
import flax
from flax import traverse_util
from flax.core import freeze
from flax.core import unfreeze
from jax import numpy as jnp

parallel_map = etree.parallel_map
unzip = etree.unzip

def _sorted_items(x):
  """Returns items of a dict ordered by keys."""
  return sorted(x.items(), key=lambda x: x[0])

# TODO(tutmann): Add unit tests.
def filter_tree(variable_dict: flax.core.FrozenDict,
                filter_fn: Callable[[str, jnp.ndarray], bool]
                ) -> flax.core.FrozenDict:
  """Filter a nested dict.

  Args:
    variable_dict: Nested dictionary of variables.
    filter_fn: Function that decides for each variable whether it fn should be
      applied or not.

  Returns:
    Filtered copy of variable_dict containing all keys where filter_fn is True.
  """
  variable_dict = unfreeze(variable_dict)
  flat_dict = traverse_util.flatten_dict(variable_dict, keep_empty_nodes=True)
  new_dict = {}
  for key, value in _sorted_items(flat_dict):
    # empty_node is not an actual leave. It's just a stub for empty nodes
    # in the nested dict.
    if value is not traverse_util.empty_node:
      path = '/' + '/'.join(key)
      if filter_fn(path, value):
        new_dict[key] = value
  new_params = traverse_util.unflatten_dict(new_dict)
  return freeze(new_params)

# TODO(tutmann): Add unit tests.
def merge_trees(destination: flax.core.FrozenDict, source: flax.core.FrozenDict,
                ) -> flax.core.FrozenDict:
  """Merge source into destination.

  Args:
    destination: Destination frozen dict. Defines the default values.
    source: Source frozen dict. Values in this dict override ones in
      destination. Note that this only applies to keys that already exist in
      destination.

  Returns:
    Frozen dict copy of destination with values of source for all keys
    that exist in both destination and source.
  """
  destination = unfreeze(destination)
  source = unfreeze(source)
  flat_destination = traverse_util.flatten_dict(
      destination, keep_empty_nodes=True)
  flat_source = traverse_util.flatten_dict(source, keep_empty_nodes=True)
  new_dict = {}
  for key, value in _sorted_items(flat_destination):
    # empty_node is not an actual leave. It's just a stub for empty nodes
    # in the nested dict.
    if value is not traverse_util.empty_node:
      if key in flat_source:
        new_dict[key] = flat_source[key]
      else:
        new_dict[key] = value
  new_params = traverse_util.unflatten_dict(new_dict)
  return freeze(new_params)