text:
import xbmc
import xbmcgui
import xbmcplugin
from urllib import quote_plus as quote
import sarpur
from sarpur import logger  # noqa
from util import strptime

class GUI(object):
    """
    A very simple class that wraps the interface functions in Kodi
    """

    def __init__(self, addon_handle, base_url):
        """
        :param addon_handle: An identifier that Kodi uses to identify the addon
                             (created in default.py)
        :param base_url: The root internal url used in all calls in the addon
        """
        self.addon_handle = addon_handle
        self.base_url = base_url

    def _get_url(self, action_key, action_value, name):

        format_params = {
            "base_url": self.base_url,
            "key": quote(action_key),
            "value": quote(action_value.encode('utf-8')),
            "name": quote(name.encode('utf-8'))
        }
        return (
            "{base_url}?action_key={key}&"
            "action_value={value}&name={name}".format(**format_params)
        )

    def _add_dir(
        self,
        name,
        action_key='',
        action_value='',
        image=None,
        is_folder=False,
        extra_info=None,
        selectable=True,
        context_menu=[],
        subtitles=None,
    ):
        """
        Creates a link in Kodi

        :param name: Name of the link
        :param action_key: Name of the action to take when link selected
        :param action_value: Parameter to use with the action
        :param image: Icon to use for the link
        :param is_folder: Does the link lead to a folder or playable item
        :param extra_info: Extra information for info label
        :param selectable: Default True.

        """
        list_item = xbmcgui.ListItem(name,
                                     iconImage=image,
                                     thumbnailImage='')
        if selectable:
            url = self._get_url(action_key, action_value, name)
            list_item.setProperty('IsPlayable', 'true')
        else:
            url = ''

        info_labels = {"Title": name}
        if extra_info:
            info_labels.update(extra_info)

        list_item.setInfo(type="Video", infoLabels=info_labels)

        if context_menu:
            list_item.addContextMenuItems(context_menu)

        if subtitles and any(subtitles):
            # Make sure we don't pass in [None]
            list_item.setSubtitles([sub for sub in subtitles if sub])

        xbmcplugin.addDirectoryItem(
            handle=self.addon_handle,
            url=url,
            listitem=list_item,
            isFolder=is_folder)

    def add_dir(self, name, action_key, action_value,
                image='DefaultFolder.png'):
        """
        Create link that leads to another folder (or "folder")

        :param name: The name of the folder
        :param action_key: Action to take
        :param action_value: Parameter to action
        :param image: Image to use with the folder
        """
        self._add_dir(
            name=name,
            action_key=action_key,
            action_value=action_value,
            image=image,
            is_folder=True,
        )

    def add_item(self, name, action_key, action_value,
                 image='DefaultMovies.png', extra_info=None, context_menu=[],
                 subtitles=None):
        """
        Create link to playable item (wrapper function for _addDir).

        :param name: The name of the folder
        :param action_key: Action to take
        :param action_value: Parameter to action
        :param image: Image to use for the item
        """
        self._add_dir(
            name=name,
            action_key=action_key,
            action_value=action_value,
            image=image,
            is_folder=False,
            extra_info=extra_info,
            context_menu=context_menu,
            subtitles=subtitles,
        )

    def add_unselectable_item(self, name, image, extra_info=None):
        unselectable_name = u'[COLOR red]{0}[/COLOR]'.format(name)
        self._add_dir(
            name=unselectable_name,
            image=image,
            selectable=False,
            extra_info=extra_info,
        )

    def add_program_dir(self, program):
        title = program['title'] or program['foreign_title']
        if title:
            self.add_dir(
                title,
                'list_program_episodes',
                str(program['id']),
                image=program.get('image'),
            )

    def add_program_episode(self, program, episode):
        if episode['title'] and program['title']:
            title = u'{0} - {1}'.format(program['title'], episode['title'])
        elif episode['title']:
            title = episode['title']
        else:
            title = program['title']
        context_menu = []
        if program['web_available_episodes'] > 1:
            context_menu.append((
                sarpur.getLocalizedString(30910),
                u'XBMC.Container.Update({0})'.format(
                    self._get_url(
                        'list_program_episodes',
                        str(program['id']),
                        title,
                    )
                )
            ))
        self.add_item(
            title,
            'play_video',
            episode['file'],
            image=program.get('image'),
            subtitles=[episode.get('subtitles_url')],
            extra_info={
                'Episode': program['episodes'][0]['number'],
                'Premiered': strptime(
                    program['episodes'][0]['firstrun'],
                    '%Y-%m-%d %H:%M:%S',
                ).strftime('%d.%m.%Y'),
                'TotalEpisodes': program['web_available_episodes'],
                'Plot': '\n'.join(program.get('description', []))
            },
            context_menu=context_menu,
        )

    @staticmethod
    def info_box(title, message):
        """
        Display a pop up message.

        :param title: The title of the pop up window
        :param message: Message you want to display to the user
        """
        xbmcgui.Dialog().ok(title, message)

    @staticmethod
    def keyboard(title):
        """
        Display a keyboard

        :param title: Name of the modal window
        :return: User's input or None
        """
        keyboard = xbmc.Keyboard('', title)
        keyboard.doModal()
        if keyboard.isConfirmed():
            return keyboard.getText().strip()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the AOS Community (AOS) under one or more
  contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The AOS licenses this file
  to you 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.
-->

<!-- START SNIPPET: e1 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xmlns:cxf="http://camel.apache.org/schema/cxf"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
       http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">

    <!-- needed cxf imports -->
    <import resource="classpath:META-INF/cxf/cxf.xml"/>
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
    <!-- use the CXF servlet -->
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <!-- let Camel automatic find the route in this java package -->
        <package>org.apache.camel.example.cxf</package>
    </camelContext>

</beans>
<!-- END SNIPPET: e1 -->

redpajama_set_name: RedPajamaGithub


text:
require 'fresh_connection/extend/adapters/base_adapter'

module FreshConnection
  module Extend
    module M2Adapter
      private

      def __change_connection
        return yield unless FreshConnection::AccessControl.replica_access?

        master_connection = @connection
        begin
          replica_connection = @model_class.replica_connection
          @connection = replica_connection.raw_connection
          yield
        ensure
          @connection = master_connection
        end
      end
    end
  end
end


text:
package co.edu.unicartagena.platf.rest.resources;

import co.edu.unicartagena.platf.entity.DocumentFile;
import co.edu.unicartagena.platf.model.Message;
import co.edu.unicartagena.platf.service.DocumentFileService;
import co.edu.unicartagena.platf.service.DocumentFileServiceImpl;
import co.edu.unicartagena.platf.service.FileService;
import co.edu.unicartagena.platf.service.FileServiceImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.UriInfo;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

/**
 *
 * @author Gustavo Pacheco <ryctabo@gmail.com>
 * @version 1.0-SNAPSHOT
 */
@Path("files/documents")
public class DocumentFileResource {

    FileService fileService = new FileServiceImpl();

    DocumentFileService service = DocumentFileServiceImpl.getInstance();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<DocumentFile> getAllDocumentFiles() {
        return service.getAll();
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadDocumentFile(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition fileMetaData,
            @Context UriInfo uriInfo) {
        String fileName = fileService.upload(fileInputStream, fileMetaData);

        if (fileName != null) {
            DocumentFile newDocumentFile = service.add(new DocumentFile(fileName));
            String newId = String.valueOf(newDocumentFile.getId());

            URI uri = uriInfo.getAbsolutePathBuilder()
                    .path(DocumentFileResource.class)
                    .path(newId).build();

            return Response.created(uri)
                    .entity(newDocumentFile)
                    .build();
        } else {
            Message em = new Message(500, "the file name is null");
            throw new WebApplicationException(Response
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(em)
                    .build());
        }
    }

    @DELETE
    @Path("{documentId}")
    @Produces(MediaType.APPLICATION_JSON)
    public DocumentFile removeDocumentFile(@PathParam("documentId") Integer id) {
        DocumentFile document = service.get(id);
        if (fileService.delete(FileService.FileType.DOCUMENT, document.getName()))
            return service.remove(id);
        else {
            String msg = String.format("Could not delete the file with id %d.", id);
            Message em = new Message(500, msg);
            throw new InternalServerErrorException(Response
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(em)
                    .build());
        }
    }

    @GET
    @Path("{documentId}")
    public Response downloadDocumentFile(@PathParam("documentId") Integer id) {
        final DocumentFile documentFile = service.get(id);
        StreamingOutput streamingOutput = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException,
                    WebApplicationException {
                String pathname = fileService.getPathName(
                        FileService.FileType.DOCUMENT,
                        documentFile.getName());
                FileInputStream in = new FileInputStream(new File(pathname));
                fileService.write(in, out);
            }
        };
        return Response.ok(streamingOutput)
                .type("application/pdf")
                .header("Content-Disposition", "filename=" + "document.pdf")
                .build();
    }

}


text:
#include "../../SDL_internal.h"
#include "SDL_mouse.h"
#include "SDL_waylandvideo.h"

#if SDL_VIDEO_DRIVER_WAYLAND

extern void Wayland_InitMouse(void);
extern void Wayland_FiniMouse(SDL_VideoData *data);

