text:
title: Security
type: guide
order: 504
---

## Reporting Vulnerabilities

When a vulnerability is reported, it immediately becomes our top concern, with a full-time contributor dropping everything to work on it. To report a vulnerability, please email [security@vuejs.org](mailto:security@vuejs.org).

While the discovery of new vulnerabilities is rare, we also recommend always using the latest versions of Vue and its official companion libraries to ensure your application remains as secure as possible.

## Rule No.1: Never Use Non-trusted Templates

The most fundamental security rule when using Vue is **never use non-trusted content as your component template**. Doing so is equivalent to allowing arbitrary JavaScript execution in your application - and worse, could lead to server breaches if the code is executed during server-side rendering. An example of such usage:

``` js
new Vue({
  el: '#app',
  template: `<div>` + userProvidedString + `</div>` // NEVER DO THIS
})
```

Vue templates are compiled into JavaScript, and expressions inside templates will be executed as part of the rendering process. Although the expressions are evaluated against a specific rendering context, due to the complexity of potential global execution environments, it is impractical for a framework like Vue to completely shield you from potential malicious code execution without incurring unrealistic performance overhead. The most straightforward way to avoid this category of problems altogether is to make sure the contents of your Vue templates are always trusted and entirely controlled by you.

## What Vue Does to Protect You

### HTML content

Whether using templates or render functions, content is automatically escaped. That means in this template:

```html
<h1>{{ userProvidedString }}</h1>
```

if `userProvidedString` contained:

```js
'<script>alert("hi")</script>'
```

then it would be escaped to the following HTML:

```html
<script>alert("hi")</script>
```

thus preventing the script injection. This escaping is done using native browser APIs, like `textContent`, so a vulnerability can only exist if the browser itself is vulnerable.

### Attribute bindings

Similarly, dynamic attribute bindings are also automatically escaped. That means in this template:

```html
<h1 v-bind:title="userProvidedString">
  hello
</h1>
```

if `userProvidedString` contained:

```js
'" onclick="alert(\'hi\')'
```

then it would be escaped to the following HTML:

```html
" onclick="alert('hi')
```

thus preventing the close of the `title` attribute to inject new, arbitrary HTML. This escaping is done using native browser APIs, like `setAttribute`, so a vulnerability can only exist if the browser itself is vulnerable.

## Potential Dangers

In any web application, allowing unsanitized, user-provided content to be executed as HTML, CSS, or JavaScript is potentially dangerous, so should be avoided wherever possible. There are times when some risk be acceptable though.

For example, services like CodePen and JSFiddle allow user-provided content to be executed, but it's in a context where this is expected and sandboxed to some extent inside iframes. In the cases when an important feature inherently requires some level of vulnerability, it's up to your team to weigh the importance of the feature against the worst-case scenarios the vulnerability enables.

### Injecting HTML

As you learned earlier, Vue automatically escapes HTML content, preventing you from accidentally injecting executable HTML into your application. However, in cases where you know the HTML is safe, you can explicitly render HTML content:

- Using a template:
  ```html
  <div v-html="userProvidedHtml"></div>
  ```

- Using a render function:
  ```js
  h('div', {
    domProps: {
      innerHTML: this.userProvidedHtml
    }
  })
  ```

- Using a render function with JSX:
  ```jsx
  <div domPropsInnerHTML={this.userProvidedHtml}></div>
  ```

Note that user-provided HTML can never be considered 100% safe unless it's in a sandboxed iframe or in a part of the app where only the user who wrote that HTML can ever be exposed to it. Additionally, allowing users to write their own Vue templates brings similar dangers.

### Injecting URLs

In a URL like this:

```html
<a v-bind:href="userProvidedUrl">
  click me
</a>
```

There's a potential security issue if the URL has not been "sanitized" to prevent JavaScript execution using `javascript:`. There are libraries such as [sanitize-url](https://www.npmjs.com/package/@braintree/sanitize-url) to help with this, but note:

If you're ever doing URL sanitization on the frontend, you already have a security issue. User-provided URLs should always be sanitized by your backend before even being saved to a database. Then the problem is avoided for _every_ client connecting to your API, including native mobile apps. Also note that even with sanitized URLs, Vue cannot help you guarantee that they lead to safe destinations.

### Injecting Styles

Looking at this example:

```html
<a
  v-bind:href="sanitizedUrl"
  v-bind:style="userProvidedStyles"
>
  click me
</a>
```

let's assume that `sanitizedUrl` has been sanitized, so that it's definitely a real URL and not JavaScript. With the `userProvidedStyles`, malicious users could still provide CSS to "click jack", e.g. styling the link into a transparent box over the "Log in" button. Then if `https://user-controlled-website.com/` is built to resemble the login page of your application, they might have just captured a user's real login information.

You may be able to imagine how allowing user-provided content for a `<style>` element would create an even greater vulnerability, giving that user full control over how to style the entire page. That's why Vue prevents rendering of style tags inside templates, such as:

```html
<style>{{ userProvidedStyles }}</style>
```