#endif


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    //'WdevPicture\Module'                        => __DIR__ . '/Module.php',
    //'WdevPicture\Controller\SkeletonController' => __DIR__ . '/src/WdevPicture/Controller/SkeletonController.php',
);


text:
include(GetGitRevisionDescription)

get_git_head_revision(GIT_REFVAR _GIT_VERSION_HASH)

# if there is not git directory we should be in a distributed package
# we will use version provided in Version.cmake
if(_GIT_VERSION_HASH STREQUAL "GITDIR-NOTFOUND")
  return()
endif()

if(_GIT_VERSION_HASH MATCHES "[a-fA-F0-9]+")
  # Get first seven chars of hash (git default for short hash)
  # https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection
  string(SUBSTRING "${_GIT_VERSION_HASH}" 0 7 _GIT_VERSION_HASH)
endif()

# find the closest anotated tag with the v prefix for version
git_describe(_GIT_TAG "--match=v*")

git_commits_since("${PROJECT_SOURCE_DIR}/Version.cmake" _GIT_VERSION_COUNT)

set(VERSION_REGEX "^v([0-9]+)\\.([0-9]+)+(\\.([0-9]+))?(\\.([0-9]+))?((a|b|c|rc)[0-9]*)?(-[0-9]+)?")

string(REGEX MATCH "${VERSION_REGEX}" _out "${_GIT_TAG}")

if("${_out}" STREQUAL "")
  message(WARNING "git tag: \"${_GIT_TAG}\" does not match expected version format!")
  return()
endif()

set(_GIT_VERSION_MAJOR "${CMAKE_MATCH_1}")
set(_GIT_VERSION_MINOR "${CMAKE_MATCH_2}")
if(NOT "${CMAKE_MATCH_4}" STREQUAL "")
  set(_GIT_VERSION_PATCH "${CMAKE_MATCH_4}")
endif()
if(NOT "${CMAKE_MATCH_6}" STREQUAL "")
  set(_GIT_VERSION_TWEAK "${CMAKE_MATCH_6}")
endif()
if(NOT "${CMAKE_MATCH_7}" STREQUAL "")
  set(_GIT_VERSION_RC "${CMAKE_MATCH_7}" ) # a,b,rc01 etc
endif()

if(NOT "${CMAKE_MATCH_9}" STREQUAL "")
  #trim leading '-'
  string(SUBSTRING "${CMAKE_MATCH_9}" 1 -1 CMAKE_MATCH_9)

  set(_GIT_TAG_COUNT "${CMAKE_MATCH_9}")
endif()

set(_GIT_VERSION "${_GIT_VERSION_MAJOR}.${_GIT_VERSION_MINOR}")
if(DEFINED _GIT_VERSION_PATCH)
  set(_GIT_VERSION "${_GIT_VERSION}.${_GIT_VERSION_PATCH}")
  if(DEFINED _GIT_VERSION_TWEAK)
    set(_GIT_VERSION "${_GIT_VERSION}.${_GIT_VERSION_TWEAK}")
  elseif(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_TWEAK)
    set(_GIT_VERSION "${_GIT_VERSION}.0")
  endif()
elseif(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_PATCH)
  set(_GIT_VERSION "${_GIT_VERSION}.0")
  if(DEFINED ${CMAKE_PROJECT_NAME}_VERSION_TWEAK)
    set(_GIT_VERSION "${_GIT_VERSION}.0")
  endif()
endif()


text:
<html>
<body>

Classes supporting the org.springframework.context package,
such as abstract base classes for ApplicationContext
implementations and a MessageSource implementation.

</body>
</html>


text:
@class XCProject;

@interface XCBuildShellScript : NSObject
{
    NSString* _key;

@private
    XCProject*_project;
    BOOL _runOnlyForDeploymentPostprocessing;
    NSArray*_files;
    NSArray*_inputPaths;
    NSArray*_outputPaths;
    NSString*_name;
    NSString*_shellPath;
    NSString*_shellScript;
}

@property(nonatomic, strong, readonly,nonnull) NSString* key;
@property(nonatomic, strong, readonly,nonnull) NSString* name;
@property(nonatomic,readonly) BOOL runOnlyForDeploymentPostprocessing;
@property(nonatomic,nonnull,strong,readonly) NSString*shellScript;
@property(nonatomic,nonnull,strong,readonly) NSString*shellPath;
@property(nonatomic,nonnull,strong,readonly) NSArray<NSString*>*files;
@property(nonatomic,nonnull,strong,readonly) NSArray<NSString*>*inputPaths;
@property(nonatomic,nonnull,strong,readonly) NSArray<NSString*>*outputPaths;

//-------------------------------------------------------------------------------------------
#pragma mark - Initialization & Destruction
//-------------------------------------------------------------------------------------------

+ (XCBuildShellScript*_Nonnull)shellScriptWithProject:(XCProject*_Nonnull)project
                                                  key:(NSString *_Nonnull)key
                                                 name:( NSString* _Nullable )name
                         files: (NSArray<NSString*>* _Nullable)files
                    inputPaths:(NSArray<NSString*>* _Nullable)inputPaths
                   outputPaths:(NSArray<NSString*>* _Nullable)outputPaths
runOnlyForDeploymentPostprocessing:(BOOL)runOnlyForDeploymentPostprocessing
                     shellPath:(NSString*_Nullable)shellPath
                   shellScript:(NSString*_Nonnull)shellScript;

- (instancetype _Nonnull)initWithProject:(XCProject*_Nonnull)project
                                    key:(NSString *_Nonnull)key
                                    name:( NSString* _Nullable )name
                       files: (NSArray<NSString*>* _Nullable)files
                  inputPaths:(NSArray<NSString*>* _Nullable)inputPaths
                 outputPaths:(NSArray<NSString*>* _Nullable)outputPaths
runOnlyForDeploymentPostprocessing:(BOOL)runOnlyForDeploymentPostprocessing
                   shellPath:(NSString*_Nullable)shellPath
                 shellScript:(NSString*_Nonnull)shellScript;

@end


text:
module API
  module V1
    # Presses Controller
    class PressesController < API::ApplicationController
      before_action :set_press, only: %i[show]

      # Get press by subdomain
      # @example
      #   get /api/press?subdomain=String
      # @param [Hash] params { subdomain: String }
      # @return [ActionDispatch::Response] {Press} (see {show})
      def find
        @press = Press.find_by(subdomain: params[:subdomain])
        return head :not_found if @press.blank?
        render :show
      end

      # List presses
      # @example
      #   get /api/presses
      # @return [ActionDispatch::Response] array of {Press}
      #
      #   (See ./app/views/api/v1/presses/index.json.jbuilder)
      #
      #   {include:file:app/views/api/v1/presses/index.json.jbuilder}
      #
      #   (See ./app/views/api/v1/presses/_press.json.jbuilder)
      #
      #   {include:file:app/views/api/v1/presses/_press.json.jbuilder}
      def index
        @presses = Press.all
      end

      # Get press by id
      # @example
      #   get /api/presses/:id
      # @param [Hash] params { id: Number }
      # @return [ActionDispatch::Response] {Press}
      #
      #   (See ./app/views/api/v1/presses/show.json.jbuilder)
      #
      #   {include:file:app/views/api/v1/presses/show.json.jbuilder}
      #
      #   (See ./app/views/api/v1/presses/_press.json.jbuilder)
      #
      #   {include:file:app/views/api/v1/presses/_press.json.jbuilder}
      def show; end

      private

        def set_press
          @press = Press.find(params[:id])
        end

        def press_params
          params.require(:press).permit(:subdomain)
        end
    end
  end
end


text:
<?php

class IPF_Form_DB_Double extends IPF_Form_DB
{
    function formField($def, $form_field='IPF_Form_Field_Float')
    {
        $def['widget_attrs'] = array('style' => 'width:140px;');
        return parent::formField($def, $form_field);
    }
}


text:
You may have been wondering how do you lint your code inside `*.vue` files, since they are not JavaScript. We will assume you are using [ESLint](https://eslint.org/) (if you are not, you should!).

You will also need the [eslint-plugin-html](https://github.com/BenoitZugmeyer/eslint-plugin-html) which supports extracting and linting the JavaScript inside `*.vue` files.

Make sure to include the plugin in your ESLint config:

``` json
"plugins": [
  "html"
]
```

Then from the command line:

``` bash
eslint --ext js,vue MyComponent.vue
```

Another option is using [eslint-loader](https://github.com/MoOx/eslint-loader) so that your `*.vue` files are automatically linted on save during development:

``` bash
npm install eslint eslint-loader --save-dev
```

``` js
// webpack.config.js
module.exports = {
  // ... other options
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue!eslint'
      }
    ]
  }
}
```

Note that Webpack loader chains are applied **right-first**. Make sure to apply `eslint` before `vue` so we are linting the pre-compile source code.

One thing we need to consider is using third party `*.vue` components shipped in NPM packages. In such case, we want to use `vue-loader` to process the third party component, but do not want to lint it. We can separate the linting into Webpack's [preLoaders](https://webpack.github.io/docs/loaders.html#loader-order):

``` js
// webpack.config.js
module.exports = {
  // ... other options
  module: {
    // only lint local *.vue files
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        exclude: /node_modules/
      }
    ],
    // but use vue-loader for all *.vue files
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      }
    ]
  }
}
```

For Webpack 2.x:

``` js
// webpack.config.js
module.exports = {
  // ... other options
  module: {
    rules: [
      // only lint local *.vue files
      {
        enforce: 'pre',
        test: /\.vue$/,
        loader: 'eslint-loader',
        exclude: /node_modules/
      },
      // but use vue-loader for all *.vue files
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  }
}
```


text:
<?php

namespace Magento\Catalog\Model\ResourceModel\Layer\Filter;

/**
 * Catalog Layer Attribute Filter Resource Model
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Attribute extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     * Initialize connection and define main table name
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('catalog_product_index_eav', 'entity_id');
    }

    /**
     * Apply attribute filter to product collection
     *
     * @param \Magento\Catalog\Model\Layer\Filter\FilterInterface $filter
     * @param int $value
     * @throws \Magento\Framework\Exception\LocalizedException
     * @return $this
     */
    public function applyFilterToCollection(\Magento\Catalog\Model\Layer\Filter\FilterInterface $filter, $value)
    {
        $collection = $filter->getLayer()->getProductCollection();
        $attribute = $filter->getAttributeModel();
        $connection = $this->getConnection();
        $tableAlias = $attribute->getAttributeCode() . '_idx';
        $conditions = [
            "{$tableAlias}.entity_id = e.entity_id",
            $connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
            $connection->quoteInto("{$tableAlias}.store_id = ?", $collection->getStoreId()),
            $connection->quoteInto("{$tableAlias}.value = ?", $value),
        ];

        $collection->getSelect()->join(
            [$tableAlias => $this->getMainTable()],
            implode(' AND ', $conditions),
            []
        );

        return $this;
    }

    /**
     * Retrieve array with products counts per attribute option
     *
     * @param \Magento\Catalog\Model\Layer\Filter\FilterInterface $filter
     * @throws \Magento\Framework\Exception\LocalizedException
     * @return array
     */
    public function getCount(\Magento\Catalog\Model\Layer\Filter\FilterInterface $filter)
    {
        // clone select from collection with filters
        $select = clone $filter->getLayer()->getProductCollection()->getSelect();
        // reset columns, order and limitation conditions
        $select->reset(\Magento\Framework\DB\Select::COLUMNS);
        $select->reset(\Magento\Framework\DB\Select::ORDER);
        $select->reset(\Magento\Framework\DB\Select::LIMIT_COUNT);
        $select->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET);

        $connection = $this->getConnection();
        $attribute = $filter->getAttributeModel();
        $tableAlias = sprintf('%s_idx', $attribute->getAttributeCode());
        $conditions = [
            "{$tableAlias}.entity_id = e.entity_id",
            $connection->quoteInto("{$tableAlias}.attribute_id = ?", $attribute->getAttributeId()),
            $connection->quoteInto("{$tableAlias}.store_id = ?", $filter->getStoreId()),
        ];

        $select->join(
            [$tableAlias => $this->getMainTable()],
            join(' AND ', $conditions),
            ['value', 'count' => new \Zend_Db_Expr("COUNT({$tableAlias}.entity_id)")]
        )->group(
            "{$tableAlias}.value"
        );

        return $connection->fetchPairs($select);
    }
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta charset="utf-8"/>
    <title>API Documentation</title>
    <meta name="author" content=""/>
    <meta name="description" content=""/>

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
    <link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
    <link href="../css/prism.css" rel="stylesheet" media="all"/>
    <link href="../css/template.css" rel="stylesheet" media="all"/>

    <link rel="shortcut icon" href="../images/favicon.ico"/>
    <link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/>
    <link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/>
    <link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/>

            API Documentation

                            API Documentation

\Morphatic

                            Charts

                                     Class hierarchy diagram

                            Reports

                                                                                Errors 0

                                                                                Markers 7

                                \

                                Morphatic

                                Qualtrics

                                Exceptions

CurlException

CurlNotInstalledException

MissingParameterException

QualtricsException

QualtricsXMLException

UnknownFormatException

                                Facades

Qualtrics

Qualtrics

QualtricsServiceProvider

                                                \Morphatic\Qualtrics

\Morphatic\QualtricsQualtricsServiceProvider

QualtricsServiceProvider class

This class registers the Qualtrics package and all of its
exceptions with the Laravel 4 framework.

Summary

                                Methods

                                Properties

                                Constants

                                                                    boot()

                                                                    register()

                                                                    provides()

                                                                    No public properties found

                                                                    No constants found

                                                                    No protected methods found

                                                                    $defer

                                N/A

                                                                    No private methods found

                                                                    No private properties found

                                N/A

File

Morphatic/Qualtrics/QualtricsServiceProvider.php

Package

\Default

Class hierarchy

\Illuminate\Support\ServiceProvider

\Morphatic\Qualtrics\QualtricsServiceProvider

Tags

                                todo

Properties

$defer

$defer : bool

Indicates if loading of the provider is deferred.

Type

                bool

Tags

                            todo

Methods

boot()

boot() : void

Bootstrap the application events.

Tags

                            todo

register()

register() : void

Register the service provider.

Tags

                            todo

provides()

provides() : array

Get the services provided by the provider.

Returns

                    array

Tags

                            todo

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

QualtricsServiceProvider.php

\Morphatic

Class Hierarchy Diagram

Errors

Markers

                    Documentation is powered by phpDocumentor  and authored
                    on January 5th, 2014 at 00:27.


text:
import React, {Component} from 'react'
import {DropdownButton, MenuItem} from 'react-bootstrap'

import lang from '../../../helpers/lang'

class Languages extends Component {

  constructor (props) {
    super(props)
  }

  render () {
    const {languages, current, doChangeLang} = this.props

    if(!languages || !languages.length) {
      return (null)
    }

    const showLangId = (langId) => (

        {lang.get(langId)}

    )

    const title = (

      {languages.map((item, index) =>

          {showLangId(item.id)}{index < languages.length - 1 ? '/': ''}

      )}

    )

    return (

        <DropdownButton data-test-id="Languages.Dropdown"
          id={`languagesDropdown`}
          title={title}
          pullRight>
        {languages.map(item =>
          <MenuItem data-test-id="Languages.MenuItem"
            onSelect={() => doChangeLang(item.id)}
            key={item.id}>
            {showLangId(item.id)} - {item.name}
          </MenuItem>
        )}
        </DropdownButton>

    )
  }
}

export default Languages


text:
package com.craftandresolve.relax.exception;

public class BadRequestException extends HTTPCodeException {
    public BadRequestException(String shortText, String description) {
        super(400, shortText, description);
    }
}


text:
package com.compufiber.model;

import java.util.*;

import javax.persistence.*;

import org.openxava.annotations.*;
import org.openxava.util.*;
// import com.compufiber.validadores.*;

@Entity
@Table(name="LV_MARCAS",
uniqueConstraints={
        @UniqueConstraint(name="mr_no_repetir_descripcion", columnNames={"descripcion"}),
        @UniqueConstraint(name="mr_no_repetir_codigo", columnNames={"codigo"})
    })
public class Marcas extends SuperClaseFeliz {
	@Required
	@Column(length=20,nullable=false,name="CODIGO")
	private Long codigo ;

	@Required
	@Column(length=100,nullable=false,name="DESCRIPCION")
	private String descripcion ;

	public Long getCodigo() {
		return codigo;
	}

	public void setCodigo(Long codigo) {
		this.codigo = codigo;
	}

	public String getDescripcion() {
		return descripcion;
	}

	public void setDescripcion(String descripcion) {
		this.descripcion = descripcion.toUpperCase().trim();
	}

	@PreUpdate
	private void ultimoPaso() {
			Date mifechora = new java.util.Date() ;
			super.setModificadoPor(Users.getCurrent()) ;
			super.setFchUltMod(mifechora)  ;
	}
}


text:
//
// 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.
//
using System;

namespace System.Data.Linq.SqlClient
{
	public static class SqlMethods
	{
        static Exception NotSupported()
        {
            return new NotSupportedException("The method in SqlMethods type cannot be used directly. It is only for Linq to SQL trsnslation");
        }

        [MonoTODO]
		public static int DateDiffDay (DateTime startDate, DateTime endDate)
		{
            throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffDay (DateTime? startDate, DateTime? endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int DateDiffHour (DateTime startDate, DateTime endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int? DateDiffHour (DateTime? startDate, DateTime? endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int DateDiffMillisecond (DateTime startDate, DateTime endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int? DateDiffMillisecond (DateTime? startDate, DateTime? endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int DateDiffMinute (DateTime startDate, DateTime endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int? DateDiffMinute (DateTime? startDate, DateTime? endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int DateDiffMonth (DateTime startDate, DateTime endDate)
		{
            throw NotSupported();
        }

		[MonoTODO]
		public static int? DateDiffMonth (DateTime? startDate, DateTime? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffSecond (DateTime startDate, DateTime endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffSecond (DateTime? startDate, DateTime? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffYear (DateTime startDate, DateTime endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffYear (DateTime? startDate, DateTime? endDate)
		{
			throw NotSupported();
		}

		#region .NET 3.5 SP1 (DateTimeOffset)

		[MonoTODO]
		public static int DateDiffMicrosecond (DateTime startDate, DateTime endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffMicrosecond (DateTime? startDate, DateTime? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffNanosecond (DateTime startDate, DateTime endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffNanosecond (DateTime? startDate, DateTime? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffDay (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffDay (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffHour (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffHour (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffMicrosecond (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffMicrosecond (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffMillisecond (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffMillisecond (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffMinute (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffMinute (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffMonth (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffMonth (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffNanosecond (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffNanosecond (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffSecond (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffSecond (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int DateDiffYear (DateTimeOffset startDate, DateTimeOffset endDate)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static int? DateDiffYear (DateTimeOffset? startDate, DateTimeOffset? endDate)
		{
			throw NotSupported();
		}
		#endregion

		[MonoTODO]
		public static bool Like (string matchExpression, string pattern)
		{
			throw NotSupported();
		}

		[MonoTODO]
		public static bool Like (string matchExpression, string pattern, char escapeCharacter)
		{
			throw NotSupported();
		}
	}
}


text:
layout: page
title: About
---

A little more about my skills...!

Currently I work as a freelancer (+- 4 years of experience) and work for allvacuumstore.ca as Web Developer/Manager. My goal is to work remotley as a Web Developer helping the Company to grow with one or all of my knowledge which are mainly FULL STACK:

- HTML, CSS, Bootstrap

- PHP, jQuery, Javascript

- MySQL

CMS:

- WordPress

- Joomla

Management:

- WAMP

- FTP

- DNS

- Hosting issues

I also have some basic  knowledge with Photoshop.


text:
Required software

* php 7.1+
* php-mysqli
* php-mbstring
* php-pdo_mysql
* mysql
* all in a command-line env like Cygwin, babun, macos, linux.

Setup and run scripts:

1. Clone from this repo
1. git repo clone directory needs to be in your include_path in php.ini
1. launch.php script should be symlinked into your "Scripts" directory in the unpacked game:

```
ln -s /cygdrive/d/path/to/git/level09/launch.php /cygrdive/d/path/to/Journey/Scripts/launch
```

Then from within the "Scripts" directory, use launch like this:

```
php launch
```


text:
using testing::_;

namespace {

using TerminateGpuCallback = base::OnceCallback<void(std::string)>;

// Copied from ui/ozone/test/mock_platform_window_delegate.h to avoid
// dependency from the whole library (it causes link problems).
class MockPlatformWindowDelegate : public ui::PlatformWindowDelegate {
 public:
  MockPlatformWindowDelegate() = default;

  MockPlatformWindowDelegate(const MockPlatformWindowDelegate&) = delete;
  MockPlatformWindowDelegate& operator=(const MockPlatformWindowDelegate&) =
      delete;

  ~MockPlatformWindowDelegate() override = default;

  MOCK_METHOD1(OnBoundsChanged, void(const BoundsChange& change));
  MOCK_METHOD1(OnDamageRect, void(const gfx::Rect& damaged_region));
  MOCK_METHOD1(DispatchEvent, void(ui::Event* event));
  MOCK_METHOD0(OnCloseRequest, void());
  MOCK_METHOD0(OnClosed, void());
  MOCK_METHOD2(OnWindowStateChanged,
               void(ui::PlatformWindowState old_state,
                    ui::PlatformWindowState new_state));
  MOCK_METHOD0(OnLostCapture, void());
  MOCK_METHOD1(OnAcceleratedWidgetAvailable,
               void(gfx::AcceleratedWidget widget));
  MOCK_METHOD0(OnWillDestroyAcceleratedWidget, void());
  MOCK_METHOD0(OnAcceleratedWidgetDestroyed, void());
  MOCK_METHOD1(OnActivationChanged, void(bool active));
  MOCK_METHOD0(OnMouseEnter, void());
};

struct Environment {
  Environment()
      : task_environment((base::CommandLine::Init(0, nullptr),
                          TestTimeouts::Initialize(),
                          base::test::TaskEnvironment::MainThreadType::UI)) {
    logging::SetMinLogLevel(logging::LOG_FATAL);

    mojo::core::Init();
  }

  void SetTerminateGpuCallback(ui::WaylandBufferManagerHost* host) {
    DCHECK(host);
    host->SetTerminateGpuCallback(base::BindOnce(
        &Environment::OnTerminateCallbackFired, base::Unretained(this)));
  }

  void OnTerminateCallbackFired(std::string message) { terminated = true; }

  base::test::TaskEnvironment task_environment;
  bool terminated = false;
};

// Given the server runs on a different thread, but some of its parameters shall
// be accessed from the thread where the buffer fuzzer runs, we need to resume
// and pause the server to avoid race conditions.
void SyncServer(wl::TestWaylandServerThread* server,
                base::test::TaskEnvironment* task_env) {
  DCHECK(server);
  DCHECK(task_env);

  // Resume the server, flushing its pending events.
  server->Resume();

  // Wait for the client to finish processing these events.
  task_env->RunUntilIdle();

  // Pause the server, after it has finished processing any follow-up requests
  // from the client.
  server->Pause();
}

}  // namespace

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  static Environment env;
  DCHECK(!env.terminated);

  // Required for ICU initialization.
  static base::NoDestructor<base::AtExitManager> exit_manager;
  FuzzedDataProvider data_provider(data, size);

  base::CommandLine::Init(0, nullptr);

  // Required for base::FormatNumber that WaylandBufferManagerHost uses.
  base::test::InitializeICUForTesting();

  std::vector<uint32_t> known_fourccs{
      DRM_FORMAT_R8,          DRM_FORMAT_GR88,        DRM_FORMAT_ABGR8888,
      DRM_FORMAT_XBGR8888,    DRM_FORMAT_ARGB8888,    DRM_FORMAT_XRGB8888,
      DRM_FORMAT_XRGB2101010, DRM_FORMAT_XBGR2101010, DRM_FORMAT_RGB565,
      DRM_FORMAT_NV12,        DRM_FORMAT_YVU420};

  wl::TestWaylandServerThread server;
  CHECK(server.Start({.shell_version = wl::ShellVersion::kV6}));

  std::unique_ptr<ui::WaylandConnection> connection =
      std::make_unique<ui::WaylandConnection>();
  CHECK(connection->Initialize());

  // Wait until everything is initialised.
  env.task_environment.RunUntilIdle();

  // Pause the server after it has responded to all incoming events.
  server.Pause();

  auto screen = connection->wayland_output_manager()->CreateWaylandScreen();
  connection->wayland_output_manager()->InitWaylandScreen(screen.get());

  MockPlatformWindowDelegate delegate;
  gfx::AcceleratedWidget widget = gfx::kNullAcceleratedWidget;

  EXPECT_CALL(delegate, OnAcceleratedWidgetAvailable(_))
      .WillOnce(testing::SaveArg<0>(&widget));
  ui::PlatformWindowInitProperties properties;
  properties.bounds = gfx::Rect(0, 0, 800, 600);
  properties.type = ui::PlatformWindowType::kWindow;
  std::unique_ptr<ui::WaylandWindow> window = ui::WaylandWindow::Create(
      &delegate, connection.get(), std::move(properties));

  CHECK_NE(widget, gfx::kNullAcceleratedWidget);

  // Let the server process the events and wait until everything is initialised.
  SyncServer(&server, &env.task_environment);

  base::FilePath temp_dir, temp_path;
  base::ScopedFD fd =
      base::CreateAndOpenFdForTemporaryFileInDir(temp_dir, &temp_path);
  EXPECT_TRUE(fd.is_valid());

  // 10K screens are reality these days.
  const gfx::Size buffer_size(data_provider.ConsumeIntegralInRange(1U, 20000U),
                              data_provider.ConsumeIntegralInRange(1U, 20000U));
  // The buffer manager opens a file descriptor for each plane so |plane_count|
  // cannot be really large.  Technically, the maximum is |ulimit| minus number
  // of file descriptors opened by this process already (which is 17 at the time
  // of writing) but there is little sense in having more than a few planes in a
  // real system so here is a hard limit of 500.
  const uint32_t kPlaneCount = data_provider.ConsumeIntegralInRange(1U, 500U);
  const uint32_t kFormat = known_fourccs[data_provider.ConsumeIntegralInRange(
      0UL, static_cast<unsigned long>(known_fourccs.size() - 1))];

  std::vector<uint32_t> strides(kPlaneCount);
  std::vector<uint32_t> offsets(kPlaneCount);
  std::vector<uint64_t> modifiers(kPlaneCount);
  for (uint32_t i = 0; i < kPlaneCount; ++i) {
    strides[i] = data_provider.ConsumeIntegralInRange(1U, UINT_MAX);
    offsets[i] = data_provider.ConsumeIntegralInRange(0U, UINT_MAX);
    modifiers[i] =
        data_provider.ConsumeIntegralInRange(uint64_t(0), UINT64_MAX);
    if (kPlaneCount > 1 && modifiers[i] == DRM_FORMAT_MOD_INVALID)
      modifiers[i] = 0;
  }

  const uint32_t kBufferId = 1;

  auto* manager_host = connection->buffer_manager_host();
  env.SetTerminateGpuCallback(manager_host);
  manager_host->CreateDmabufBasedBuffer(
      mojo::PlatformHandle(std::move(fd)), buffer_size, strides, offsets,
      modifiers, kFormat, kPlaneCount, kBufferId);

  // Wait until the buffers are created.
  SyncServer(&server, &env.task_environment);

  if (!env.terminated) {
    // The server must notify the buffers are created so that the client is able
    // to free the resources (destroy the params).
    auto params_vector = server.zwp_linux_dmabuf_v1()->buffer_params();
    // To ensure, no other buffers are created, test the size of the vector.
    for (auto* mock_params : params_vector) {
      zwp_linux_buffer_params_v1_send_created(mock_params->resource(),
                                              mock_params->buffer_resource());
    }
    SyncServer(&server, &env.task_environment);
  } else {
    // If the |manager_host| fires the terminate gpu callback, we need to set
    // the callback again.
    env.SetTerminateGpuCallback(manager_host);
  }

  manager_host->DestroyBuffer(kBufferId);

  // Wait until the buffers are destroyed.
  SyncServer(&server, &env.task_environment);

  // Reset the value as |env| is a static object.
  env.terminated = false;

  return 0;
}


text:
package foam.dao;

import foam.core.X;
import foam.mlang.predicate.And;
import foam.mlang.predicate.Predicate;
import foam.mlang.order.Comparator;
import foam.dao.Sink;

public class OrderedDAO
  extends ProxyDAO
{
  protected foam.mlang.order.Comparator order_;

  public OrderedDAO(Comparator order, DAO delegate) {
    order_ = order;
    setDelegate(delegate);
  }

  public OrderedDAO setOrder(foam.mlang.order.Comparator order) {
    order_ = order;
    return this;
  }

  public Sink select_(X x,Sink s, long skip, long limit, Comparator order, Predicate predicate) {
    return super.select_(x, s, skip, limit, order_ == null ? order : order_, predicate);
  }

  public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
    super.removeAll_(x, skip, limit, order_ == null ? order : order_, predicate);
  }
}


text:
package uk.ac.susx.tag.gramexp.ast;

public abstract class AbstractNode<T extends AbstractNode<T>> implements Node<T> {
    private int startIndex;
    private int endIndex;

    public int getStartIndex() {
        return startIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }

    public void shiftIndices(int delta) {
        startIndex += delta;
        endIndex += delta;
    }

    public void mapIndices(int[] ixMap) {
        startIndex = ixMap[startIndex];
        endIndex = ixMap[endIndex];
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + " [" + startIndex + '-' + endIndex + ']';
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hacker with Bullhorn | Classic</title>
    <link rel="stylesheet" href="/css/style.css" />
    <link rel="stylesheet" href="/css/fonts.css" />

  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/atom-one-light.min.css">

        /home/classic

        ~/home

        ~/categories

        ~/tags

        ~/subscribe

Hacker with Bullhorn

Open-Source

2012/04/23

  Categories: Bullhorn Example

Hacker with bullhorn: “Save your money! Accept one of our free tanks! It is invulnerable, and can drive across rocks and swamps at ninety miles an hour while getting a hundred miles to the gallon!”

Prospective station wagon buyer: “I know what you say is true…but…er…I don’t know how to maintain a tank!”

Bullhorn: “You don’t know how to maintain a station wagon either!”

Buyer: “But this dealership has mechanics on staff. If something goes wrong with my station wagon, I can take a day off work, bring it here, and pay them to work on it while I sit in the waiting room for hours, listening to elevator music.”

Bullhorn: “But if you accept one of our free tanks we will send volunteers to your house to fix it for free while you sleep!”

Buyer: “Stay away from my house, you freak!”

Bullhorn: “But…”

Buyer: “Can’t you see that everyone is buying station wagons?”

      Open-Source | Github | Twitter


text:
class GithubLicenseCrawler < Versioneye::Crawl
  GITHUB_URL = "https://github.com"

  def self.logger
    if !defined?(@@log) || @@log.nil?
      @@log = Versioneye::DynLog.new("log/license.log", 10).log
    end
    @@log
  end

  def self.is_github_url(uri)
    false if uri.to_s.empty?

    if uri.host =~ /github\.com\z/i or uri.host =~ /githubusercontent\.com\z/i
      true
    else
      false
    end
  end

  # unifies various github urls into repo main-page
  def self.to_page_url(link_uri)
    _, owner, repo, _ = link_uri.path.to_s.split(/\//)
    return nil if owner.nil? or repo.nil?

    parse_url("#{GITHUB_URL}/#{owner}/#{repo}")
  end

  def self.crawl_licenses(licenses, update = false)
    lm = LicenseMatcher.new
    url_cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 2.minutes)

    n, n_match = 0, 0
    licenses.to_a.each do |lic_db|
      n += 1
      prod_dt = {
        language: lic_db[:language],
        prod_key: lic_db[:prod_key],
        version: lic_db[:version],
        url: lic_db[:url]
      }

      res = crawl_repo_page(lm, url_cache, prod_dt, update)
      n_match += 1 if res
    end

    [n, n_match]
  end

  def self.crawl_versionlinks(links, update = false)
    lm = LicenseMatcher.new
    url_cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 2.minutes)
    n, n_match = 0, 0

    links.to_a.each do |link|
      n += 1
      prod_dt = {
        language: link[:language],
        prod_key: link[:prod_key],
        version: link[:version_id],
        url: link[:link]
      }

      res = crawl_repo_page(lm, url_cache, prod_dt, update)
      n_match += 1 if res
    end

    [n, n_match]
  end

  # matches spdx ids found in the div.overall-summary container on the github repo page
  def self.crawl_repo_page(lm, url_cache, prod_dt, update = false, min_confidence = 0.9)
    repo_uri = parse_url prod_dt[:url]
    return if repo_uri.nil? # ignore non-valid urls
    return if !is_github_url(repo_uri) # ignore not valid github urls

    repo_uri = to_page_url repo_uri  # unify various repo urls into main www-page url
    return if repo_uri.nil? # failed to unify repo

    lic_id, score = url_cache.fetch(repo_uri) do
      logger.info "crawl_repo_pages: going to fetch overall summary from #{repo_uri.to_s}"
      fetch_and_process_page(lm, repo_uri)
    end

    return if lic_id.nil?

    if update
      matches = [[lm.to_spdx_id(lic_id), score, repo_uri.to_s]]
      save_license_updates(prod_dt, matches, min_confidence, "GithubLicenseCrawler")
    end

    true
  end

  def self.fetch_and_process_page(lm, link_uri)
    summary_text = fetch_overall_summary link_uri

    return [] if summary_text.to_s.empty?

    best_match = lm.match_rules(summary_text).to_a.first
    if best_match.to_s.empty?
      logger.info "\tfetch_and_process_page: no license in the summary of #{link_uri.to_s}: #{summary_text}"
      return []
    end

    return best_match
  end

  def self.fetch_overall_summary(link_uri)
    res = fetch link_uri
    if res.nil? or res.code < 200 or res.code >= 400
      logger.warn "\tfetch_overall_summary: failed request #{res.code} -> #{link_uri.to_s}"
      return nil
    end

    html_doc = Nokogiri::HTML(res.body)
    return nil if html_doc.nil?

    summary_elements = html_doc.xpath('//div[contains(@class, "overall-summary")]//a').to_a
    body_text  = ""
    summary_elements.each do |el|
      if el
        #add the `license` string to lower ambiguity as we are matching very specific area on the page
        body_text += ' ' + el.text.to_s + ' license '
      end
    end

    body_text.gsub(/\s+/, ' ')
  end

end


text:
namespace boost { namespace intrusive { namespace test {

#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4, class O5>
#else
template<class T, class ...Options>
#endif
struct has_insert_before<boost::intrusive::set<T,
   #if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
   O1, O2, O3, O4, O5
   #else
   Options...
   #endif
> >
{
   static const bool value = true;
};

}}}

struct my_tag;

using namespace boost::intrusive;

template<class VoidPointer>
struct hooks
{
   typedef set_base_hook
            <void_pointer<VoidPointer> >                    base_hook_type;
   typedef set_base_hook
           <link_mode<auto_unlink>
           , void_pointer<VoidPointer>
           , tag<my_tag>
           , optimize_size<true> >                          auto_base_hook_type;
   typedef set_member_hook<void_pointer
      <VoidPointer>, optimize_size<true> >                  member_hook_type;
   typedef set_member_hook
      <link_mode<auto_unlink>, void_pointer<VoidPointer> >  auto_member_hook_type;
   typedef nonhook_node_member< rbtree_node_traits <VoidPointer, false >,
                                rbtree_algorithms
                              > nonhook_node_member_type;
};

// container generator with void node allocator
template < bool Default_Holder >
struct GetContainer_With_Holder
{
template< class ValueType
        , class Option1 =void
        , class Option2 =void
        , class Option3 =void
        >
struct GetContainer
{
   typedef boost::intrusive::set
      < ValueType
      , Option1
      , Option2
      , Option3
      > type;
};
};

// container generator with standard (non-void) node allocator
template <>
struct GetContainer_With_Holder< false >
{
template< class ValueType
        , class Option1 =void
        , class Option2 =void
        , class Option3 =void
        >
struct GetContainer
{
   // extract node type through options->value_traits->node_traits->node
   typedef typename pack_options< rbtree_defaults, Option1, Option2, Option3 >::type packed_options;
   typedef typename detail::get_value_traits< ValueType, typename packed_options::proto_value_traits>::type value_traits;
   typedef typename value_traits::node_traits::node node;

   typedef boost::intrusive::set
      < ValueType
      , Option1
      , Option2
      , Option3
      , header_holder_type< pointer_holder< node > >
      > type;
};
};

template<class VoidPointer, bool constant_time_size, bool Default_Holder>
class test_main_template
{
   public:
   int operator()()
   {
      using namespace boost::intrusive;
      typedef testvalue<hooks<VoidPointer> , constant_time_size> value_type;

      test::test_generic_set < typename detail::get_base_value_traits
                  < value_type
                  , typename hooks<VoidPointer>::base_hook_type
                  >::type
                , GetContainer_With_Holder< Default_Holder >::template GetContainer
                >::test_all();
      test::test_generic_set < typename detail::get_member_value_traits
                  < value_type
                  , member_hook< value_type
                               , typename hooks<VoidPointer>::member_hook_type
                               , &value_type::node_
                               >
                  >::type
                , GetContainer_With_Holder< Default_Holder >::template GetContainer
                >::test_all();
      test::test_generic_set < nonhook_node_member_value_traits< value_type,
                                                                 typename hooks<VoidPointer>::nonhook_node_member_type,
                                                                 &value_type::nhn_member_,
                                                                 safe_link
                                                               >,
                               GetContainer_With_Holder< Default_Holder >::template GetContainer
                             >::test_all();
      return 0;
   }
};

template<class VoidPointer, bool Default_Holder>
class test_main_template<VoidPointer, false, Default_Holder>
{
   public:
   int operator()()
   {
      using namespace boost::intrusive;
      typedef testvalue<hooks<VoidPointer> , false> value_type;

      test::test_generic_set < typename detail::get_base_value_traits
                  < value_type
                  , typename hooks<VoidPointer>::base_hook_type
                  >::type
                , GetContainer_With_Holder< Default_Holder >::template GetContainer
                >::test_all();

      test::test_generic_set < typename detail::get_member_value_traits
                  < value_type
                  , member_hook< value_type
                               , typename hooks<VoidPointer>::member_hook_type
                               , &value_type::node_
                               >
                  >::type
                , GetContainer_With_Holder< Default_Holder >::template GetContainer
                >::test_all();

      test::test_generic_set < typename detail::get_base_value_traits
                  < value_type
                  , typename hooks<VoidPointer>::auto_base_hook_type
                  >::type
                , GetContainer_With_Holder< Default_Holder >::template GetContainer
                >::test_all();

      test::test_generic_set < typename detail::get_member_value_traits
                  < value_type
                  , member_hook< value_type
                               , typename hooks<VoidPointer>::auto_member_hook_type
                               , &value_type::auto_node_
                               >
                  >::type
                , GetContainer_With_Holder< Default_Holder >::template GetContainer
                >::test_all();

      return 0;
   }
};

// container generator which ignores further parametrization, except for compare option
template < typename Value_Traits, bool ConstantTimeSize, typename HeaderHolder >
struct Get_Preset_Container
{
    template < class
             , class Option1 = void
             , class Option2 = void
             , class Option3 = void
             >
    struct GetContainer
    {
        // ignore further paramatrization except for the compare option
        // notably ignore the size option (use preset)
        typedef typename pack_options< rbtree_defaults, Option1, Option2, Option3 >::type packed_options;
        typedef typename packed_options::compare compare_option;

        typedef boost::intrusive::set< typename Value_Traits::value_type,
                                       value_traits< Value_Traits >,
                                       constant_time_size< ConstantTimeSize >,
                                       compare< compare_option >,
                                       header_holder_type< HeaderHolder >
                                     > type;
    };
};

template < bool ConstantTimeSize >
struct test_main_template_bptr
{
    void operator () ()
    {
        typedef BPtr_Value value_type;
        typedef BPtr_Value_Traits< RBTree_BPtr_Node_Traits > value_traits;
        typedef bounded_allocator< value_type > allocator_type;

        allocator_type::init();
        test::test_generic_set< value_traits,
                                Get_Preset_Container< value_traits, ConstantTimeSize,
                                                      bounded_pointer_holder< value_type >
                                                    >::template GetContainer
                              >::test_all();
        assert(allocator_type::is_clear());
        allocator_type::destroy();
    }
};

int main()
{
   // test (plain/smart pointers) x (nonconst/const size) x (void node allocator)
   test_main_template<void*, false, true>()();
   test_main_template<boost::intrusive::smart_ptr<void>, false, true>()();
   test_main_template<void*, true, true>()();
   test_main_template<boost::intrusive::smart_ptr<void>, true, true>()();
   //test (plain pointers) x (nonconst/const size) x (standard node allocator)
   test_main_template<void*, false, false>()();
   test_main_template<void*, true, false>()();
   // test (bounded pointers) x (nonconst/const size) x (special node allocator)
   test_main_template_bptr< true >()();
   test_main_template_bptr< false >()();

   return boost::report_errors();
}

#include <boost/intrusive/detail/config_end.hpp>


text:
package org.jetbrains.sbt
package project

import com.intellij.ide.util.newProjectWizard.AddModuleWizard
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.ide.wizard.Step
import com.intellij.openapi.externalSystem.service.project.wizard.SelectExternalProjectStep
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectOpenProcessorBase

/**
 * @author Pavel Fatin
 */
class SbtProjectOpenProcessor(builder: SbtProjectImportBuilder) extends ProjectOpenProcessorBase[SbtProjectImportBuilder](builder) {
  // Actual detection is done via the canOpenProject method (to "open" projects without build.sbt file).
  // However, these "extensions" are used inside ProjectOpenProcessorBase.doOpenProject to determine a project root directory.
  // TODO Don't depend on file extensions in ProjectOpenProcessorBase.doOpenProject to discover a project root (IDEA)
  def getSupportedExtensions = Array(Sbt.BuildFile, Sbt.ProjectDirectory)

  override def canOpenProject(file: VirtualFile): Boolean = SbtProjectImportProvider.canImport(file)

  override def doQuickImport(file: VirtualFile, wizardContext: WizardContext): Boolean = {
    val path = SbtProjectImportProvider.projectRootOf(file).getPath

    val dialog = new AddModuleWizard(null, path, new SbtProjectImportProvider(getBuilder))

    getBuilder.prepare(wizardContext)
    getBuilder.getControl(null).setLinkedProjectPath(path)

    dialog.getWizardContext.setProjectBuilder(getBuilder)
    dialog.navigateToStep((step: Step) => step.isInstanceOf[SelectExternalProjectStep])

    if (StringUtil.isEmpty(wizardContext.getProjectName)) {
      val projectName = dialog.getWizardContext.getProjectName
      if (!StringUtil.isEmpty(projectName)) {
        wizardContext.setProjectName(projectName)
      }
    }

    dialog.show()

    dialog.isOK
  }

  // That's a hack to display SBT icon in the open project file chooser (this part of the IDEA API is broken)
  // TODO Remove this when IDEA API will be properly re-designed
  override def lookForProjectsInDirectory = false
}


text:
package com.sangupta.dryredis;

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

interface DryRedisHashOperations {

    public int hdel(String key, String field);

    public int hdel(String key, List<String> fields);

    public int hexists(String key, String field);

    public Object hget(String key, String field);

    public List<String> hgetall(String key);

    public List<String> hkeys(String key);

    public int hlen(String key);

    public int hset(String key, String field, String value);

    public int hsetnx(String key, String field, String value);

    public int hstrlen(String key, String field);

    public List<String> hvals(String key);

    public long hincrby(String key, String field, long increment);

    public double hincrbyfloat(String key, String field, double increment);

    public List<String> hmget(String key, List<String> fields);

    public String hmset(String key, Map<String, String> fieldValues);

}


text:
"""
Basic rendering classes for Nevow applications.

API Stability: Completely unstable.
"""

from zope.interface import implements

from nevow.inevow import IRequest, IRenderable, IRendererFactory
from nevow.errors import MissingRenderMethod, MissingDocumentFactory

from nevow.util import Expose
from nevow.rend import _getPreprocessors

from nevow.flat.ten import registerFlattener
from nevow._flat import FlattenerError, _OldRendererFactory, _ctxForRequest
from nevow._flat import deferflatten

renderer = Expose(
    """
    Allow one or more methods to be used to satisfy template render
    directives::

    | class Foo(Element):
    |     def twiddle(self, request, tag):
    |         return tag['Hello, world.']
    |     renderer(twiddle)

    |

    |
    |

    Will result in this final output:

    |

    |     Hello, world.
    |

    """)

class Element(object):
    """
    Base for classes which can render part of a page.

    An Element is a renderer that can be embedded in a stan document and can
    hook its template (from the docFactory) up to render methods.

    An Element might be used to encapsulate the rendering of a complex piece of
    data which is to be displayed in multiple different contexts.  The Element
    allows the rendering logic to be easily re-used in different ways.

    Element implements L{IRenderable.renderer} to return render methods which
    are registered using L{nevow.page.renderer}.  For example::

        class Menu(Element):
            def items(self, request, tag):
                ....
            renderer(items)

    Render methods are invoked with two arguments: first, the
    L{nevow.inevow.IRequest} being served and second, the tag object which
    "invoked" the render method.

    Element implements L{IRenderable.render} to load C{docFactory} and return
    the result.

    @type docFactory: L{IDocFactory} provider
    @ivar docFactory: The factory which will be used to load documents to
        return from C{render}.
    """
    implements(IRenderable)

    docFactory = None
    preprocessors = ()

    def __init__(self, docFactory=None):
        if docFactory is not None:
            self.docFactory = docFactory

    def renderer(self, name):
        """
        Get the named render method using C{nevow.page.renderer}.
        """
        method = renderer.get(self, name, None)
        if method is None:
            raise MissingRenderMethod(self, name)
        return method

    def render(self, request):
        """
        Load and return C{self.docFactory}.
        """
        rend = self.rend
        if rend.im_func is not Element.__dict__['rend']:
            context = _ctxForRequest(request, [], self, False)
            return rend(context, None)

        docFactory = self.docFactory
        if docFactory is None:
            raise MissingDocumentFactory(self)
        return docFactory.load(None, _getPreprocessors(self))

    def rend(self, context, data):
        """
        Backwards compatibility stub.  This is only here so that derived
        classes can upcall to it.  It is not otherwise used in the rendering
        process.
        """
        context.remember(_OldRendererFactory(self), IRendererFactory)
        docFactory = self.docFactory
        if docFactory is None:
            raise MissingDocumentFactory(self)
        return docFactory.load(None, _getPreprocessors(self))

def _flattenElement(element, ctx):
    """
    Use the new flattener implementation to flatten the given L{IRenderable} in
    a manner appropriate for the specified context.
    """
    if ctx.precompile:
        return element

    synchronous = []
    accumulator = []
    request = IRequest(ctx, None) # XXX None case is DEPRECATED
    finished = deferflatten(request, element, ctx.isAttrib, True, accumulator.append)
    def cbFinished(ignored):
        if synchronous is not None:
            synchronous.append(None)
        return accumulator
    def ebFinished(err):
        if synchronous is not None:
            synchronous.append(err)
        else:
            return err
    finished.addCallbacks(cbFinished, ebFinished)
    if synchronous:
        if synchronous[0] is None:
            return accumulator
        synchronous[0].raiseException()
    synchronous = None
    return finished

registerFlattener(_flattenElement, Element)

__all__ = [
    'FlattenerError',

    'Element',

    'renderer', 'deferflatten',
    ]


text:
package com.github.lassana.circletimerwidget.widget;

import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.support.annotation.NonNull;

/**
* @author Nikolai Doronin
* @since 1/2/15.
*/
class CircleTimerSavedState extends Preference.BaseSavedState {
    int position;

    public CircleTimerSavedState(Parcel source) {
        super(source);
    }

    public CircleTimerSavedState(Parcelable superState) {
        super(superState);
    }

    @Override
    public void writeToParcel(@NonNull Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
        dest.writeInt(position);
    }

    public static final Creator<CircleTimerSavedState> CREATOR = new Creator<CircleTimerSavedState>() {
        @Override
        public CircleTimerSavedState createFromParcel(Parcel source) {
            return new CircleTimerSavedState(source);
        }

        @Override
        public CircleTimerSavedState[] newArray(int size) {
            return new CircleTimerSavedState[size];
        }
    };

}


text:
    __has_builtin(__builtin_operator_delete) != 201802L
#error builtin should report updated value
#endif

typedef __SIZE_TYPE__ size_t;
namespace std {
  struct nothrow_t {};
#if __cplusplus >= 201103L
enum class align_val_t : size_t {};
#else
  enum align_val_t {
  // We can't force an underlying type when targeting windows.
# ifndef _WIN32
    __zero = 0, __max = (size_t)-1
# endif
  };
#endif
}
std::nothrow_t nothrow;

void *operator new(size_t); // expected-note 1+ {{candidate function}}
void operator delete(void *); // expected-note 1+ {{candidate function}}

// Declare the reserved placement operators.
void *operator new(size_t, void*) throw(); // expected-note 1+ {{candidate function}}
void operator delete(void *, void *)throw(); // expected-note 1+ {{candidate function}}
void *operator new[](size_t, void*) throw();
void operator delete[](void*, void*) throw();

// Declare the replaceable global allocation operators.
void *operator new(size_t, const std::nothrow_t &) throw(); // expected-note 1+ {{candidate function}}
void *operator new[](size_t, const std::nothrow_t &) throw();
void operator delete(void *, const std::nothrow_t &)throw(); // expected-note 1+ {{candidate function}}
void operator delete[](void *, const std::nothrow_t &) throw();

// aligned allocation and deallocation functions.
void* operator new  ( size_t count, std::align_val_t al); // expected-note 1+ {{candidate function}}
void operator delete(void *, std::align_val_t); // expected-note 1+ {{candidate}}
#ifndef __cpp_aligned_new
// expected-note@-3 1+ {{non-usual 'operator new' declared here}}
// expected-note@-3 1+ {{non-usual 'operator delete' declared here}}
#endif
void *operator new[](size_t count, std::align_val_t al);
void operator delete[](void*, std::align_val_t);

void operator delete(void *, size_t); // expected-note 1+ {{candidate}}
#ifndef __cpp_sized_deallocation
// expected-note@-2 1+ {{non-usual 'operator delete' declared here}}
#endif
void operator delete[](void*, size_t);

// Declare some other placemenet operators.
void *operator new(size_t, void*, bool) throw(); // expected-note 1+ {{candidate function}}
void *operator new[](size_t, void*, bool) throw();

void *NP = 0;

void test_typo_in_args() {
  __builtin_operator_new(DNE);          // expected-error {{undeclared identifier 'DNE'}}
  __builtin_operator_new(DNE, DNE2);    // expected-error {{undeclared identifier 'DNE'}} expected-error {{'DNE2'}}
  __builtin_operator_delete(DNE);       // expected-error {{'DNE'}}
  __builtin_operator_delete(DNE, DNE2); // expected-error {{'DNE'}} expected-error {{'DNE2'}}
}

void test_arg_types() {
  __builtin_operator_new(NP);                      // expected-error {{no matching function for call to 'operator new'}}
  __builtin_operator_new(NP, std::align_val_t(0)); // expected-error {{no matching function for call to 'operator new'}}
}
void test_return_type() {
  int w = __builtin_operator_new(42);        // expected-error {{cannot initialize a variable of type 'int' with an rvalue of type 'void *'}}
  int y = __builtin_operator_delete(NP);     // expected-error {{cannot initialize a variable of type 'int' with an rvalue of type 'void'}}
}

void test_aligned_new() {
#ifdef __cpp_aligned_new
  void *p = __builtin_operator_new(42, std::align_val_t(2));
  __builtin_operator_delete(p, std::align_val_t(2));
#else
  // FIXME: We've manually declared the aligned new/delete overloads,
  // but LangOpts::AlignedAllocation is false. Should our overloads be considered
  // usual allocation/deallocation functions?
  void *p = __builtin_operator_new(42, std::align_val_t(2)); // expected-error {{call to '__builtin_operator_new' selects non-usual allocation function}}
  __builtin_operator_delete(p, std::align_val_t(2));         // expected-error {{call to '__builtin_operator_delete' selects non-usual deallocation function}}
#endif
}

void test_sized_delete() {
#ifdef __cpp_sized_deallocation
  __builtin_operator_delete(NP, 4);
#else
  __builtin_operator_delete(NP, 4); // expected-error {{call to '__builtin_operator_delete' selects non-usual deallocation function}}
#endif
}

void *operator new(size_t, bool);   // expected-note 1+ {{candidate}}
// expected-note@-1 {{non-usual 'operator new' declared here}}
void operator delete(void *, bool); // expected-note 1+ {{candidate}}
// expected-note@-1 {{non-usual 'operator delete' declared here}}

void test_non_usual() {
  __builtin_operator_new(42, true);     // expected-error {{call to '__builtin_operator_new' selects non-usual allocation function}}
  __builtin_operator_delete(NP, false); // expected-error {{call to '__builtin_operator_delete' selects non-usual deallocation function}}
}

template <int ID>
struct Tag {};
struct ConvertsToTypes {
  operator std::align_val_t() const;
  operator Tag<0>() const;
};

void *operator new(size_t, Tag<0>);   // expected-note 0+ {{candidate}}
void operator delete(void *, Tag<0>); // expected-note 0+ {{candidate}}

void test_ambiguous() {
#ifdef __cpp_aligned_new
  ConvertsToTypes cvt;
  __builtin_operator_new(42, cvt);    // expected-error {{call to 'operator new' is ambiguous}}
  __builtin_operator_delete(NP, cvt); // expected-error {{call to 'operator delete' is ambiguous}}
#endif
}

void test_no_args() {
  __builtin_operator_new();    // expected-error {{no matching function for call to 'operator new'}}
  __builtin_operator_delete(); // expected-error {{no matching function for call to 'operator delete'}}
}

void test_no_matching_fn() {
  Tag<1> tag;
  __builtin_operator_new(42, tag);    // expected-error {{no matching function for call to 'operator new'}}
  __builtin_operator_delete(NP, tag); // expected-error {{no matching function for call to 'operator delete'}}
}

template <class Tp, class Up, class RetT>
void test_dependent_call(Tp new_arg, Up delete_arg, RetT) {
  RetT ret = __builtin_operator_new(new_arg);
  __builtin_operator_delete(delete_arg);
}
template void test_dependent_call(int, int*, void*);

void test_const_attribute() {
  __builtin_operator_new(42); // expected-warning {{ignoring return value of function declared with const attribute}}
#ifdef __cpp_aligned_new
  __builtin_operator_new(42, std::align_val_t(8)); // expected-warning {{ignoring return value of function declared with const attribute}}
#endif
}


text:
function CurrencyConverter(currency) {
  "use strict";

  var SINGLES = {
    "0": "zero",
    "1": "one",
    "2": "two",
    "3": "three",
    "4": "four",
    "5": "five",
    "6": "six",
    "7": "seven",
    "8": "eight",
    "9": "nine"
  },
  TENS = {
    "20": "twenty",
    "30": "thirty",
    "40": "forty",
    "50": "fifty",
    "60": "sixty",
    "70": "seventy",
    "80": "eighty",
    "90": "ninety"
  },
  TEENS = {
    "10": "ten",
    "11": "eleven",
    "12": "twelve",
    "13": "thirteen",
    "14": "fourteen",
    "15": "fifteen",
    "16": "sixteen",
    "17": "seventeen",
    "18": "eighteen",
    "19": "nineteen"
  },
  SUFFIXES = [
    "",
    "thousand",
    "million",
    "billion",
    "trillion",
    "quadrillion",
    "quintillion",
    "sextillion"
  ],
  textArray = ["and", "dollars"],

  createOnesString = function(value) {
    return SINGLES[value.toString()];
  },

  createTeenString = function(value) {
    return TEENS[value.toString()];
  },

  createHypenatedString = function(numberText) {
    var array = numberText.split(""),
        joinWith = "",
        tensPlace = array[0],
        onesPlace = array[1],
        tenMultiple = parseInt(tensPlace, 10)*10,
        stringArray = [TENS[tenMultiple.toString()]];

    if (onesPlace !== "0") {
      stringArray.push(SINGLES[onesPlace]);
      joinWith = "-";
    }
    return stringArray.join(joinWith);
  },

  createTensString = function(tensInput) {
    var integerValue = parseInt(tensInput, 10);

    if (integerValue < 10) {
      return createOnesString(integerValue);
    }

    if (integerValue < 20) {
      return createTeenString(integerValue);
    }
    return createHypenatedString(tensInput);
  },

  addHundredsText = function(numberGroup, array) {
    var hundredsValue = numberGroup.slice(0, 1);

    if (hundredsValue !== "0") {
      array.unshift("hundred");
      array.unshift(SINGLES[hundredsValue]);
    }
    return array;
  },

  removeZeroValues = function(array) {
    if (array[0] === "zero") {
      array.pop();
    }
    return array;
  },

  createHundredGroups = function(numberGroup) {
    var tensValue = numberGroup.slice(-2),
        hundredsArray = [createTensString(tensValue)];

    if (numberGroup.length === 3) {
      hundredsArray = removeZeroValues(hundredsArray);
      hundredsArray = addHundredsText(numberGroup, hundredsArray);
    }
    return hundredsArray.join(" ");
  },

  addSuffix = function(count, array) {
    if (count !== 0) {
      array.unshift(SUFFIXES[count]);
    }
    return;
  },

  addCentsString = function(currencyArray) {
    var centsValue = "00",
        trailingZerosTruncated;

    if (currencyArray.length === 2) {
      trailingZerosTruncated = currencyArray[1].slice(0, 2);
      centsValue = ("0" + trailingZerosTruncated).slice(-2);
    }

    textArray.splice(-1, 0, centsValue+"/100");
    return;
  },

  splitDecimalPlace = function(value) {
    var currencyArray = value.split(".");

    addCentsString(currencyArray);
    return currencyArray[0];
  },

  convertedCurrencyString = function() {
    var string = textArray.join(" ");

    return string.charAt(0).toUpperCase() + string.slice(1);
  },

  parseDollarValue = function(dollarString) {
    var thousandsCount = 0,
        hundred,
        hundredString;

    while (dollarString.length > 0) {
      hundred = dollarString.slice(-3);
      dollarString = dollarString.slice(0, -3);
      hundredString = createHundredGroups(hundred);
      if (hundredString.length > 0) {
        addSuffix(thousandsCount, textArray);
        textArray.unshift(hundredString);
      }
      thousandsCount += 1;
    }
    return;
  };

  this.convertCurrency = function() {
    var dollarString = splitDecimalPlace(currency);

    parseDollarValue(dollarString);
    return convertedCurrencyString();
  };
}

CurrencyConverter.prototype.toText = function() {
  "use strict";

  return this.convertCurrency();
};


text:
export { default as socketIngressStream } from "./socket-ingress-stream";
export { default as socketEgressStream } from "./socket-egress-stream";
export { default as tcpEgressStream } from "./tcp-egress-stream";
export { default as tcpIngressStream } from "./tcp-ingress-stream";
export { default as rtmpInputStream } from "./rtmp-input-stream";
export { default as rtmpOutputStream } from "./rtmp-output-stream";
export { default as mpegMungerStream } from "./mpeg-munger-stream";
export { default as constantFpsStream } from "./constant-fps-stream";
export { default as ptsNormalizerStream } from "./pts-normalizer-stream";
export { default as fileInputStream } from "./file-input-stream";
export { default as fileOutputStream } from "./file-output-stream";
export { default as colorbarsStream } from "./colorbars-stream";
export { default as dashStream } from "./dash-stream";
export { default as dashServer } from "./dash-server";
export { default as spStream } from "./sp-stream";
export { default as convertVideoStream } from "./convert-video-stream";


text:
import * as _ from "../index";
declare module "../index" {
    interface LoDashStatic {
        /**
         * The opposite of _.method; this method creates a function that invokes the method at a given path on object.
         * Any additional arguments are provided to the invoked method.
         *
         * @param object The object to query.
         * @param args The arguments to invoke the method with.
         * @return Returns the new function.
         */
        methodOf(
            object: object,
            ...args: any[]
        ): (path: PropertyPath) => any;
    }

    interface LoDashImplicitWrapper<TValue> {
        /**
         * @see _.methodOf
         */
        methodOf(
            ...args: any[]
        ): LoDashImplicitWrapper<(path: PropertyPath) => any>;
    }

    interface LoDashExplicitWrapper<TValue> {
        /**
         * @see _.methodOf
         */
        methodOf(
            ...args: any[]
        ): LoDashExplicitWrapper<(path: PropertyPath) => any>;
    }
}


text:
Android Library to put a **ListView** inside a **ScrollView** without collapsing.

[![Maven Central](https://img.shields.io/badge/maven%20central-expandableheightlistview%3A1.0.0-brightgreen.svg)](http://search.maven.org/#artifactdetails|com.github.paolorotolo|expandableheightlistview|1.0.0|)
[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-ExpandableHeightListView-green.svg?style=flat)](https://android-arsenal.com/details/1/1919)

## How to use
Add this to your **build.gradle**:
```java
repositories {
    mavenCentral()
}

dependencies {
  compile 'com.github.paolorotolo:expandableheightlistview:1.0.0'
}
```

Add ExpandableHeightListView instead of ListView in your **xml files**:

```java
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <com.github.paolorotolo.expandableheightlistview.ExpandableHeightListView
            android:id="@+id/expandable_listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="8dp">
        </com.github.paolorotolo.expandableheightlistview.ExpandableHeightListView>
</ScrollView>
```

Expand ExpandableHeightListView **programmatically**:
```java
    ExpandableHeightListView expandableListView = (ExpandableHeightListView) findViewById(R.id.expandable_listview);

    expandableListView.setAdapter(adapterName);

    // This actually does the magic
    expandableListView.setExpanded(true);
```

It also works well with **GridView**.

Just use this instead:
```
<com.github.paolorotolo.expandableheightlistview.ExpandableHeightGridView
            android:id="@+id/expandable_listview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:padding="8dp">
        </com.github.paolorotolo.expandableheightlistview.ExpandableHeightGridView>
```

## Example
See it in action: download **test .apk** [here](https://github.com/PaoloRotolo/ExpandableHeightListView/raw/master/ExpandableHeightListViewExample/app/app-release.apk).

Also check the example app's sources here on GitHub *(ExpandableHeightListViewExample)*.

##Wait, what?
Well, did you ever try to put a ListView inside a ScrollView?

**This is what happens.**

And this is what you can do with **ExpandableHeightListView**.

*Inspired by [this](http://stackoverflow.com/questions/20659696/scroll-feature-of-listview-within-scroll-view) answer on StackOverflow.*