To keep your users fully safe from click jacking, we recommend only allowing full control over CSS inside a sandboxed iframe. Alternatively, when providing user control through a style binding, we recommend using its [object syntax](class-and-style.html#Object-Syntax-1) and only allowing users to provide values for specific properties it's safe for them to control, like this:

```html
<a
  v-bind:href="sanitizedUrl"
  v-bind:style="{
    color: userProvidedColor,
    background: userProvidedBackground
  }"
>
  click me
</a>
```

### Injecting JavaScript

We strongly discourage ever rendering a `<script>` element with Vue, since templates and render functions should never have side effects. However, this isn't the only way to include strings that would be evaluated as JavaScript at runtime.

Every HTML element has attributes with values accepting strings of JavaScript, such as `onclick`, `onfocus`, and `onmouseenter`. Binding user-provided JavaScript to any of these event attributes is a potential security risk, so should be avoided.

Note that user-provided JavaScript can never be considered 100% safe unless it's in a sandboxed iframe or in a part of the app where only the user who wrote that JavaScript can ever be exposed to it.

Sometimes we receive vulnerability reports on how it's possible to do cross-site scripting (XSS) in Vue templates. In general, we do not consider such cases to be actual vulnerabilities, because there's no practical way to protect developers from the two scenarios that would allow XSS:

1. The developer is explicitly asking Vue to render user-provided, unsanitized content as Vue templates. This is inherently unsafe and there's no way for Vue to know the origin.

2. The developer is mounting Vue to an entire HTML page which happens to contain server-rendered and user-provided content. This is fundamentally the same problem as \#1, but sometimes devs may do it without realizing. This can lead to possible vulnerabilities where the attacker provides HTML which is safe as plain HTML but unsafe as a Vue template. The best practice is to never mount Vue on nodes that may contain server-rendered and user-provided content.

## Best Practices

The general rule is that if you allow unsanitized, user-provided content to be executed (as either HTML, JavaScript, or even CSS), you might be opening yourself up to attacks. This advice actually holds true whether using Vue, another framework, or even no framework.

Beyond the recommendations made above for [Potential Dangers](#Potential-Dangers), we also recommend familiarizing yourself with these resources:

- [HTML5 Security Cheat Sheet](https://html5sec.org/)
- [OWASP's Cross Site Scripting (XSS) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)

Then use what you learn to also review the source code of your dependencies for potentially dangerous patterns, if any of them include 3rd-party components or otherwise influence what's rendered to the DOM.

## Backend Coordination

HTTP security vulnerabilities, such as cross-site request forgery (CSRF/XSRF) and cross-site script inclusion (XSSI), are primarily addressed on the backend, so aren't a concern of Vue's. However, it's still a good idea to communicate with your backend team to learn how to best interact with their API, e.g. by submitting CSRF tokens with form submissions.

## Server-Side Rendering (SSR)

There are some additional security concerns when using SSR, so make sure to follow the best practices outlined throughout [our SSR documentation](https://ssr.vuejs.org/) to avoid vulnerabilities.


text:
package mock.web.rest;

import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.message.content.TemplateContent;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.email.message.Email;

@RestController
@RequestMapping("api")
public class EmailResource {
	@Autowired
	MessagingService messagingService;

	@RequestMapping(value="email/simple", method=POST)
	@ResponseStatus(CREATED)
	public void simple(@RequestParam("subject") String subject, @RequestBody String content, @RequestParam("to") String to) throws MessagingException {
		messagingService.send(new Email()
								.subject(subject)
								.content(content)
								.to(to));
	}

	@RequestMapping(value="email/thymeleaf", method=POST)
	@ResponseStatus(CREATED)
	public void thymeleaf(@RequestParam("subject") String subject, @RequestParam("template") String template, @RequestBody Object context, @RequestParam("to") String to) throws MessagingException {
		messagingService.send(new Email()
								.subject(subject)
								.content(new TemplateContent(template, context))
								.to(to));
	}

	@RequestMapping(value="email/freemarker", method=POST)
	@ResponseStatus(CREATED)
	public void freemarker(@RequestParam("subject") String subject, @RequestParam("template") String template, @RequestBody Object context, @RequestParam("to") String to) throws MessagingException {
		messagingService.send(new Email()
								.subject(subject)
								.content(new TemplateContent(template, context))
								.to(to));
	}
}

redpajama_set_name: RedPajamaGithub


text:
include(FBCMakeParseArgs)

# Generate a C++ library from a thrift file
#
# Parameters:
# - SERVICES <svc1> [<svc2> ...]
#   The names of the services defined in the thrift file.
# - DEPENDS <dep1> [<dep2> ...]
#   A list of other thrift C++ libraries that this library depends on.
# - OPTIONS <opt1> [<opt2> ...]
#   A list of options to pass to the thrift compiler.
# - INCLUDE_DIR <path>
#   The sub-directory where generated headers will be installed.
#   Defaults to "include" if not specified.  The caller must still call
#   install() to install the thrift library if desired.
# - THRIFT_INCLUDE_DIR <path>
#   The sub-directory where generated headers will be installed.
#   Defaults to "${INCLUDE_DIR}/thrift-files" if not specified.
#   The caller must still call install() to install the thrift library if
#   desired.
function(add_fbthrift_cpp_library LIB_NAME THRIFT_FILE)
  # Parse the arguments
  set(one_value_args INCLUDE_DIR THRIFT_INCLUDE_DIR)
  set(multi_value_args SERVICES DEPENDS OPTIONS)
  fb_cmake_parse_args(
    ARG "" "${one_value_args}" "${multi_value_args}" "${ARGN}"
  )
  if(NOT DEFINED ARG_INCLUDE_DIR)
    set(ARG_INCLUDE_DIR "include")
  endif()
  if(NOT DEFINED ARG_THRIFT_INCLUDE_DIR)
    set(ARG_THRIFT_INCLUDE_DIR "${ARG_INCLUDE_DIR}/thrift-files")
  endif()

  get_filename_component(base ${THRIFT_FILE} NAME_WE)
  get_filename_component(
    output_dir
    ${CMAKE_CURRENT_BINARY_DIR}/${THRIFT_FILE}
    DIRECTORY
  )

  # Generate relative paths in #includes
  file(
    RELATIVE_PATH include_prefix
    "${CMAKE_SOURCE_DIR}"
    "${CMAKE_CURRENT_SOURCE_DIR}/${THRIFT_FILE}"
  )
  get_filename_component(include_prefix ${include_prefix} DIRECTORY)

  if (NOT "${include_prefix}" STREQUAL "")
    list(APPEND ARG_OPTIONS "include_prefix=${include_prefix}")
  endif()
  # CMake 3.12 is finally getting a list(JOIN) function, but until then
  # treating the list as a string and replacing the semicolons is good enough.
  string(REPLACE ";" "," GEN_ARG_STR "${ARG_OPTIONS}")

  # Compute the list of generated files
  list(APPEND generated_headers
    "${output_dir}/gen-cpp2/${base}_constants.h"
    "${output_dir}/gen-cpp2/${base}_types.h"
    "${output_dir}/gen-cpp2/${base}_types.tcc"
    "${output_dir}/gen-cpp2/${base}_types_custom_protocol.h"
    "${output_dir}/gen-cpp2/${base}_metadata.h"
  )
  list(APPEND generated_sources
    "${output_dir}/gen-cpp2/${base}_constants.cpp"
    "${output_dir}/gen-cpp2/${base}_data.h"
    "${output_dir}/gen-cpp2/${base}_data.cpp"
    "${output_dir}/gen-cpp2/${base}_types.cpp"
    "${output_dir}/gen-cpp2/${base}_metadata.cpp"
  )
  foreach(service IN LISTS ARG_SERVICES)
    list(APPEND generated_headers
      "${output_dir}/gen-cpp2/${service}.h"
      "${output_dir}/gen-cpp2/${service}.tcc"
      "${output_dir}/gen-cpp2/${service}AsyncClient.h"
      "${output_dir}/gen-cpp2/${service}_custom_protocol.h"
    )
    list(APPEND generated_sources
      "${output_dir}/gen-cpp2/${service}.cpp"
      "${output_dir}/gen-cpp2/${service}AsyncClient.cpp"
      "${output_dir}/gen-cpp2/${service}_processmap_binary.cpp"
      "${output_dir}/gen-cpp2/${service}_processmap_compact.cpp"
    )
  endforeach()

  # This generator expression gets the list of include directories required
  # for all of our dependencies.
  # It requires using COMMAND_EXPAND_LISTS in the add_custom_command() call
  # below.  COMMAND_EXPAND_LISTS is only available in CMake 3.8+
  # If we really had to support older versions of CMake we would probably need
  # to use a wrapper script around the thrift compiler that could take the
  # include list as a single argument and split it up before invoking the
  # thrift compiler.
  if (NOT POLICY CMP0067)
    message(FATAL_ERROR "add_fbthrift_cpp_library() requires CMake 3.8+")
  endif()
  set(
    thrift_include_options
    "-I;$<JOIN:$<TARGET_PROPERTY:${LIB_NAME}.thrift_includes,INTERFACE_INCLUDE_DIRECTORIES>,;-I;>"
  )

  # Emit the rule to run the thrift compiler
  add_custom_command(
    OUTPUT
      ${generated_headers}
      ${generated_sources}
    COMMAND_EXPAND_LISTS
    COMMAND
      "${CMAKE_COMMAND}" -E make_directory "${output_dir}"
    COMMAND
      "${FBTHRIFT_COMPILER}"
      --strict
      --gen "mstch_cpp2:${GEN_ARG_STR}"
      "${thrift_include_options}"
      -o "${output_dir}"
      "${CMAKE_CURRENT_SOURCE_DIR}/${THRIFT_FILE}"
    WORKING_DIRECTORY
      "${CMAKE_BINARY_DIR}"
    MAIN_DEPENDENCY
      "${THRIFT_FILE}"
    DEPENDS
      ${ARG_DEPENDS}
      "${FBTHRIFT_COMPILER}"
  )

  # Now emit the library rule to compile the sources
  add_library(
    "${LIB_NAME}" STATIC
    ${generated_sources}
  )

  target_include_directories(
    "${LIB_NAME}"
    PUBLIC
      "$<BUILD_INTERFACE:${CMAKE_BINARY_DIR}>"
      "$<INSTALL_INTERFACE:${ARG_INCLUDE_DIR}>"
  )
  target_link_libraries(
    "${LIB_NAME}"
    PUBLIC
      ${ARG_DEPENDS}
      FBThrift::thriftcpp2
      Folly::folly
  )

  # Add ${generated_headers} to the PUBLIC_HEADER property for ${LIB_NAME}
  #
  # This allows callers to install it using
  # "install(TARGETS ${LIB_NAME} PUBLIC_HEADER)"
  # However, note that CMake's PUBLIC_HEADER behavior is rather inflexible,
  # and does have any way to preserve header directory structure.  Callers
  # must be careful to use the correct PUBLIC_HEADER DESTINATION parameter
  # when doing this, to put the files the correct directory themselves.
  # We define a HEADER_INSTALL_DIR property with the include directory prefix,
  # so typically callers should specify the PUBLIC_HEADER DESTINATION as
  # "$<TARGET_PROPERTY:${LIB_NAME},HEADER_INSTALL_DIR>"
  set_property(
    TARGET "${LIB_NAME}"
    PROPERTY PUBLIC_HEADER ${generated_headers}
  )

  # Define a dummy interface library to help propagate the thrift include
  # directories between dependencies.
  add_library("${LIB_NAME}.thrift_includes" INTERFACE)
  target_include_directories(
    "${LIB_NAME}.thrift_includes"
    INTERFACE
      "$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}>"
      "$<INSTALL_INTERFACE:${ARG_THRIFT_INCLUDE_DIR}>"
  )
  foreach(dep IN LISTS ARG_DEPENDS)
    target_link_libraries(
      "${LIB_NAME}.thrift_includes"
      INTERFACE "${dep}.thrift_includes"
    )
  endforeach()

  set_target_properties(
    "${LIB_NAME}"
    PROPERTIES
      EXPORT_PROPERTIES "THRIFT_INSTALL_DIR"
      THRIFT_INSTALL_DIR "${ARG_THRIFT_INCLUDE_DIR}/${include_prefix}"
      HEADER_INSTALL_DIR "${ARG_INCLUDE_DIR}/${include_prefix}/gen-cpp2"
  )
endfunction()


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

require('../config.php');
require_once('lib.php');

require_login(0, false);
if (isguestuser()) {
    // Guest users cannot perform lookups.
    throw new require_login_exception('Guests are not allowed here.');
}

$ip   = optional_param('ip', getremoteaddr(), PARAM_HOST);
$user = optional_param('user', 0, PARAM_INT);

if (isset($CFG->iplookup)) {
    // Clean up of old settings.
    set_config('iplookup', NULL);
}

$PAGE->set_url('/iplookup/index.php', array('id'=>$ip, 'user'=>$user));
$PAGE->set_pagelayout('popup');
$PAGE->set_context(context_system::instance());

$info = array($ip);
$note = array();

if (!preg_match('/(^\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $match)) {
    print_error('invalidipformat', 'error');
}

if ($match[1] > 255 or $match[2] > 255 or $match[3] > 255 or $match[4] > 255) {
    print_error('invalidipformat', 'error');
}

if ($match[1] == '127' or $match[1] == '10' or ($match[1] == '172' and $match[2] >= '16' and $match[2] <= '31') or ($match[1] == '192' and $match[2] == '168')) {
    print_error('iplookupprivate', 'error');
}

$info = iplookup_find_location($ip);

if ($info['error']) {
    // Can not display.
    notice($info['error']);
}

if ($user) {
    if ($user = $DB->get_record('user', array('id'=>$user, 'deleted'=>0))) {
        // note: better not show full names to everybody
        if (has_capability('moodle/user:viewdetails', context_user::instance($user->id))) {
            array_unshift($info['title'], fullname($user));
        }
    }
}
array_unshift($info['title'], $ip);

$title = implode(' - ', $info['title']);
$PAGE->set_title(get_string('iplookup', 'admin').': '.$title);
$PAGE->set_heading($title);
echo $OUTPUT->header();

if (empty($CFG->googlemapkey3)) {
    $imgwidth  = 620;
    $imgheight = 310;
    $dotwidth  = 18;
    $dotheight = 30;

    $dx = round((($info['longitude'] + 180) * ($imgwidth / 360)) - $imgwidth - $dotwidth/2);
    $dy = round((($info['latitude'] + 90) * ($imgheight / 180)));

    echo '
';
    echo '';
    echo '';
    echo '
';
    echo '
'.$info['note'].'
';

} else {
    if (strpos($CFG->wwwroot, 'https:') === 0) {
        $PAGE->requires->js(new moodle_url('https://maps.googleapis.com/maps/api/js', array('key'=>$CFG->googlemapkey3, 'sensor'=>'false')));
    } else {
        $PAGE->requires->js(new moodle_url('http://maps.googleapis.com/maps/api/js', array('key'=>$CFG->googlemapkey3, 'sensor'=>'false')));
    }
    $module = array('name'=>'core_iplookup', 'fullpath'=>'/iplookup/module.js');
    $PAGE->requires->js_init_call('M.core_iplookup.init3', array($info['latitude'], $info['longitude'], $ip), true, $module);

    echo '

';
    echo '
'.$info['note'].'
';
}

echo $OUTPUT->footer();


text:
package net.maritimecloud.common.cqrs;

/**
 * Marker interface that makes it easier to identify CQRS Commands in the mist of classes.
 * <p>
 * @author Christoffer Børrild
 */
public interface Command {

}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\OrderBundle\Tests\DependencyInjection;

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
use Sylius\Bundle\OrderBundle\DependencyInjection\Compiler\RegisterCartContextsPass;
use Sylius\Bundle\OrderBundle\DependencyInjection\Compiler\RegisterProcessorsPass;
use Sylius\Bundle\OrderBundle\DependencyInjection\SyliusOrderExtension;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Processor\OrderProcessorInterface;
use Symfony\Component\DependencyInjection\Definition;

final class SyliusOrderExtensionTest extends AbstractExtensionTestCase
{
    /**
     * @test
     */
    public function it_autoconfigures_cart_contexts_and_order_processors(): void
    {
        $this->markTestSkipped('Symfony 4.4 makes it impossible to test autoconfigured services this way.');

        $this->container->setDefinition(
            'acme.cart_context_autoconfigured',
            (new Definition())
                ->setClass($this->getMockClass(CartContextInterface::class))
                ->setAutoconfigured(true)
        );

        $this->container->setDefinition(
            'acme.processor_autoconfigured',
            (new Definition())
                ->setClass($this->getMockClass(OrderProcessorInterface::class))
                ->setAutoconfigured(true)
        );

        $this->load();
        $this->compile();

        $this->assertContainerBuilderHasServiceDefinitionWithTag(
            'acme.cart_context_autoconfigured',
            RegisterCartContextsPass::CART_CONTEXT_SERVICE_TAG
        );

        $this->assertContainerBuilderHasServiceDefinitionWithTag(
            'acme.processor_autoconfigured',
            RegisterProcessorsPass::PROCESSOR_SERVICE_TAG
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function getContainerExtensions(): array
    {
        return [new SyliusOrderExtension()];
    }
}


text:
<?php

declare(strict_types=1);

namespace Sphp\Html\Media\Multimedia;

use Sphp\Html\Media\MediaSource;

/**
 * Defines multimedia resources for media components
 *
 * @author  Sami Holck <sami.holck@gmail.com>
 * @license https://opensource.org/licenses/MIT The MIT License
 * @filesource
 */
interface MultimediaSource extends MediaSource {

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace lessonweb.Data
{
    public partial class PilotClass
    {
        // if the user exists and is valid, return the user, else return null
        public static ArrayList getPilotClassesForPilot(String pilotid)
        {
            ArrayList classes = new ArrayList();
            using (DBClassesDataContext dbc = new DBClassesDataContext())
            {
                IEnumerable<PilotClass> ach = (from u in dbc.PilotClasses
                                                     where u.PilotEmail == pilotid
                                                      select u);
                foreach (PilotClass pc in ach)
                {
                    PilotClassDefinition pcd = PilotClassDefinition.getPilotClassDefinition(pc.PilotClassID);
                    if (pcd != null)
                    {
                        classes.Add(pcd);
                    }
                }
            }
            return classes;
        }

        /// <summary>
        /// Get the date when pilot class was achieved
        /// </summary>
        /// <param name="classid"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static DateTime WhenAchieved(Guid classid, String user)
        {
            using (DBClassesDataContext dbc = new DBClassesDataContext())
            {
                PilotClass ach = (from u in dbc.PilotClasses
                                               where u.PilotEmail == user && u.PilotClassID==classid
                                               select u).SingleOrDefault();
                if (ach != null)
                {
                    return ach.DateCompleted;
                }
            }
            return DateTime.MinValue;
        }

        internal static void saveClasses(DBClassesDataContext dc, string email, List<Guid> classes)
        {
            foreach (Guid cls in classes)
            {
                PilotClass pcls = (from u in dc.PilotClasses
                                    where u.PilotEmail == email && u.PilotClassID == cls
                                    select u).SingleOrDefault();
                if (pcls == null)
                {
                    pcls = new PilotClass();
                    pcls.PilotClassID = cls;
                    pcls.PilotEmail = email;
                    pcls.DateCompleted = DateTime.Now;
                    dc.PilotClasses.InsertOnSubmit(pcls);
                }
            }
        }

    }
}


text:
This Puppet module contains configuration for Tiny Tiny RSS.

## Build Status

[![Build Status](https://travis-ci.org/jpds/puppet-ttrss.svg?branch=master)](https://travis-ci.org/jpds/puppet-ttrss)

## Example usage

Parameters for module configuration:
```
class { 'ttrss':
  dbname               => 'ttrss',
  dbusername           => 'ttrss',
  dbpassword           => 'password',
  dbserver             => 'localhost',
  dbtype               => 'pgsql',
  enable_update_daemon => true,
  single_user_mode     => true,
  ttrsspath            => 'http://news.example.com',
}
```

This module only installs and configures Tiny Tiny RSS. It does not install a
web or database server for the application - this is intended to be handled by
their specific module, below is an example Puppet configuration for the latter:

```
class { 'apache':
  default_mods        => false,
  default_confd_files => false,
  mpm_module          => 'prefork',
}

apache::vhost { 'news.example.com':
  servername => 'news.example.com',
  port    => '80',
  docroot => '/usr/share/tt-rss/www',
}

include apache::mod::php

class { 'postgresql::server': }

postgresql::server::db { 'ttrss':
  user     => 'ttrss',
  password => postgresql_password('ttrss', 'password'),
}
```

## License

See [LICENSE](LICENSE) file.


text:
namespace aroma {

void register_Shader(lua_State *l);

class Shader {
public:
	bool linked;
	GLuint program;

	Shader();
	bool add(GLuint type, const char *src);
	bool link();
	void bind();

	GLuint attr_loc(const char* name);
	GLuint uniform_loc(const char* name);

	void set_uniform(const char* name, const Mat4 & matrix);
	void set_uniform(const char* name, const Color & color);
	void set_uniform(const char* name, const float num);
	void set_uniform(const char* name, const GLuint num);

	static int _new(lua_State *l);
	static int _gc(lua_State *l);

	static int _bind(lua_State *l);
	static int _release(lua_State *l);
	static int _uniform(lua_State *l);

	static int _frag(lua_State *l);
	static int _vert(lua_State *l);
};

}


text:
package org.apache.ode.bpel.obj.serde.jacksonhack;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializer;
import com.fasterxml.jackson.databind.ser.BeanSerializerBuilder;

public class TypeBeanSerializerBuilder extends BeanSerializerBuilder{
	 private final static BeanPropertyWriter[] NO_PROPERTIES = new BeanPropertyWriter[0];
	protected TypeBeanSerializerBuilder(BeanSerializerBuilder src) {
		super(src);
	}

	public TypeBeanSerializerBuilder(BeanDescription beanDesc) {
		super(beanDesc);
	}
	@Override
	public TypeBeanSerializer createDummy() {
        return TypeBeanSerializer.createDummy(_beanDesc.getType());
    }

	/**
     * Method called to create {@link BeanSerializer} instance with
     * all accumulated information. Will construct a serializer if we
     * have enough information, or return null if not.
     */
	@Override
    public JsonSerializer<?> build()
    {
        BeanPropertyWriter[] properties;
        // No properties, any getter or object id writer?
        // No real serializer; caller gets to handle
        if (_properties == null || _properties.isEmpty()) {
            if (_anyGetter == null && _objectIdWriter == null) {
                return null;
            }
            properties = NO_PROPERTIES;
        } else {
            properties = _properties.toArray(new BeanPropertyWriter[_properties.size()]);
        }
        return new TypeBeanSerializer(_beanDesc.getType(), this,
                properties, _filteredProperties);
    }
}


text:
"""ASR model parameters."""

# Import ModelParams to ensure that they are added to the global registry.
import lingvo.tasks.asr.params.librispeech  # pylint: disable=unused-import


text:
require "spec_helper"

describe Logidze::History::Type do
  subject { Logidze::History::Type.new }

  describe "#cast" do
    it "handles hash" do
      val = subject.cast("a" => "b")
      expect(val).to be_a(Logidze::History)
      expect(val.data).to eq "a" => "b"
    end

    it "handles nil" do
      expect(subject.cast(nil)).to be_nil
    end
  end

  describe "#deserialize" do
    it "handles valid json" do
      val = subject.deserialize('{"a":"b"}')
      expect(val).to be_a(Logidze::History)
      expect(val.data).to eq "a" => "b"
    end

    it "handles nil" do
      expect(subject.deserialize(nil)).to be_nil
    end
  end

  describe "#serialize" do
    it "handles nil" do
      expect(subject.serialize(nil)).to be_nil
    end

    it "handles history" do
      expect(subject.serialize(Logidze::History.new("a" => "b")))
        .to eq '{"a":"b"}'
    end
  end

  describe "#changed_in_place?" do
    let(:raw_data) { '{"v":1}' }

    it "detects changes", :aggregate_failures do
      val = subject.deserialize(raw_data)
      expect(subject.changed_in_place?(raw_data, val)).to eq false

      val.version = 2
      expect(subject.changed_in_place?(raw_data, val)).to eq true
    end
  end
end


text:
package com.facebook.buck.halide;

import com.facebook.buck.shell.ShellStep;
import com.facebook.buck.step.ExecutionContext;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.nio.file.Path;

public class HalideCompilerStep extends ShellStep {
  // The list of environment variables needed to run our generated compiler.
  private final ImmutableMap<String, String> environment;

  // The list of arguments needed to run our generated compiler.
  private final ImmutableList<String> compilerPrefix;

  // The output directory in which to write the generated shader code.
  private final Path outputDir;

  // The name of the function (or pipeline) to compile.
  private final String funcName;

  // The Halide target string for the target architecture, e.g. "x86-64-osx".
  private final String halideTarget;

  public HalideCompilerStep(
      Path workingDirectory,
      ImmutableMap<String, String> environment,
      ImmutableList<String> compilerPrefix,
      Path outputDir,
      String funcName,
      String halideTarget) {
    super(workingDirectory);
    this.environment = environment;
    this.compilerPrefix = compilerPrefix;
    this.outputDir = outputDir;
    this.funcName = funcName;
    this.halideTarget = halideTarget;
  }

  @Override
  protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    builder.addAll(compilerPrefix);
    builder.add("-h");
    builder.add("-o", outputDir.toString());
    builder.add("-t", halideTarget);

    builder.add(funcName);
    return builder.build();
  }

  @Override
  public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) {
    return environment;
  }

  @Override
  public String getShortName() {
    return "halide";
  }
}


text:
package mesosphere.marathon.core.task.update.impl.steps

import javax.inject.Named

import akka.actor.ActorRef
import com.google.inject.{ Inject, Provider }
import mesosphere.marathon.MarathonSchedulerActor.ScaleApp
import mesosphere.marathon.core.task.{ Task, TaskStateChange, TaskStateOp }
import mesosphere.marathon.core.task.bus.MarathonTaskStatus
import mesosphere.marathon.core.task.bus.TaskChangeObservables.TaskChanged
import mesosphere.marathon.core.task.update.TaskUpdateStep
import org.apache.mesos.Protos.TaskState
import org.slf4j.LoggerFactory

import scala.concurrent.Future

/**
  * Trigger rescale of affected app if a task died or a reserved task timed out.
  */
class ScaleAppUpdateStepImpl @Inject() (
    @Named("schedulerActor") schedulerActorProvider: Provider[ActorRef]) extends TaskUpdateStep {
  private[this] val log = LoggerFactory.getLogger(getClass)
  private[this] lazy val schedulerActor = schedulerActorProvider.get()

  override def name: String = "scaleApp"

  override def processUpdate(taskChanged: TaskChanged): Future[_] = {

    val terminalOrExpungedTask: Option[Task] = {
      (taskChanged.stateOp, taskChanged.stateChange) match {
        // stateOp is a terminal MesosUpdate
        case (TaskStateOp.MesosUpdate(task, MarathonTaskStatus.Terminal(_), _), _) => Some(task)

        // A Lost task that might come back wouldN#t be included in Terminal(_)
        case (TaskStateOp.MesosUpdate(task, MarathonTaskStatus.Lost(_), _), _) => Some(task)

        // stateChange is an expunge (probably because we expunged a timeout reservation)
        case (_, TaskStateChange.Expunge(task)) => Some(task)

        // no ScaleApp needed
        case _ => None
      }
    }

    terminalOrExpungedTask.foreach { task =>
      val appId = task.taskId.runSpecId
      val taskId = task.taskId
      val state = task.mesosStatus.fold(TaskState.TASK_STAGING)(_.getState)
      val reason = task.mesosStatus.fold("")(status => if (status.hasReason) status.getReason.toString else "")
      log.info(s"initiating a scale check for app [$appId] due to [$taskId] $state $reason")
      log.info("schedulerActor: {}", schedulerActor)
      schedulerActor ! ScaleApp(task.taskId.runSpecId)
    }

    Future.successful(())
  }
}


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

<title>Uses of Class javax.net.ssl.SSLServerSocketFactory (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<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

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Class
javax.net.ssl.SSLServerSocketFactory

Packages that use SSLServerSocketFactory

Package
Description

javax.net.ssl

Provides classes for the secure socket package.

Uses of SSLServerSocketFactory in javax.net.ssl

Methods in javax.net.ssl that return SSLServerSocketFactory

Modifier and Type
Method and Description

protected abstract SSLServerSocketFactory
SSLContextSpi.engineGetServerSocketFactory()

Returns a ServerSocketFactory object for
 this context.

SSLServerSocketFactory
SSLContext.getServerSocketFactory()

Returns a ServerSocketFactory object for
 this context.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text: Convocatorias


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

	<!-- ½»Ò×Ô¶³Ì·þÎñ
		<bean id="remoteTradeServiceHessian"
			class="org.springframework.remoting.caucho.HessianServiceExporter">
			<property name="service" ref="remoteTradeService" />
			<property name="serviceInterface"
				value="com.hundsun.network.gates.luosi.qingbo.reomte.service.RemoteTradeService" />
		</bean>

	<bean id="remoteGoldTradeServiceHessian"
		class="org.springframework.remoting.caucho.HessianServiceExporter">
		<property name="service" ref="remoteGoldTradeService" />
		<property name="serviceInterface"
			value="com.hundsun.network.gates.luosi.qingbo.reomte.service.RemoteGoldTradeService" />
	</bean>-->

	<!-- <bean id="remoteAuctionCoreServiceHessian"
		class="org.springframework.remoting.caucho.HessianServiceExporter">
		<property name="service" ref="remoteAuctionCoreService" />
		<property name="serviceInterface"
			value="com.hundsun.network.gates.luosi.qingbo.reomte.service.RemoteAuctionCoreService" />
	</bean> -->

	<!-- ½»Ò×Ô¶³Ì·þÎñ(ÔwangjiangµÄ) -->
	<bean id="remoteTradeServiceHessian"
		class="org.springframework.remoting.caucho.HessianServiceExporter">
		<property name="service" ref="remoteTradeService" />
		<property name="serviceInterface"
			value="com.hundsun.network.gates.luosi.wangjiang.reomte.service.RemoteTradeService" />
	</bean>

	<!-- ÅÄÒ×½»Ò×Ô¶³Ì·þÎñ(ÔwangjiangµÄ) -->
	<bean id="remoteAuctionServiceHessian"
		class="org.springframework.remoting.caucho.HessianServiceExporter">
		<property name="service" ref="remoteAuctionService" />
		<property name="serviceInterface"
			value="com.hundsun.network.gates.luosi.wangjiang.reomte.service.RemoteAuctionService" />
	</bean>
</beans>


text:
class GravatarService
  include Gitlab::CurrentSettings

  def execute(email, size = nil, scale = 2, username: nil)
    return unless current_application_settings.gravatar_enabled?

    identifier = email.presence || username.presence
    return unless identifier

    hash = Digest::MD5.hexdigest(identifier.strip.downcase)
    size = 40 unless size && size > 0

    sprintf gravatar_url,
      hash: hash,
      size: size * scale,
      email: ERB::Util.url_encode(email&.strip || ''),
      username: ERB::Util.url_encode(username&.strip || '')
  end

  def gitlab_config
    Gitlab.config.gitlab
  end

  def gravatar_config
    Gitlab.config.gravatar
  end

  def gravatar_url
    if gitlab_config.https
      gravatar_config.ssl_url
    else
      gravatar_config.plain_url
    end
  end
end


text:
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

using Game.Model;

using Newtonsoft.Json;

using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

namespace Game
{
	public partial class GameWindow : Form
	{
		#region Constants and Fields

		private readonly MaterialMap materialMap;

		private readonly Random rnd = new Random();

		private IScene scene;

		private int h;

		private bool loaded;

		private int w;

		#endregion

		#region Constructors and Destructors
		public GameWindow():this(new GameOptions())
		{

		}

		protected override void OnDeactivate(EventArgs e)
		{
			this.scene.DeactivateControls();
			base.OnDeactivate(e);
		}
		protected override void OnActivated(EventArgs e)
		{
			this.scene.ActivateControls();
			base.OnDeactivate(e);
		}
		public GameWindow(GameOptions options)
		{
			this.InitializeComponent();

			this.materialMap = new MaterialMap();

			this.materialMap[1] = new WorldMaterial { Color = Color4.White, Texture = new Texture(LoadTexture("001")) };
			this.materialMap[2] = new WorldMaterial { Color = Color4.White, Texture = new Texture(LoadTexture("grass")) };
			this.materialMap[3] = new WorldMaterial { Color = Color4.White, Texture = new Texture(LoadTexture("wood")) };
			this.materialMap[4] = new WorldMaterial { Color = Color4.Blue };

			this.spider = LoadModel("spider");
			this.fly = LoadModel("Fly");

			var world = new World(options.VoxelArray, this.materialMap, new Texture(LoadTexture("gradient")));
			this.gameScene = this.scene = new GameScene(world, options) {Spider = spider, Fly = fly};

			this.editorScene = new EditorScene(world,options.VoxelArray);
			this.BringToFront();
			this.Focus();
			this.KeyPreview = true;
			glControl.MouseMove += OnGlControlMouseMove;
		}

		#endregion

		#region Public Methods and Operators

		public void UpdateGame()
		{
			//if (glControl.IsIdle)
			{
				this.glControl.Invalidate();
				//this.RenderScene(this, null);
			}
		}

		#endregion

		#region Methods

		static Model3D LoadModel(string s1)
		{
			using (var s = typeof(GameWindow).Assembly.GetManifestResourceStream("Game.Models." + s1 + ".json"))
			{
				var ms = new MemoryStream();
				s.CopyTo(ms);
				ms.Flush();
				var value = Encoding.UTF8.GetString(ms.ToArray()).Trim((char)65279);
				return (Model3D)JsonConvert.DeserializeObject(value, typeof(Model3D));
			}
		}
		private static Bitmap LoadTexture(string s1)
		{
			using (var s = typeof(GameWindow).Assembly.GetManifestResourceStream("Game.Textures." + s1 + ".jpg"))
			{
				return new Bitmap(s);
			}
		}

		private void ControlLoaded(object sender, EventArgs e)
		{
			this.loaded = true;
			this.glControl.MakeCurrent();
			this.SetupViewport();
		}

		private void GoBack()
		{
			//
		}

		private void GoForward()
		{
			//
		}

		private DateTime? previousTime;

		private IScene gameScene;

		private IScene editorScene;

		private Model3D fly;

		private Model3D spider;

		private void RenderScene(object sender, PaintEventArgs e)
		{
			DateTime now = DateTime.Now;
			if (previousTime != null)
			{
				var dt = now.Subtract(previousTime.Value);
				this.scene.Update(dt);
			}
			previousTime = now;
			if (!this.loaded) // Play nice
			{
				return;
			}
			try
			{
				this.glControl.MakeCurrent();
				GL.ClearColor(new Color4(0, 0x20, 0x40, 0));
				GL.ClearDepth(1.0f);
				GL.DepthMask(true);
				GL.DepthFunc(DepthFunction.Less);
				GL.Viewport(0,0,w,h);
				GL.Clear(ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit);

				this.scene.Render(this.w, this.h);

				GL.Flush();
				this.glControl.SwapBuffers();
			}
			catch (Exception ex)
			{
				this.glControl.Visible = false;
				MessageBox.Show(ex.ToString(), ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void SceneResize(object sender, EventArgs e)
		{
			if (!this.loaded)
			{
				return;
			}
			this.glControl.MakeCurrent();
			this.SetupViewport();
		}

		private void SetupViewport()
		{
			if (!this.loaded)
			{
				return;
			}
			if (GraphicsContext.CurrentContext == null)
			{
				return;
			}
			this.w = Math.Max(1, this.glControl.Width);
			this.h = Math.Max(1, this.glControl.Height);
			// Use all of the glControl painting area
			//this.graphicsContext.SetViewport(0, 0, w, h);

			//this.Camera.AspectRatio = w / (float)h;
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{

			scene.OnKeyDown(e);
			if (!e.Handled)
				base.OnKeyDown(e);
		}
		protected override void OnKeyUp(KeyEventArgs e)
		{
			if (e.KeyCode == Keys.F5)
			{
				if (this.scene == this.gameScene)
				{
					this.scene = this.editorScene;
				}
				else
				{
					this.scene = this.gameScene;
				}
				e.Handled = true;
				return;
			}
			scene.OnKeyUp(e);
			if (!e.Handled)
				base.OnKeyDown(e);
		}

		private void OnGlControlMouseMove(object sender, MouseEventArgs e)
		{
			scene.OnMouseMove(e);
		}

		#endregion
	}
}


text:
#import "InvoiceDataViewController.h"
#import "PayPalInvoiceItem.h"

typedef enum EditInvoiceFields {
	INVOICEFIELD_TAX = 164,
	INVOICEFIELD_SHIPPING,
} EditInvoiceField;

@implementation InvoiceDataViewController

@synthesize invoiceData, delegate;

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

	self.title = @"Edit Invoice";

	CGRect appFrame = [UIScreen mainScreen].applicationFrame;
	UIView *header = [[[UIView alloc] initWithFrame:CGRectMake(0., 0., appFrame.size.width, 1000.)] autorelease];

	UITextField *field;
	field = [self addTextFieldWithLabel:@"Total Tax" tag:INVOICEFIELD_TAX toView:header required:FALSE type:UIKeyboardTypeNumbersAndPunctuation];
	field.text = invoiceData.totalTax == nil ? nil : [self.formatter stringFromNumber:invoiceData.totalTax];
	field = [self addTextFieldWithLabel:@"Total Shipping" tag:INVOICEFIELD_SHIPPING toView:header required:FALSE type:UIKeyboardTypeNumbersAndPunctuation];
	field.text = invoiceData.totalShipping == nil ? nil : [self.formatter stringFromNumber:invoiceData.totalShipping];

	CGRect frame = header.frame;
	frame.size.height = field.frame.origin.y + field.frame.size.height + 10.;
	header.frame = frame;
	self.tableView.tableHeaderView = header;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return invoiceData.invoiceItems.count + 1;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...
	if (indexPath.row < invoiceData.invoiceItems.count) {
		PayPalInvoiceItem *item = (PayPalInvoiceItem *)[invoiceData.invoiceItems objectAtIndex:indexPath.row];

		NSMutableString *buf = [NSMutableString string];
		if (item.name.length > 0) {
			[buf appendString:item.name];
		} else {
			[buf appendFormat:@"Item %d", indexPath.row + 1];
		}
		if (item.itemId.length > 0) {
			[buf appendFormat:@" (%@)", item.itemId];
		}
		cell.textLabel.text = buf;

		buf = [NSMutableString string];
		if (item.itemCount != nil) {
			[buf appendFormat:@"%@ @ ", item.itemCount];
		}
		if (item.itemPrice != nil) {
			[buf appendString:[self.formatter stringFromNumber:item.itemPrice]];
		}
		if (item.totalPrice != nil) {
			if (buf.length > 0) {
				[buf appendString:@" = "];
			}
			[buf appendString:[self.formatter stringFromNumber:item.totalPrice]];
		}
		cell.detailTextLabel.text = buf;

		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	} else {
		cell.textLabel.text = @"Add Item";
		cell.detailTextLabel.text = nil;
		cell.accessoryView = UITableViewCellAccessoryNone;
	}

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	return indexPath.row == invoiceData.invoiceItems.count ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		[invoiceData.invoiceItems removeObjectAtIndex:indexPath.row];
		if (invoiceData.invoiceItems.count == 0) {
			invoiceData.invoiceItems = nil;
		}
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
		if (invoiceData.invoiceItems == nil) {
			invoiceData.invoiceItems = [NSMutableArray array];
		}
		[invoiceData.invoiceItems addObject:[[[PayPalInvoiceItem alloc] init] autorelease]];
		[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	if (indexPath.row < invoiceData.invoiceItems.count) {
		InvoiceItemViewController *eiivc = [[[InvoiceItemViewController alloc] init] autorelease];
		eiivc.invoiceItem = (PayPalInvoiceItem *)[invoiceData.invoiceItems objectAtIndex:indexPath.row];
		eiivc.delegate = self;
		[self.navigationController pushViewController:eiivc animated:TRUE];
	} else {
		[tableView deselectRowAtIndexPath:indexPath animated:TRUE];
		if (invoiceData.invoiceItems == nil) {
			invoiceData.invoiceItems = [NSMutableArray array];
		}
		[invoiceData.invoiceItems addObject:[[[PayPalInvoiceItem alloc] init] autorelease]];
		[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
	}
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc {
	[delegate doneEditingInvoiceData];
	self.invoiceData = nil;
	self.delegate = nil;
    [super dealloc];
}

#pragma mark -
#pragma mark UITextFieldDelegate Methods

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	switch(textField.tag){
		case INVOICEFIELD_TAX:
			invoiceData.totalTax = [self decimalNumberForField:textField range:range string:string];
			break;
		case INVOICEFIELD_SHIPPING:
			invoiceData.totalShipping = [self decimalNumberForField:textField range:range string:string];
			break;
	}
	return FALSE;
}

#pragma mark -
#pragma mark EditInvoiceItemDelegate Methods

- (void)doneEditingInvoiceItem:(PayPalInvoiceItem *)item {
	NSUInteger index = [invoiceData.invoiceItems indexOfObject:item];
	if (index != NSNotFound) {
		[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
	}
}

@end


text:
<?php

/**
 * Detect whether request should be debugged
 *
 * @package Minify
 * @author Stephen Clay <steve@mrclay.org>
 */
class Minify_DebugDetector {
    public static function shouldDebugRequest(Minify_Env $env)
    {
        if ($env->get('debug') !== null) {
            return true;
        }
        $cookieValue = $env->cookie('minifyDebug');
        if ($cookieValue) {
            foreach (preg_split('/\\s+/', $cookieValue) as $debugUri) {
                $pattern = '@' . preg_quote($debugUri, '@') . '@i';
                $pattern = str_replace(array('\\*', '\\?'), array('.*', '.'), $pattern);
                if (preg_match($pattern, $env->getRequestUri())) {
                    return true;
                }
            }
        }

        return false;
    }
}


text:
package net.buycraft.plugin.sponge.logging;

import net.buycraft.plugin.sponge.BuycraftPlugin;

import java.util.logging.Level;

public class LoggerUtils {
    private final BuycraftPlugin plugin;

    public LoggerUtils(final BuycraftPlugin plugin) {
        this.plugin = plugin;
    }

    public void log(Level level, String message) {
        log(level, message, null);
    }

    public void log(Level level, String message, Throwable e) {
        plugin.getLogger().info(message, e);
    }
}


text:
package org.adl.datamodels;

/**
 * Encapsulates one delimiter found in a dot notation bound string defined by a
 * value token (DMToken).
 *
 * Filename: RequestDelimiter.java

 *
 * Description:

 *
 * Design Issues:

 *
 * Implementation Issues:

 *
 * Known Problems:

 *
 * Side Effects:

 *
 * References:

 *

 *
SCORM 2004
 *

 *
 * @author ADL Technical Team
 */
public class RequestDelimiter {

	/**
	 * Describes the name of this delimiter.
	 */
	private String mName = null;

	/**
	 * Describes the value of this delimiter.
	 */
	private String mValue = null;

	/**
	 * Creates one delimter from a dot-notation bound data model request.  This
	 * method may throw the following Java RuntimeExceptions:
	 *

	 *
NullPointerException: If the data is omitted

	 *
IllegalArgumentException:  If the element name or value
	 *       is improperly formatted

	 *

	 *
	 * @param iName  The name of the delimiter
	 *
	 * @param iValue The value of the delimiter
	 *
	 */
	public RequestDelimiter(String iName, String iValue) {
		// Make sure none of the parameters are null
		if (iName == null || iValue == null)
			throw new NullPointerException("Delimiter not specified");

		// Make sure the name parameters has non-zero length
		if (iName.length() == 0)
			throw new IllegalArgumentException("Delimiter name is blank");

		mName = iName;
		mValue = iValue;
	}

	/**
	 * Describes the name of this delimiter.
	 *
	 * @return The name of this delimter.
	 */
	public String getName() {
		return mName;
	}

	/**
	 * Describes the value of this delimter.
	 *
	 * @return The value of this delimiter.
	 */
	public String getValue() {
		return mValue;
	}

	/**
	 * Provides the dot-notation binding for this delimiter.
	 *
	 * @return The dot-notation String corresponding to this
	 *         delimiter.
	 */
	public String showDotNotation() {
		String dot = "";

		dot = "{" + mName + "=" + mValue + "}";

		return dot;
	}

} // end RequestDelimiter


text:
""" Display file contents in hexadecimal """

import argparse
from .base import base_parser, LogSetup
from ..utils.hexdump import hexdump as dump

parser = argparse.ArgumentParser(description=__doc__, parents=[base_parser])
parser.add_argument(
    "file",
    metavar="file",
    type=argparse.FileType("rb"),
    help="File to dump contents of",
)
parser.add_argument(
    "--width", default=16, type=int, help="Width of the hexdump."
)

def hexdump(args=None):
    """ Display file contents in hexadecimal """
    args = parser.parse_args(args)
    with LogSetup(args):
        contents = args.file.read()
        args.file.close()
        dump(contents, width=args.width)

if __name__ == "__main__":
    hexdump()


text:
 Newsletter

Sign up to our newsletter to receive the latest News from
                {{ config('app.name') }}.

            <form id="form-newsletter-subscribe" method="post" action="/api/newsletter/subscribe">
                {!! csrf_field() !!}

                        Full Name
                        <input type="text" name="fullname" class="form-control d-block" placeholder="Full Name">

                        Email Address
                        <input type="text" name="email" class="form-control d-block" placeholder="Email Address">

                        <button type="submit" class="btn btn-primary btn-block btn-ajax-submit">Sign up
                        </button>

Please
                            Complete the form

            </form>

@section('scripts')
    @parent

@endsection


text:
package org.wikiwatershed.mmw.geoprocessing

import geotrellis.proj4.{CRS, ConusAlbers, LatLng, WebMercator}
import geotrellis.raster._
import geotrellis.raster.rasterize._
import geotrellis.spark._
import geotrellis.spark.io._
import geotrellis.spark.io.s3._
import geotrellis.vector._
import geotrellis.vector.io._

import com.typesafe.config.Config
import org.apache.spark.SparkContext
import spray.json._

import scala.collection.JavaConverters._
import scala.collection.mutable

/**
  * Collection of common utilities to be used by SparkJobs.
  */
trait JobUtils {

  /**
    * Transform the incoming GeoJSON into a [[MultiPolygon]] in the
    * destination CRS.
    *
    * @param   geoJson  The incoming geometry
    * @param   srcCRS   The CRS that the incoming geometry is in
    * @param   destCRS  The CRS that the outgoing geometry should be in
    * @return           A MultiPolygon
    */
  def parseGeometry(geoJson: String, srcCRS: CRS, destCRS: CRS): MultiPolygon = {
    geoJson.parseJson.convertTo[Geometry] match {
      case p: Polygon => MultiPolygon(p.reproject(srcCRS, destCRS))
      case mp: MultiPolygon => mp.reproject(srcCRS, destCRS)
      case _ => MultiPolygon()
    }
  }

  /**
    * Transform incoming GeoJSON into a [[MultiLine]] in the destination CRS.
    * Same as [[parseGeometry()]] but for MultiLines instead.
    *
    * @param   geoJson  The incoming geometry
    * @param   srcCRS   The CRS that the incoming geometry is in
    * @param   destCRS  The CRS that the outgoing geometry should be in
    * @return           A MultiLine
    */
  def toMultiLine(geoJson: String, srcCRS: CRS, destCRS: CRS): MultiLine = {
    geoJson.parseJson.convertTo[Geometry] match {
      case l: Line => MultiLine(l.reproject(srcCRS, destCRS))
      case ml: MultiLine => ml.reproject(srcCRS, destCRS)
      case _ => MultiLine()
    }
  }

  /**
    * Fetch a particular layer from the catalog, restricted to the
    * given extent, and return a [[TileLayerRDD]] of the result.
    *
    * @param   catalog  The S3 location from which the data should be read
    * @param   layerId  The layer that should be read
    * @param   extent   The extent (subset) of the layer that should be read
    * @return           An RDD of [[SpatialKey]]s
    */
  def queryAndCropLayer(
    catalog: S3LayerReader,
    layerId: LayerId,
    extent: Extent
  ): TileLayerRDD[SpatialKey] = {
    catalog.query[SpatialKey, Tile, TileLayerMetadata[SpatialKey]](layerId)
      .where(Intersects(extent))
      .result
  }

  /**
    * Return an [[S3LayerReader]] object to read from the catalog
    * directory in the azavea datahub.
    *
    * @return  An S3LayerReader object
    */
  def catalog(sc: SparkContext): S3LayerReader =
    catalog("datahub-catalogs-us-east-1", "")(sc)

  /**
    * Take a bucket and a catalog, and return an [[S3LayerReader]]
    * object to read from it.
    *
    * @param   bucket    The name of the S3 bucket
    * @param   rootPath  The name of the catalog (child of the root directory) in the bucket
    * @return            An S3LayerReader object
    */
  def catalog(bucket: String, rootPath: String)(implicit sc: SparkContext): S3LayerReader = {
    val attributeStore = new S3AttributeStore(bucket, rootPath)
    val catalog = new S3LayerReader(attributeStore)

    catalog
  }

  /**
    * For a given config, return a function that can find the value of a key
    * if it exists in the config.
    *
    * @param   config    The config containing keys
    * @return            A function String => Option[String] that takes a key and returns its value if it exists, else None
    */
  def getOptionalFn(config: Config) = (key: String) => {
    config.hasPath(key) match {
      case true => Option(config.getString(key))
      case false => None
    }
  }

  /**
    * For a given config and CRS key, return one of several recognized
    * [[geotrellis.proj4.CRS]]s, or raise an error.
    *
    * @param  config  The config
    * @param  key     The key (e.g. "input.rasterCRS")
    */
  def getCRS(config: Config, key: String) = {
    config.getString(key) match {
      case "LatLng" => LatLng
      case "WebMercator" => WebMercator
      case "ConusAlbers" => ConusAlbers
      case s: String => throw new Exception(s"Unknown CRS: $s")
    }
  }

  /**
    * Returns a join of a sequence of raster layers, containing between 1
    * and 3 layers.
    *
    * @param   rasterLayers  The list of layers
    * @return                Joined RDD with a list of tiles, corresponding to each raster in the list, matching a spatial key
    */
  def joinRasters(rasterLayers: Seq[TileLayerRDD[SpatialKey]]) = {
    rasterLayers.length match {
      case 1 =>
        rasterLayers.head
          .map({ case (k, v) => (k, List(v)) })
      case 2 =>
        rasterLayers.head.join(rasterLayers.tail.head)
          .map({ case (k, (v1, v2)) => (k, List(v1, v2)) })
      case 3 =>
        rasterLayers.head.join(rasterLayers.tail.head).join(rasterLayers.tail.tail.head)
          .map({ case (k, ((v1, v2), v3)) => (k, List(v1, v2, v3)) })

      case 0 => throw new Exception("At least 1 raster must be specified")
      case _ => throw new Exception("At most 3 rasters can be specified")
    }
  }

  /**
    * Given a layer, a key, a tile, and a sequence of MultiPolygons, returns
    * a list of distinct pixels present in all polygons clipped to an extent
    * corresponding to the key and tile.
    *
    * @param   layer         The [[TileLayerRDD]] to clip
    * @param   key           The [[SpatialKey]] to transform extent to
    * @param   tile          The [[Tile]] to calculate raster extent from
    * @param   multiPolygons The list of polygons
    * @return                List of distinct pixels
    */
  def getDistinctPixels(layer: TileLayerRDD[SpatialKey], key: SpatialKey, tile: Tile, multiPolygons: Seq[MultiPolygon]) = {
    val extent = layer.metadata.mapTransform(key)
    val rasterExtent = RasterExtent(extent, tile.cols, tile.rows)

    val pixels = mutable.ListBuffer.empty[(Int, Int)]
    val cb = new Callback {
      def apply(col: Int, row: Int): Unit = {
        val pixel = (col, row)
        pixels += pixel
      }
    }

    multiPolygons.foreach({ multiPolygon =>
      multiPolygon & extent match {
        case PolygonResult(p) =>
          Rasterizer.foreachCellByPolygon(p, rasterExtent)(cb)
        case MultiPolygonResult(mp) =>
          mp.polygons.foreach({ p =>
            Rasterizer.foreachCellByPolygon(p, rasterExtent)(cb)
          })

        case _ =>
      }
    })

    pixels.distinct
  }

  /**
    * Convenience method for parsing config for various RasterGrouped operations
    */
  def parseGroupedConfig(config: Config) = {
    val crs: String => geotrellis.proj4.CRS = getCRS(config, _)

    val zoom = config.getInt("input.zoom")
    val rasterCRS = crs("input.rasterCRS")
    val polygonCRS = crs("input.polygonCRS")
    val rasterLayerIds = config.getStringList("input.rasters").asScala.map({ str => LayerId(str, zoom) })
    val polygon = config.getStringList("input.polygon").asScala.map({
      str => parseGeometry(str, polygonCRS, rasterCRS).buffer(0).asMultiPolygon.get
    })

    val targetLayerId: Option[LayerId] = {
      if (config.hasPath("input.targetRaster"))
        Some(LayerId(config.getString("input.targetRaster"), zoom))
      else
        None
    }

    (rasterLayerIds, targetLayerId, polygon)
  }

  /**
    * Convenience method for parsing config for various RasterLinesJoin operations
    */
  def parseLinesJoinConfig(config: Config) = {
    val crs: String => geotrellis.proj4.CRS = getCRS(config, _)

    val zoom = config.getInt("input.zoom")
    val rasterCRS = crs("input.rasterCRS")
    val polygonCRS = crs("input.polygonCRS")
    val linesCRS = crs("input.vectorCRS")
    val rasterLayerIds = config.getStringList("input.rasters").asScala.map({ str => LayerId(str, zoom) })
    val polygon = config.getStringList("input.polygon").asScala.map({
      str => parseGeometry(str, polygonCRS, rasterCRS).buffer(0).asMultiPolygon.get
    })
    val lines = config.getStringList("input.vector").asScala.map({ str => toMultiLine(str, linesCRS, rasterCRS) })

    (rasterLayerIds, lines, polygon)
  }

  /**
    * Set of methods for easy processing of parameters
    */
  def toLayers(rasterLayerIds: Seq[LayerId], polygon: Seq[MultiPolygon], sc: SparkContext) = {
    val extent = GeometryCollection(polygon).envelope
    val rasterLayers = rasterLayerIds.map({ rasterLayerId =>
      queryAndCropLayer(catalog(sc), rasterLayerId, extent)
    })

    rasterLayers
  }

  def toLayers(rasterLayerIds: Seq[LayerId], targetLayerId: LayerId, polygon: Seq[MultiPolygon], sc: SparkContext) = {
    val extent = GeometryCollection(polygon).envelope
    val rasterLayers = rasterLayerIds.map({ rasterLayerId =>
      queryAndCropLayer(catalog(sc), rasterLayerId, extent)
    })
    val targetLayer = queryAndCropLayer(catalog(sc), targetLayerId, extent)

    (rasterLayers, targetLayer)
  }

  def toLayers(targetLayerId: LayerId, polygon: Seq[MultiPolygon], sc: SparkContext) = {
    val extent = GeometryCollection(polygon).envelope
    val targetLayer = queryAndCropLayer(catalog(sc), targetLayerId, extent)

    targetLayer
  }
}


text:
START_ATF_NAMESPACE
    typedef _PRINTER_NOTIFY_INFO *LPPRINTER_NOTIFY_INFO;
END_ATF_NAMESPACE