text:
import time
import functools

from eventlet import spawn_n, GreenPile, Timeout
from eventlet.queue import Queue, Empty, Full
from eventlet.timeout import Timeout

from swift.common.utils import normalize_timestamp, TRUE_VALUES, public
from swift.common.bufferedhttp import http_connect
from swift.common.constraints import MAX_ACCOUNT_NAME_LENGTH
from swift.common.exceptions import ChunkReadTimeout, ConnectionTimeout
from swift.common.http import is_informational, is_success, is_redirection, \
    is_server_error, HTTP_OK, HTTP_PARTIAL_CONTENT, HTTP_MULTIPLE_CHOICES, \
    HTTP_BAD_REQUEST, HTTP_NOT_FOUND, HTTP_SERVICE_UNAVAILABLE, \
    HTTP_INSUFFICIENT_STORAGE
from swift.common.swob import Request, Response, status_map

def update_headers(response, headers):
    """
    Helper function to update headers in the response.

    :param response: swob.Response object
    :param headers: dictionary headers
    """
    if hasattr(headers, 'items'):
        headers = headers.items()
    for name, value in headers:
        if name == 'etag':
            response.headers[name] = value.replace('"', '')
        elif name not in ('date', 'content-length', 'content-type',
                          'connection', 'x-put-timestamp', 'x-delete-after'):
            response.headers[name] = value

def source_key(resp):
    """
    Provide the timestamp of the swift http response as a floating
    point value.  Used as a sort key.

    :param resp: httplib response object
    """
    return float(resp.getheader('x-put-timestamp') or
                 resp.getheader('x-timestamp') or 0)

def delay_denial(func):
    """
    Decorator to declare which methods should have any swift.authorize call
    delayed. This is so the method can load the Request object up with
    additional information that may be needed by the authorization system.

    :param func: function for which authorization will be delayed
    """
    func.delay_denial = True

    @functools.wraps(func)
    def wrapped(*a, **kw):
        return func(*a, **kw)
    return wrapped

def get_account_memcache_key(account):
    return 'account/%s' % account

def get_container_memcache_key(account, container):
    return 'container/%s/%s' % (account, container)

class Controller(object):
    """Base WSGI controller class for the proxy"""
    server_type = 'Base'

    # Ensure these are all lowercase
    pass_through_headers = []

    def __init__(self, app):
        self.account_name = None
        self.app = app
        self.trans_id = '-'

    def transfer_headers(self, src_headers, dst_headers):

        st = self.server_type.lower()
        x_remove = 'x-remove-%s-meta-' % st
        x_remove_read = 'x-remove-%s-read' % st
        x_remove_write = 'x-remove-%s-write' % st
        x_meta = 'x-%s-meta-' % st
        dst_headers.update((k.lower().replace('-remove', '', 1), '')
                           for k in src_headers
                           if k.lower().startswith(x_remove) or
                           k.lower() in (x_remove_read, x_remove_write))

        dst_headers.update((k.lower(), v)
                           for k, v in src_headers.iteritems()
                           if k.lower() in self.pass_through_headers or
                           k.lower().startswith(x_meta))

    def error_increment(self, node):
        """
        Handles incrementing error counts when talking to nodes.

        :param node: dictionary of node to increment the error count for
        """
        node['errors'] = node.get('errors', 0) + 1
        node['last_error'] = time.time()

    def error_occurred(self, node, msg):
        """
        Handle logging, and handling of errors.

        :param node: dictionary of node to handle errors for
        :param msg: error message
        """
        self.error_increment(node)
        self.app.logger.error(_('%(msg)s %(ip)s:%(port)s'),
                              {'msg': msg, 'ip': node['ip'],
                              'port': node['port']})

    def exception_occurred(self, node, typ, additional_info):
        """
        Handle logging of generic exceptions.

        :param node: dictionary of node to log the error for
        :param typ: server type
        :param additional_info: additional information to log
        """
        self.app.logger.exception(
            _('ERROR with %(type)s server %(ip)s:%(port)s/%(device)s re: '
              '%(info)s'),
            {'type': typ, 'ip': node['ip'], 'port': node['port'],
             'device': node['device'], 'info': additional_info})

    def error_limited(self, node):
        """
        Check if the node is currently error limited.

        :param node: dictionary of node to check
        :returns: True if error limited, False otherwise
        """
        now = time.time()
        if not 'errors' in node:
            return False
        if 'last_error' in node and node['last_error'] < \
                now - self.app.error_suppression_interval:
            del node['last_error']
            if 'errors' in node:
                del node['errors']
            return False
        limited = node['errors'] > self.app.error_suppression_limit
        if limited:
            self.app.logger.debug(
                _('Node error limited %(ip)s:%(port)s (%(device)s)'), node)
        return limited

    def error_limit(self, node):
        """
        Mark a node as error limited.

        :param node: dictionary of node to error limit
        """
        node['errors'] = self.app.error_suppression_limit + 1
        node['last_error'] = time.time()

    def account_info(self, account, autocreate=False):
        """
        Get account information, and also verify that the account exists.

        :param account: name of the account to get the info for
        :returns: tuple of (account partition, account nodes, container_count)
                  or (None, None, None) if it does not exist
        """
        partition, nodes = self.app.account_ring.get_nodes(account)
        # 0 = no responses, 200 = found, 404 = not found, -1 = mixed responses
        if self.app.memcache:
            cache_key = get_account_memcache_key(account)
            cache_value = self.app.memcache.get(cache_key)
            if not isinstance(cache_value, dict):
                result_code = cache_value
                container_count = 0
            else:
                result_code = cache_value['status']
                container_count = cache_value['container_count']
            if result_code == HTTP_OK:
                return partition, nodes, container_count
            elif result_code == HTTP_NOT_FOUND and not autocreate:
                return None, None, None
        result_code = 0
        container_count = 0
        attempts_left = len(nodes)
        path = '/%s' % account
        headers = {'x-trans-id': self.trans_id, 'Connection': 'close'}
        iternodes = self.iter_nodes(partition, nodes, self.app.account_ring)
        while attempts_left > 0:
            try:
                node = iternodes.next()
            except StopIteration:
                break
            attempts_left -= 1
            try:
                with ConnectionTimeout(self.app.conn_timeout):
                    conn = http_connect(node['ip'], node['port'],
                                        node['device'], partition, 'HEAD',
                                        path, headers)
                with Timeout(self.app.node_timeout):
                    resp = conn.getresponse()
                    body = resp.read()
                    if is_success(resp.status):
                        result_code = HTTP_OK
                        container_count = int(
                            resp.getheader('x-account-container-count') or 0)
                        break
                    elif resp.status == HTTP_NOT_FOUND:
                        if result_code == 0:
                            result_code = HTTP_NOT_FOUND
                        elif result_code != HTTP_NOT_FOUND:
                            result_code = -1
                    elif resp.status == HTTP_INSUFFICIENT_STORAGE:
                        self.error_limit(node)
                        continue
                    else:
                        result_code = -1
            except (Exception, Timeout):
                self.exception_occurred(node, _('Account'),
                                        _('Trying to get account info for %s')
                                        % path)
        if result_code == HTTP_NOT_FOUND and autocreate:
            if len(account) > MAX_ACCOUNT_NAME_LENGTH:
                return None, None, None
            headers = {'X-Timestamp': normalize_timestamp(time.time()),
                       'X-Trans-Id': self.trans_id,
                       'Connection': 'close'}
            resp = self.make_requests(Request.blank('/v1' + path),
                                      self.app.account_ring, partition, 'PUT',
                                      path, [headers] * len(nodes))
            if not is_success(resp.status_int):
                self.app.logger.warning('Could not autocreate account %r' %
                                        path)
                return None, None, None
            result_code = HTTP_OK
        if self.app.memcache and result_code in (HTTP_OK, HTTP_NOT_FOUND):
            if result_code == HTTP_OK:
                cache_timeout = self.app.recheck_account_existence
            else:
                cache_timeout = self.app.recheck_account_existence * 0.1
            self.app.memcache.set(cache_key,
                                  {'status': result_code,
                                  'container_count': container_count},
                                  timeout=cache_timeout)
        if result_code == HTTP_OK:
            return partition, nodes, container_count
        return None, None, None

    def container_info(self, account, container, account_autocreate=False):
        """
        Get container information and thusly verify container existance.
        This will also make a call to account_info to verify that the
        account exists.

        :param account: account name for the container
        :param container: container name to look up
        :returns: dict containing at least container partition ('partition'),
                  container nodes ('containers'), container read
                  acl ('read_acl'), container write acl ('write_acl'),
                  and container sync key ('sync_key').
                  Values are set to None if the container does not exist.
        """
        part, nodes = self.app.container_ring.get_nodes(account, container)
        path = '/%s/%s' % (account, container)
        container_info = {'status': 0, 'read_acl': None,
                          'write_acl': None, 'sync_key': None,
                          'count': None, 'bytes': None,
                          'versions': None, 'partition': None,
                          'nodes': None}
        if self.app.memcache:
            cache_key = get_container_memcache_key(account, container)
            cache_value = self.app.memcache.get(cache_key)
            if isinstance(cache_value, dict):
                if 'container_size' in cache_value:
                    cache_value['count'] = cache_value['container_size']
                if is_success(cache_value['status']):
                    container_info.update(cache_value)
                    container_info['partition'] = part
                    container_info['nodes'] = nodes
                return container_info
        if not self.account_info(account, autocreate=account_autocreate)[1]:
            return container_info
        attempts_left = len(nodes)
        headers = {'x-trans-id': self.trans_id, 'Connection': 'close'}
        for node in self.iter_nodes(part, nodes, self.app.container_ring):
            try:
                with ConnectionTimeout(self.app.conn_timeout):
                    conn = http_connect(node['ip'], node['port'],
                                        node['device'], part, 'HEAD',
                                        path, headers)
                with Timeout(self.app.node_timeout):
                    resp = conn.getresponse()
                    body = resp.read()
                if is_success(resp.status):
                    container_info.update({
                        'status': HTTP_OK,
                        'read_acl': resp.getheader('x-container-read'),
                        'write_acl': resp.getheader('x-container-write'),
                        'sync_key': resp.getheader('x-container-sync-key'),
                        'count': resp.getheader('x-container-object-count'),
                        'bytes': resp.getheader('x-container-bytes-used'),
                        'versions': resp.getheader('x-versions-location')})
                    break
                elif resp.status == HTTP_NOT_FOUND:
                    container_info['status'] = HTTP_NOT_FOUND
                else:
                    container_info['status'] = -1
                    if resp.status == HTTP_INSUFFICIENT_STORAGE:
                        self.error_limit(node)
            except (Exception, Timeout):
                self.exception_occurred(
                    node, _('Container'),
                    _('Trying to get container info for %s') % path)
            attempts_left -= 1
            if attempts_left <= 0:
                break
        if self.app.memcache:
            if container_info['status'] == HTTP_OK:
                self.app.memcache.set(
                    cache_key, container_info,
                    timeout=self.app.recheck_container_existence)
            elif container_info['status'] == HTTP_NOT_FOUND:
                self.app.memcache.set(
                    cache_key, container_info,
                    timeout=self.app.recheck_container_existence * 0.1)
        if container_info['status'] == HTTP_OK:
            container_info['partition'] = part
            container_info['nodes'] = nodes
        return container_info

    def iter_nodes(self, partition, nodes, ring):
        """
        Node iterator that will first iterate over the normal nodes for a
        partition and then the handoff partitions for the node.

        :param partition: partition to iterate nodes for
        :param nodes: list of node dicts from the ring
        :param ring: ring to get handoff nodes from
        """
        for node in nodes:
            if not self.error_limited(node):
                yield node
        handoffs = 0
        for node in ring.get_more_nodes(partition):
            if not self.error_limited(node):
                handoffs += 1
                if self.app.log_handoffs:
                    self.app.logger.increment('handoff_count')
                    self.app.logger.warning(
                        'Handoff requested (%d)' % handoffs)
                    if handoffs == len(nodes):
                        self.app.logger.increment('handoff_all_count')
                yield node

    def _make_request(self, nodes, part, method, path, headers, query,
                      logger_thread_locals):
        self.app.logger.thread_locals = logger_thread_locals
        for node in nodes:
            try:
                with ConnectionTimeout(self.app.conn_timeout):
                    conn = http_connect(node['ip'], node['port'],
                                        node['device'], part, method, path,
                                        headers=headers, query_string=query)
                    conn.node = node
                with Timeout(self.app.node_timeout):
                    resp = conn.getresponse()
                    if not is_informational(resp.status) and \
                            not is_server_error(resp.status):
                        return resp.status, resp.reason, resp.read()
                    elif resp.status == HTTP_INSUFFICIENT_STORAGE:
                        self.error_limit(node)
            except (Exception, Timeout):
                self.exception_occurred(node, self.server_type,
                                        _('Trying to %(method)s %(path)s') %
                                        {'method': method, 'path': path})

    def make_requests(self, req, ring, part, method, path, headers,
                      query_string=''):
        """
        Sends an HTTP request to multiple nodes and aggregates the results.
        It attempts the primary nodes concurrently, then iterates over the
        handoff nodes as needed.

        :param headers: a list of dicts, where each dict represents one
                        backend request that should be made.
        :returns: a swob.Response object
        """
        start_nodes = ring.get_part_nodes(part)
        nodes = self.iter_nodes(part, start_nodes, ring)
        pile = GreenPile(len(start_nodes))
        for head in headers:
            pile.spawn(self._make_request, nodes, part, method, path,
                       head, query_string, self.app.logger.thread_locals)
        response = [resp for resp in pile if resp]
        while len(response) < len(start_nodes):
            response.append((HTTP_SERVICE_UNAVAILABLE, '', ''))
        statuses, reasons, bodies = zip(*response)
        return self.best_response(req, statuses, reasons, bodies,
                                  '%s %s' % (self.server_type, req.method))

    def best_response(self, req, statuses, reasons, bodies, server_type,
                      etag=None):
        """
        Given a list of responses from several servers, choose the best to
        return to the API.

        :param req: swob.Request object
        :param statuses: list of statuses returned
        :param reasons: list of reasons for each status
        :param bodies: bodies of each response
        :param server_type: type of server the responses came from
        :param etag: etag
        :returns: swob.Response object with the correct status, body, etc. set
        """
        resp = Response(request=req)
        if len(statuses):
            for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
                hstatuses = \
                    [s for s in statuses if hundred <= s < hundred + 100]
                if len(hstatuses) > len(statuses) / 2:
                    status = max(hstatuses)
                    status_index = statuses.index(status)
                    resp.status = '%s %s' % (status, reasons[status_index])
                    resp.body = bodies[status_index]
                    resp.content_type = 'text/html'
                    if etag:
                        resp.headers['etag'] = etag.strip('"')
                    return resp
        self.app.logger.error(_('%(type)s returning 503 for %(statuses)s'),
                              {'type': server_type, 'statuses': statuses})
        resp.status = '503 Internal Server Error'
        return resp

    @public
    def GET(self, req):
        """Handler for HTTP GET requests."""
        return self.GETorHEAD(req)

    @public
    def HEAD(self, req):
        """Handler for HTTP HEAD requests."""
        return self.GETorHEAD(req)

    def _make_app_iter_reader(self, node, source, queue, logger_thread_locals):
        """
        Reads from the source and places data in the queue. It expects
        something else be reading from the queue and, if nothing does within
        self.app.client_timeout seconds, the process will be aborted.

        :param node: The node dict that the source is connected to, for
                     logging/error-limiting purposes.
        :param source: The httplib.Response object to read from.
        :param queue: The eventlet.queue.Queue to place read source data into.
        :param logger_thread_locals: The thread local values to be set on the
                                     self.app.logger to retain transaction
                                     logging information.
        """
        self.app.logger.thread_locals = logger_thread_locals
        success = True
        try:
            try:
                while True:
                    with ChunkReadTimeout(self.app.node_timeout):
                        chunk = source.read(self.app.object_chunk_size)
                    if not chunk:
                        break
                    queue.put(chunk, timeout=self.app.client_timeout)
            except Full:
                self.app.logger.warn(
                    _('Client did not read from queue within %ss') %
                    self.app.client_timeout)
                self.app.logger.increment('client_timeouts')
                success = False
            except (Exception, Timeout):
                self.exception_occurred(node, _('Object'),
                                        _('Trying to read during GET'))
                success = False
        finally:
            # Ensure the queue getter gets a terminator.
            queue.resize(2)
            queue.put(success)
            # Close-out the connection as best as possible.
            if getattr(source, 'swift_conn', None):
                self.close_swift_conn(source)

    def _make_app_iter(self, node, source):
        """
        Returns an iterator over the contents of the source (via its read
        func).  There is also quite a bit of cleanup to ensure garbage
        collection works and the underlying socket of the source is closed.

        :param source: The httplib.Response object this iterator should read
                       from.
        :param node: The node the source is reading from, for logging purposes.
        """
        try:
            # Spawn reader to read from the source and place in the queue.
            # We then drop any reference to the source or node, for garbage
            # collection purposes.
            queue = Queue(1)
            spawn_n(self._make_app_iter_reader, node, source, queue,
                    self.app.logger.thread_locals)
            source = node = None
            while True:
                chunk = queue.get(timeout=self.app.node_timeout)
                if isinstance(chunk, bool):  # terminator
                    success = chunk
                    if not success:
                        raise Exception(_('Failed to read all data'
                                          ' from the source'))
                    break
                yield chunk
        except Empty:
            raise ChunkReadTimeout()
        except (GeneratorExit, Timeout):
            self.app.logger.warn(_('Client disconnected on read'))
        except Exception:
            self.app.logger.exception(_('Trying to send to client'))
            raise

    def close_swift_conn(self, src):
        try:
            src.swift_conn.close()
        except Exception:
            pass
        src.swift_conn = None
        try:
            while src.read(self.app.object_chunk_size):
                pass
        except Exception:
            pass
        try:
            src.close()
        except Exception:
            pass

    def GETorHEAD_base(self, req, server_type, partition, nodes, path,
                       attempts):
        """
        Base handler for HTTP GET or HEAD requests.

        :param req: swob.Request object
        :param server_type: server type
        :param partition: partition
        :param nodes: nodes
        :param path: path for the request
        :param attempts: number of attempts to try
        :returns: swob.Response object
        """
        statuses = []
        reasons = []
        bodies = []
        sources = []
        newest = req.headers.get('x-newest', 'f').lower() in TRUE_VALUES
        nodes = iter(nodes)
        while len(statuses) < attempts:
            try:
                node = nodes.next()
            except StopIteration:
                break
            if self.error_limited(node):
                continue
            try:
                with ConnectionTimeout(self.app.conn_timeout):
                    headers = dict(req.headers)
                    headers['Connection'] = 'close'
                    conn = http_connect(
                        node['ip'], node['port'], node['device'], partition,
                        req.method, path, headers=headers,
                        query_string=req.query_string)
                with Timeout(self.app.node_timeout):
                    possible_source = conn.getresponse()
                    # See NOTE: swift_conn at top of file about this.
                    possible_source.swift_conn = conn
            except (Exception, Timeout):
                self.exception_occurred(
                    node, server_type, _('Trying to %(method)s %(path)s') %
                    {'method': req.method, 'path': req.path})
                continue
            if is_success(possible_source.status) or \
                    is_redirection(possible_source.status):
                # 404 if we know we don't have a synced copy
                if not float(possible_source.getheader('X-PUT-Timestamp', 1)):
                    statuses.append(HTTP_NOT_FOUND)
                    reasons.append('')
                    bodies.append('')
                    self.close_swift_conn(possible_source)
                else:
                    statuses.append(possible_source.status)
                    reasons.append(possible_source.reason)
                    bodies.append('')
                    sources.append(possible_source)
                    if not newest:  # one good source is enough
                        break
            else:
                statuses.append(possible_source.status)
                reasons.append(possible_source.reason)
                bodies.append(possible_source.read())
                if possible_source.status == HTTP_INSUFFICIENT_STORAGE:
                    self.error_limit(node)
                elif is_server_error(possible_source.status):
                    self.error_occurred(node, _('ERROR %(status)d %(body)s '
                                                'From %(type)s Server') %
                                        {'status': possible_source.status,
                                         'body': bodies[-1][:1024],
                                         'type': server_type})
        if sources:
            sources.sort(key=source_key)
            source = sources.pop()
            for src in sources:
                self.close_swift_conn(src)
            res = Response(request=req, conditional_response=True)
            if req.method == 'GET' and \
                    source.status in (HTTP_OK, HTTP_PARTIAL_CONTENT):
                res.app_iter = self._make_app_iter(node, source)
                # See NOTE: swift_conn at top of file about this.
                res.swift_conn = source.swift_conn
            res.status = source.status
            update_headers(res, source.getheaders())
            if not res.environ:
                res.environ = {}
            res.environ['swift_x_timestamp'] = \
                source.getheader('x-timestamp')
            res.accept_ranges = 'bytes'
            res.content_length = source.getheader('Content-Length')
            if source.getheader('Content-Type'):
                res.charset = None
                res.content_type = source.getheader('Content-Type')
            return res
        return self.best_response(req, statuses, reasons, bodies,
                                  '%s %s' % (server_type, req.method))


text:
VID="$1"
curl https://i.ytimg.com/vi/$VID/maxresdefault.jpg | convert -quality 70 - "$VID.webp"

redpajama_set_name: RedPajamaGithub


text:
package com.google.errorprone.bugpatterns.nullness;

import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH;

import com.google.errorprone.BugCheckerRefactoringTestHelper;
import com.google.errorprone.CompilationTestHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * @author kmb@google.com (Kevin Bierhoff)
 */
@RunWith(JUnit4.class)
public class FieldMissingNullableTest {

  @Test
  public void testLiteralNullAssignment() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message = \"hello\";",
            "  public void reset() {",
            "    // BUG: Diagnostic contains: @Nullable",
            "    message = null;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testDefiniteNullAssignment() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message = \"hello\";",
            "  public void setMessage(String message) {",
            "    // BUG: Diagnostic contains: @Nullable",
            "    this.message = message != null ? null : message;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testAssignmentInsideIfNull() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message;",
            "  public void setMessage(String message) {",
            "    if (message == null) {",
            "      // BUG: Diagnostic contains: @Nullable",
            "      this.message = message;",
            "    } else {",
            "      this.message = \"hello\";",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testMaybeNullAssignment() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message = \"hello\";",
            "  public void setMessage(int x) {",
            "    // BUG: Diagnostic contains: @Nullable",
            "    message = x >= 0 ? null : \"negative\";",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNullInitializer() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import javax.annotation.Nullable;",
            "public class NullableParameterTest {",
            "  // BUG: Diagnostic contains: @Nullable",
            "  public static final String MESSAGE = null;",
            "}")
        .doTest();
  }

  @Test
  public void testMaybeNullAssignmentInLambda() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import javax.annotation.Nullable;",
            "public class NullableParameterTest {",
            "  private String message = \"hello\";",
            "  public void setMessageIfPresent(java.util.Optional<String> message) {",
            // Note this code is bogus: s is guaranteed non-null...
            "    // BUG: Diagnostic contains: @Nullable",
            "    message.ifPresent(s -> { this.message = s != null ? s : null; });",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testComparisonToNull() {
    createAggressiveCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message;",
            "  public void reset() {",
            "    // BUG: Diagnostic contains: @Nullable",
            "    if (message != null) {",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testComparisonToNullOnOtherInstance() {
    createAggressiveCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message;",
            "  public void reset(FieldMissingNullTest other) {",
            "    // BUG: Diagnostic contains: @Nullable",
            "    if (other.message != null) {",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_comparisonToNullConservative() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message;",
            "  public void reset() {",
            "    if (message != null) {",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_alreadyAnnotated() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import javax.annotation.Nullable;",
            "public class FieldMissingNullTest {",
            "  @Nullable String message;",
            "  public void reset() {",
            "    this.message = null;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_alreadyTypeAnnotated() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/anno/my/Nullable.java",
            "package com.google.anno.my;",
            "import java.lang.annotation.ElementType;",
            "import java.lang.annotation.Target;",
            "@Target({ElementType.TYPE_USE})",
            "public @interface Nullable {}")
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import com.google.anno.my.Nullable;",
            "public class FieldMissingNullTest {",
            "  @Nullable String message;",
            "  public void reset() {",
            "    this.message = null;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_alreadyAnnotatedMonotonic() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import org.checkerframework.checker.nullness.qual.MonotonicNonNull;",
            "public class FieldMissingNullTest {",
            "  private @MonotonicNonNull String message;",
            "  public void reset() {",
            "    if (message != null) {",
            "    }",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_alreadyTypeAnnotatedInnerClass() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import org.checkerframework.checker.nullness.qual.Nullable;",
            "public class FieldMissingNullTest {",
            "  class Inner {}",
            "  @Nullable Inner message;",
            "  public void reset() {",
            "    this.message = null;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_initializeWithNonNullLiteral() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private final String message;",
            "  public FieldMissingNullTest() {",
            "    message = \"hello\";",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_nonNullInitializer() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class FieldMissingNullTest {",
            "  private String message = \"hello\";",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_lambdaInitializer() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/FieldMissingNullTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import java.util.function.Predicate;",
            "import java.util.function.Function;",
            "public class FieldMissingNullTest {",
            "  private Runnable runnable = () -> {};",
            "  private Predicate<?> predicate1 = p -> true;",
            "  private Predicate<?> predicate2 = (p -> true);",
            "  private Predicate<?> predicate3 = (String p) -> { return false; };",
            "  private Function<?, ?> function1 = p -> null;",
            "  private Function<?, ?> function2 = (p -> null);",
            "  private Function<?, ?> function3 = (String p) -> { return null; };",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_nonNullMethod() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/NonNullMethodTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class NonNullMethodTest {",
            "  private String message = \"hello\";",
            "  public void setMessage(int x) {",
            "    message = String.valueOf(x);",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_nonNullField() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/NonNullFieldTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class NonNullFieldTest {",
            "  private String message = \"hello\";",
            "  private String previous = \"\";",
            "  public void save() {",
            "    previous = message;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_nonNullParameter() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/NonNullParameterTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class NonNullParameterTest {",
            "  private String message = \"hello\";",
            "  public void setMessage(String message) {",
            "    this.message = message;",
            "  }",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_this() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/ThisTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class ThisTest {",
            "  private static ThisTest theInstance = new ThisTest();",
            "  public void makeDefault() {",
            "    this.theInstance = this;",
            "  }",
            "}")
        .doTest();
  }

  /**
   * Makes sure the check never flags methods returning a primitive. Returning null from them is a
   * bug, of course, but we're not trying to find those bugs in this check.
   */
  @Test
  public void testNegativeCases_primitiveFieldType() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/PrimitiveReturnTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "public class PrimitiveReturnTest {",
            "  private int count = (Integer) null;",
            "}")
        .doTest();
  }

  @Test
  public void testNegativeCases_initializeWithLambda() {
    createCompilationTestHelper()
        .addSourceLines(
            "com/google/errorprone/bugpatterns/nullness/NullableParameterTest.java",
            "package com.google.errorprone.bugpatterns.nullness;",
            "import javax.annotation.Nullable;",
            "public class NullableParameterTest {",
            "  private String message = \"hello\";",
            "  public void setMessageIfPresent(java.util.Optional<String> message) {",
            "    message.ifPresent(s -> { this.message = s; });",
            "  }",
            "}")
        .doTest();
  }

  // regression test for https://github.com/google/error-prone/issues/708
  @Test
  public void i708() {
    createCompilationTestHelper()
        .addSourceLines(
            "Test.java",
            "import java.util.regex.Pattern;",
            "class T {",
            "  private static final Pattern FULLY_QUALIFIED_METHOD_NAME_PATTERN =",
            "      Pattern.compile(\"(.+)#([^()]+?)(\\\\((.*)\\\\))?\");",
            "}")
        .doTest();
  }

  @Test
  public void testSuggestNonJsr305Nullable() {
    createRefactoringTestHelper()
        .addInputLines(
            "in/Test.java",
            "class T {",
            "  @Nullable private final Object obj1 = null;",
            "  private final Object obj2 = null;",
            "  @interface Nullable {}",
            "}")
        .addOutputLines(
            "out/Test.java",
            "class T {",
            "  @Nullable private final Object obj1 = null;",
            "  @Nullable private final Object obj2 = null;",
            "  @interface Nullable {}",
            "}")
        .doTest(TEXT_MATCH);
  }

  @Test
  public void testAnnotationInsertedAfterModifiers() {
    createRefactoringTestHelper()
        .addInputLines(
            "in/Test.java",
            "import org.checkerframework.checker.nullness.qual.Nullable;",
            "class T {",
            "  private final Object obj1 = null;",
            "}")
        .addOutputLines(
            "out/Test.java",
            "import org.checkerframework.checker.nullness.qual.Nullable;",
            "class T {",
            "  private final @Nullable Object obj1 = null;",
            "}")
        .doTest(TEXT_MATCH);
  }

  @Test
  public void testNonAnnotationNullable() {
    createRefactoringTestHelper()
        .addInputLines(
            "in/Test.java",
            "class T {",
            "  private final Object obj2 = null;",
            "  class Nullable {}",
            "}")
        .addOutputLines(
            "out/Test.java",
            "class T {",
            "  private final @org.jspecify.nullness.Nullable Object obj2 = null;",
            "  class Nullable {}",
            "}")
        .doTest();
  }

  private CompilationTestHelper createCompilationTestHelper() {
    return CompilationTestHelper.newInstance(FieldMissingNullable.class, getClass());
  }

  private CompilationTestHelper createAggressiveCompilationTestHelper() {
    return createCompilationTestHelper().setArgs("-XepOpt:Nullness:Conservative=false");
  }

  private BugCheckerRefactoringTestHelper createRefactoringTestHelper() {
    return BugCheckerRefactoringTestHelper.newInstance(FieldMissingNullable.class, getClass());
  }
}


text:
#include "application_manager/commands/mobile/on_way_point_change_notification.h"
#include "application_manager/application_manager.h"

namespace application_manager {
namespace commands {

OnWayPointChangeNotification::OnWayPointChangeNotification(
    const MessageSharedPtr& message, ApplicationManager& application_manager)
    : CommandNotificationImpl(message, application_manager) {}

OnWayPointChangeNotification::~OnWayPointChangeNotification() {}

void OnWayPointChangeNotification::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  std::set<int32_t> subscribed_for_way_points =
      application_manager_.GetAppsSubscribedForWayPoints();

  for (std::set<int32_t>::const_iterator app_id =
           subscribed_for_way_points.begin();
       app_id != subscribed_for_way_points.end();
       ++app_id) {
    (*message_)[strings::params][strings::connection_key] = *app_id;
    SendNotification();
  }
}
}  // namespace commands
}  // namespace application_manager


text:
package org.cesiumjs.cs.core.options;

import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import org.cesiumjs.cs.core.Cartesian2;

/**
 * @author Serge Silaev aka iSergio
 */
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class WebMercatorTilingSchemeOptions {
    /**
     * The southwest corner of the rectangle covered by the tiling scheme, in
     * meters. If this parameter or rectangleNortheastInMeters is not specified, the
     * entire globe is covered in the longitude direction and an equal distance is
     * covered in the latitude direction, resulting in a square projection.
     */
    @JsProperty
    public Cartesian2 rectangleSouthwestInMeters;
    /**
     * optional The northeast corner of the rectangle covered by the tiling scheme,
     * in meters. If this parameter or rectangleSouthwestInMeters is not specified,
     * the entire globe is covered in the longitude direction and an equal distance
     * is covered in the latitude direction, resulting in a square projection.
     */
    @JsProperty
    public Cartesian2 rectangleNortheastInMeters;

    @JsConstructor
    public WebMercatorTilingSchemeOptions() {
    }
}


text:
package org.camunda.bpm.engine.test.bpmn.async;

import static org.camunda.bpm.engine.test.bpmn.async.RetryCmdDeployment.deployment;
import static org.camunda.bpm.engine.test.bpmn.async.RetryCmdDeployment.prepareCompensationEventProcess;
import static org.camunda.bpm.engine.test.bpmn.async.RetryCmdDeployment.prepareEscalationEventProcess;
import static org.camunda.bpm.engine.test.bpmn.async.RetryCmdDeployment.prepareMessageEventProcess;
import static org.camunda.bpm.engine.test.bpmn.async.RetryCmdDeployment.prepareSignalEventProcess;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;

import java.util.Collection;

import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

/**
 * @author Askar Akhmerov
 */
@RunWith(Parameterized.class)
public class FoxJobRetryCmdEventsTest {

  public ProcessEngineRule engineRule = new ProcessEngineRule();
  public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);
  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Rule
  public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(testRule);

  @Parameterized.Parameter
  public RetryCmdDeployment deployment;

  @Parameterized.Parameters(name = "deployment {index}")
  public static Collection<RetryCmdDeployment[]> scenarios() {
    return RetryCmdDeployment.asParameters(
        deployment()
            .withEventProcess(prepareSignalEventProcess()),
        deployment()
            .withEventProcess(prepareMessageEventProcess()),
        deployment()
            .withEventProcess(prepareEscalationEventProcess()),
        deployment()
            .withEventProcess(prepareCompensationEventProcess())
    );
  }

  private Deployment currentDeployment;

  @Before
  public void setUp () {
    currentDeployment = testRule.deploy(deployment.getBpmnModelInstances());
  }

  @Test
  public void testFailedIntermediateThrowingSignalEventAsync () {
    ProcessInstance pi = engineRule.getRuntimeService().startProcessInstanceByKey(RetryCmdDeployment.PROCESS_ID);
    assertJobRetries(pi);
  }

  @After
  public void tearDown() {
    engineRule.getRepositoryService().deleteDeployment(currentDeployment.getId(),true,true);
  }

  protected void assertJobRetries(ProcessInstance pi) {
    assertThat(pi,is(notNullValue()));

    Job job = fetchJob(pi.getProcessInstanceId());

    try {
      engineRule.getManagementService().executeJob(job.getId());
    } catch (Exception e) {
    }

    // update job
    job = fetchJob(pi.getProcessInstanceId());
    assertThat(job.getRetries(),is(4));
  }

  protected Job fetchJob(String processInstanceId) {
    return engineRule.getManagementService().createJobQuery().processInstanceId(processInstanceId).singleResult();
  }

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;

namespace Selenium.Internal.SeleniumEmulation
{
    /// <summary>
    /// Defines the command for the noOp keyword.
    /// </summary>
    internal class NoOp : SeleneseCommand
    {
        private object returnValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="NoOp"/> class.
        /// </summary>
        /// <param name="toReturn">An object to return as the result of the command.</param>
        public NoOp(object toReturn)
        {
            this.returnValue = toReturn;
        }

        /// <summary>
        /// Handles the command.
        /// </summary>
        /// <param name="driver">The driver used to execute the command.</param>
        /// <param name="locator">The first parameter to the command.</param>
        /// <param name="value">The second parameter to the command.</param>
        /// <returns>The result of the command.</returns>
        protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
        {
            return this.returnValue;
        }
    }
}


text:
1.5.2 / 2014-06-26
==================

  * deps: cookie-signature@1.0.4
    - fix for timing attacks

1.5.1 / 2014-06-21
==================

  * Move hard-to-track-down `req.secret` deprecation message

1.5.0 / 2014-06-19
==================

  * Debug name is now "express-session"
  * Deprecate integration with `cookie-parser` middleware
  * Deprecate looking for secret in `req.secret`
  * Directly read cookies; `cookie-parser` no longer required
  * Directly set cookies; `res.cookie` no longer required
  * Generate session IDs with `uid-safe`, faster and even less collisions

1.4.0 / 2014-06-17
==================

  * Add `genid` option to generate custom session IDs
  * Add `saveUninitialized` option to control saving uninitialized sessions
  * Add `unset` option to control unsetting `req.session`
  * Generate session IDs with `rand-token` by default; reduce collisions
  * deps: buffer-crc32@0.2.3

1.3.1 / 2014-06-14
==================

  * Add description in package for npmjs.org listing

1.3.0 / 2014-06-14
==================

  * Integrate with express "trust proxy" by default
  * deps: debug@1.0.2

1.2.1 / 2014-05-27
==================

  * Fix `resave` such that `resave: true` works

1.2.0 / 2014-05-19
==================

  * Add `resave` option to control saving unmodified sessions

1.1.0 / 2014-05-12
==================

  * Add `name` option; replacement for `key` option
  * Use `setImmediate` in MemoryStore for node.js >= 0.10

1.0.4 / 2014-04-27
==================

  * deps: debug@0.8.1

1.0.3 / 2014-04-19
==================

  *  Use `res.cookie()` instead of `res.setHeader()`
  * deps: cookie@0.1.2

1.0.2 / 2014-02-23
==================

  * Add missing dependency to `package.json`

1.0.1 / 2014-02-15
==================

  * Add missing dependencies to `package.json`

1.0.0 / 2014-02-15
==================

  * Genesis from `connect`


text:
package org.cocos2d.tests;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import org.cocos2d.actions.base.Action;
import org.cocos2d.actions.base.RepeatForever;
import org.cocos2d.actions.instant.CallFuncN;
import org.cocos2d.actions.interval.IntervalAction;
import org.cocos2d.actions.interval.RotateBy;
import org.cocos2d.actions.interval.ScaleBy;
import org.cocos2d.actions.interval.Sequence;
import org.cocos2d.layers.Layer;
import org.cocos2d.menus.Menu;
import org.cocos2d.menus.MenuItemImage;
import org.cocos2d.nodes.*;
import org.cocos2d.opengl.CCGLSurfaceView;
import org.cocos2d.particlesystem.ParticleSun;
import org.cocos2d.types.CCSize;

public class CocosNodeTest extends Activity {
    private static final String LOG_TAG = CocosNodeTest.class.getSimpleName();
    private CCGLSurfaceView mGLSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mGLSurfaceView = new CCGLSurfaceView(this);
        setContentView(mGLSurfaceView);
    }

    @Override
    public void onStart() {
        super.onStart();

        // attach the OpenGL view to a window
        Director.sharedDirector().attachInView(mGLSurfaceView);

        // set landscape mode
        Director.sharedDirector().setLandscape(false);

        // show FPS
        Director.sharedDirector().setDisplayFPS(true);

        // frames per second
        Director.sharedDirector().setAnimationInterval(1.0f / 60);

        Scene scene = Scene.node();
        scene.addChild(nextAction());

        // Make the Scene active
        Director.sharedDirector().runWithScene(scene);

    }

    @Override
    public void onPause() {
        super.onPause();

        Director.sharedDirector().pause();
    }

    @Override
    public void onResume() {
        super.onResume();

        Director.sharedDirector().resume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        TextureManager.sharedTextureManager().removeAllTextures();
    }

    public static final int kTagSprite1 = 1;
    public static final int kTagSprite2 = 2;
    public static final int kTagSprite3 = 3;

    static int sceneIdx = -1;
    static Class transitions[] = {
            Test1.class,
            Test2.class,
            Test3.class,
            Test4.class,
            Test5.class,
            Test6.class,
            Test7.class,
    };

    static Layer nextAction() {

        sceneIdx++;
        sceneIdx = sceneIdx % transitions.length;

        return restartAction();
    }

    static Layer backAction() {
        sceneIdx--;
        int total = transitions.length;
        if (sceneIdx < 0)
            sceneIdx += total;
        return restartAction();
    }

    static Layer restartAction() {
        try {
            Class c = transitions[sceneIdx];
            return (Layer) c.newInstance();
        } catch (Exception e) {
            return null;
        }
    }

    static abstract class TestDemo extends Layer {
        public TestDemo() {
            CCSize s = Director.sharedDirector().winSize();

            Label label = Label.label(title(), "DroidSans", 18);
            label.setPosition(s.width / 2, s.height - 30);
            addChild(label);

            MenuItemImage item1 = MenuItemImage.item("b1.png", "b2.png", this, "backCallback");
            MenuItemImage item2 = MenuItemImage.item("r1.png", "r2.png", this, "restartCallback");
            MenuItemImage item3 = MenuItemImage.item("f1.png", "f2.png", this, "nextCallback");

            Menu menu = Menu.menu(item1, item2, item3);
            menu.setPosition(0, 0);
            item1.setPosition(s.width / 2 - 100, 30);
            item2.setPosition(s.width / 2, 30);
            item3.setPosition(s.width / 2 + 100, 30);
            addChild(menu, -1);
        }

        public static void restartCallback() {
            Scene s = Scene.node();
            s.addChild(restartAction());
            Director.sharedDirector().replaceScene(s);
        }

        public void nextCallback() {
            Scene s = Scene.node();
            s.addChild(nextAction());
            Director.sharedDirector().replaceScene(s);
        }

        public void backCallback() {
            Scene s = Scene.node();
            s.addChild(backAction());
            Director.sharedDirector().replaceScene(s);
        }

        public abstract String title();
    }

    static class Test1 extends TestDemo {

        public void onEnter() {
            super.onEnter();

            CCSize s = Director.sharedDirector().winSize();

            Sprite sp0 = Sprite.sprite("grossini.png");
            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp2 = Sprite.sprite("grossinis_sister2.png");
            Sprite point0 = Sprite.sprite("r1.png");
            Sprite point1 = Sprite.sprite("r1.png");
            Sprite point2 = Sprite.sprite("r1.png");

            point0.scale(0.25f);
            point1.scale(0.25f);
            point2.scale(0.25f);

            sp0.setPosition(s.width/2, s.height / 2);
            point0.setPosition(sp0.getPositionX(), sp0.getPositionY());
            sp0.setAnchorPoint(0.5f, 0.5f);

            sp1.setPosition(s.width/2 - 100, s.height / 2);
            point1.setPosition(sp1.getPositionX(), sp1.getPositionY());
            sp1.setAnchorPoint(0, 0);

            sp2.setPosition(s.width/2 + 100, s.height / 2);
            point2.setPosition(sp2.getPositionX(), sp2.getPositionY());
            sp2.setAnchorPoint(1, 1);

            addChild(sp0);
            addChild(sp1);
            addChild(sp2);

            addChild(point0, 1);
            addChild(point1, 1);
            addChild(point2, 1);

            IntervalAction a1 = RotateBy.action(2, 360);
            IntervalAction a2 = ScaleBy.action(2, 2);

            Action action1 = RepeatForever.action(Sequence.actions(a1, a2, a2.reverse()));

            Action action2 = action1.copy();
            Action action0 = action1.copy();

            sp0.runAction(action0);
            sp1.runAction(action1);
            sp2.runAction(action2);
        }

        public String title() {
            return "Transform Anchor";
        }
    }

    static class Test2 extends TestDemo {

        public void onEnter() {
            super.onEnter();

            CCSize s = Director.sharedDirector().winSize();

            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp2 = Sprite.sprite("grossinis_sister2.png");
            Sprite sp3 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp4 = Sprite.sprite("grossinis_sister2.png");

            sp1.setPosition(100, s.height / 2);
            sp2.setPosition(s.width - 100, s.height / 2);
            addChild(sp1);
            addChild(sp2);

            sp3.scale(0.25f);
            sp4.scale(0.25f);

            sp1.addChild(sp3);
            sp2.addChild(sp4);

            IntervalAction a1 = RotateBy.action(2, 360);
            IntervalAction a2 = ScaleBy.action(2, 2);

            Action action1 = RepeatForever.action(Sequence.actions(a1, a2, a2.reverse()));
            Action action2 = RepeatForever.action(Sequence.actions(a1.copy(), a2.copy(), a2.reverse()));

            sp2.setAnchorPoint(0, 0);

            sp1.runAction(action1);
            sp2.runAction(action2);
        }

        public String title() {
            return "Transform Anchor and Children";
        }
    }

    static class Test3 extends TestDemo {

        public void onEnter() {
            super.onEnter();

            CCSize s = Director.sharedDirector().winSize();

            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp2 = Sprite.sprite("grossinis_sister2.png");
            Sprite sp3 = Sprite.sprite("grossini.png");

            sp1.setPosition(20, 80);
            sp2.setPosition(70, 50);
            sp3.setPosition(s.width / 2, s.height / 2);

            // these tags belong to sp3 (kTagSprite1, kTagSprite2)
            sp3.addChild(sp1, -1, kTagSprite1);
            sp3.addChild(sp2, 1, kTagSprite2);

            // this tag belong to Test3 (kTagSprite1)
            addChild(sp3, 0, kTagSprite1);

            IntervalAction a1 = RotateBy.action(4, 360);
            Action action1 = RepeatForever.action(a1);
            sp3.runAction(action1);

            schedule("changeZOrder", 2.0f);
        }

        public void changeZOrder(float dt) {
            CocosNode grossini = getChild(kTagSprite1);

            CocosNode sprite1 = grossini.getChild(kTagSprite1);
            CocosNode sprite2 = grossini.getChild(kTagSprite2);

            int zt = sprite1.getZOrder();
            grossini.reorderChild(sprite1, sprite2.getZOrder());
            grossini.reorderChild(sprite2, zt);
        }

        public String title() {
            return "Z Order";
        }
    }

    static class Test4 extends TestDemo {

        public Test4() {

            CCSize s = Director.sharedDirector().winSize();

            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp2 = Sprite.sprite("grossinis_sister2.png");

            sp1.setPosition(100, s.height / 2);
            sp2.setPosition(s.width - 100, s.height / 2);

            addChild(sp1, 0, 2);
            addChild(sp2, 0, 3);

            schedule("delay2", 2.0f);
            schedule("delay4", 4.0f);
        }

        public void delay2(float dt) {
            CocosNode node = getChild(2);
            IntervalAction action1 = RotateBy.action(1, 360);
            node.runAction(action1);
        }

        public void delay4(float dt) {
            unschedule("delay4");
            removeChild(3, false);
        }

        public String title() {
            return "Tags";
        }
    }

    static class Test5 extends TestDemo {

        public Test5() {
            CCSize s = Director.sharedDirector().winSize();

            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp2 = Sprite.sprite("grossinis_sister2.png");

            sp1.setPosition(100, s.height / 2);
            sp2.setPosition(s.width - 100, s.height / 2);

            IntervalAction rot = RotateBy.action(2, 360);
            IntervalAction rot_back = rot.reverse();
            Action forever = RepeatForever.action(
                    Sequence.actions(rot, rot_back));
            Action forever2 = forever.copy();

            addChild(sp1, 0, kTagSprite1);
            addChild(sp2, 0, kTagSprite2);

            sp1.runAction(forever);
            sp2.runAction(forever2);

            schedule("addAndRemove", 2.0f);
        }

        public void addAndRemove(float dt) {
            CocosNode sp1 = getChild(kTagSprite1);
            CocosNode sp2 = getChild(kTagSprite2);

            removeChild(sp1, false);
            removeChild(sp2, true);

            addChild(sp1, 0, kTagSprite1);
            addChild(sp2, 0, kTagSprite2);
        }

        public String title() {
            return "Remove";
        }
    }

    static class Test6 extends TestDemo {

        public Test6() {
            CCSize s = Director.sharedDirector().winSize();

            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            Sprite sp11 = Sprite.sprite("grossinis_sister1.png");

            Sprite sp2 = Sprite.sprite("grossinis_sister2.png");
            Sprite sp21 = Sprite.sprite("grossinis_sister2.png");

            sp1.setPosition(100, s.height / 2);
            sp2.setPosition(s.width - 100, s.height / 2);

            IntervalAction rot = RotateBy.action(2, 360);
            IntervalAction rot_back = rot.reverse();
            Action forever1 = RepeatForever.action(Sequence.actions(rot, rot_back));
            Action forever11 = forever1.copy();

            Action forever2 = forever1.copy();
            Action forever21 = forever1.copy();

            addChild(sp1, 0, kTagSprite1);
            sp1.addChild(sp11);
            addChild(sp2, 0, kTagSprite2);
            sp2.addChild(sp21);

            sp1.runAction(forever1);
            sp11.runAction(forever11);
            sp2.runAction(forever2);
            sp21.runAction(forever21);

            schedule("addAndRemove", 2.0f);
        }

        public void addAndRemove(float dt) {
            CocosNode sp1 = getChild(kTagSprite1);
            CocosNode sp2 = getChild(kTagSprite2);

            removeChild(sp1, false);
            removeChild(sp2, true);

            addChild(sp1, 0, kTagSprite1);
            addChild(sp2, 0, kTagSprite2);
        }

        public String title() {
            return "Remove with Children";
        }
    }

    static class Test7 extends TestDemo {

        public Test7() {
            CCSize s = Director.sharedDirector().winSize();

            Sprite sp1 = Sprite.sprite("grossinis_sister1.png");
            addChild(sp1, 0, kTagSprite1);

            sp1.setPosition(s.width / 2, s.height / 2);

            schedule("shouldNotCrash", 1.0f);
        }

        public void shouldNotCrash(float delta) {
            unschedule("shouldNotCrash");

            CCSize s = Director.sharedDirector().winSize();

            // if the node has timers, it crashes
            CocosNode explosion = ParticleSun.node();

            // if it doesn't, it works Ok.
            //	CocosNode explosion = Sprite.sprite("grossinis_sister2.png");

            explosion.setPosition(s.width / 2, s.height / 2);

            runAction(Sequence.actions(RotateBy.action(2, 360),
                    CallFuncN.action(this, "removeMe")));

            addChild(explosion);
        }

        // remove
        public void removeMe(CocosNode node) {
            parent.removeChild(node, true);
            nextCallback();
        }

        public String title() {
            return "Stress Test #1";
        }
    }

}


text:
package fr.isep.simizer.laws;

import fr.isep.simizer.utils.StdRandom;

/**
 * A {@code Law} representing a Poisson distribution.
 * <p>
 * For an explanation of how out-of-range values are handled, see {@link
 * Law#nextValue()}.
 */
public class PoissonLaw extends Law {

  /** The alpha value for this Poisson distribution. */
  private double alpha;

  /**
   * Initializes a PoissonLaw instance with an {@code alpha} value of {@code
   * 1.0}.
   */
  public PoissonLaw() {
    this(1.0);
  }

  /**
   * Initializes a PoissonLaw with a custom {@code alpha} value.
   *
   * @param alpha the alpha value used to describe the distribution
   */
  public PoissonLaw(double alpha) {
    super();

    this.alpha = alpha;
  }

  @Override
  public int generateNextValue() {
    double l = Math.exp(-alpha);
    double p = 1.0;

    int k = 0;
    do {
      k++;
      p = StdRandom.uniform() * p;
    } while (p > l);
    return k - 1;
  }
}


text:
package org.datavaultplatform.common.io;

public class Progress {
    public long startTime = 0;
    public long dirCount = 0;
    public long fileCount = 0;
    public long byteCount = 0;
    public long timestamp = 0;
}


text:
class Bumbleworks::Rails::ApplicationController < ApplicationController
end


text:
package at.srfg.graphium.api.service;

public interface ISubscribedGraphserverImportStateService {

	void processFinishedImport(String serverName, String graphName, String version);

	void processFailedImport(String serverName, String graphName, String version);

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="icon" href="favicon.ico">

  <title>Vía Crucis | Séptima Estación</title>

  <link href="dist/css/bootstrap.min.css" rel="stylesheet">

  <link href="theme.css" rel="stylesheet">

  <link href="icons.css" rel="stylesheet">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
              Toggle navigation

            </button>
             Vía Crucis

Primera Estación

Segunda Estación

Tercera Estación

Cuarta Estación

Quinta Estación

Sexta Estación

Séptima Estación

Octava Estación

Novena Estación

Décima Estación

Undécima Estación

Duodécima Estación

Decimotercera Estación

Decimocuarta Estación

Decimoquinta Estación

Séptima Estación

Jesús cae por segunda vez

 V. Te adoramos, oh Cristo, y te bendecimos.

              R. Pues por tu santa cruz redimiste al mundo.

 [V. Adoramus te, Christe, et benedicimus tibi

              R. Quia per sanctam crucem tuam redemisti mundum.]

 Jesús había tomado de nuevo la cruz y con ella a cuestas llegó a la cima de la empinada calle que daba a una de las puertas de la ciudad. Allí, extenuado, sin fuerzas, cayó por segunda vez bajo el peso de la cruz. Faltaba poco para llegar al sitio en que tenía que ser crucificado, y Jesús, empeñado en llevar a cabo hasta la meta los planes de Dios, aún logró reunir fuerzas, levantarse y proseguir su camino.

 Nada tiene de extraño que Jesús cayera si se tiene en cuenta cómo había sido castigado desde la noche anterior, y cómo se encontraba en aquel momento. Pero, al mismo tiempo, este paso nos muestra lo frágil que es la condición humana, aun cuando la aliente el mejor espíritu, y que no han de desmoralizarnos las flaquezas ni las caídas cuando seguimos a Cristo cargados con nuestra cruz. Jesús, por los suelos una vez más, no se siente derrotado ni abandona su cometido. Para Él no es tan grave el caer como el no levantarnos. Y pensemos cuántas son las personas que se sienten derrotadas y sin ánimos para reemprender el seguimiento de Cristo, y que la ayuda de una mano amiga podría sacarlas de su postración.

 Padrenuestro, Avemaría y Gloria.

 Jesús, pequé: Ten piedad y misericordia de mí.

 Bendita y alabada sea la pasión y muerte de nuestro Señor Jesucristo y los dolores de su santísima Madre, triste y afligida al pie de la cruz. Amén, Jesús.

 Anterior

Siguiente

             Subir


text:
#ifndef __XN_FRAME_STREAM_PROCESSOR_H__
#define __XN_FRAME_STREAM_PROCESSOR_H__

//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnStreamProcessor.h"
#include <XnDDK/XnFrameStream.h>

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

/*
* A processor for streams that are frame-based.
*/
class XnFrameStreamProcessor : public XnStreamProcessor
{
public:
	/*
	* Initializes a new frame-stream-processor.
	*
	* @param	pDevicePrivateData	[in]	A pointer to the device.
	* @param	csName				[in]	Name of this stream.
	* @param	nTypeSOF			[in]	The packet type that signifies start-of-frame.
	* @param	nTypeEOF			[in]	The packet type that signifies end-of-frame.
	*/
	XnFrameStreamProcessor(XnFrameStream* pStream, XnSensorStreamHelper* pHelper, XnFrameBufferManager* pBufferManager, XnUInt16 nTypeSOF, XnUInt16 nTypeEOF);

	/**
	* Destroys a frame-based stream processor
	*/
	virtual ~XnFrameStreamProcessor();

protected:
	//---------------------------------------------------------------------------
	// Overridden Functions
	//---------------------------------------------------------------------------
	virtual void ProcessPacketChunk(const XnSensorProtocolResponseHeader* pHeader, const XnUChar* pData, XnUInt32 nDataOffset, XnUInt32 nDataSize);
	virtual void OnPacketLost();

	//---------------------------------------------------------------------------
	// New Virtual Functions
	//---------------------------------------------------------------------------

	/*
	* Called when a frame starts.
	*
	* @param	pHeader		[in]	Header for current packet.
	*/
	virtual void OnStartOfFrame(const XnSensorProtocolResponseHeader* pHeader);

	/*
	* Called for every chunk received
	*
	* @param	pHeader		[in]	A pointer to current packet header.
	* @param	pData		[in]	A pointer to the data.
	* @param	nDataOffset	[in]	The offset of this data chunk inside current packet.
	* @param	nDataSize	[in]	Size of the data in bytes.
	*/
	virtual void ProcessFramePacketChunk(const XnSensorProtocolResponseHeader* pHeader, const XnUChar* pData, XnUInt32 nDataOffset, XnUInt32 nDataSize) = 0;

	/*
	* Called when a frame ends.
	*
	* @param	pHeader		[in]	Header for current packet.
	*/
	virtual void OnEndOfFrame(const XnSensorProtocolResponseHeader* pHeader);

	/*
	* Called when a frame is ready for reading.
	*
	* @param	nFrameID	[in]	ID of this frame.
	* @param	nFrameTS	[in]	Timestamp of this frame.
	*/
	virtual void OnFrameReady(XnUInt32 /*nFrameID*/, XnUInt64 /*nFrameTS*/) {}

	//---------------------------------------------------------------------------
	// Utility Functions
	//---------------------------------------------------------------------------

	inline XnFrameStream* GetStream()
	{
		return (XnFrameStream*)XnStreamProcessor::GetStream();
	}

	/*
	* Gets the expected output size.
	*/
	inline XnUInt32 GetExpectedOutputSize()
	{
		return GetStream()->GetRequiredDataSize();
	}

	/*
	* Gets current write buffer.
	*/
	inline XnBuffer* GetWriteBuffer()
	{
		return m_pTripleBuffer->GetWriteBuffer();
	}

	/*
	* Gets current frame ID (for logging purposes mainly).
	*/
	inline XnUInt32 GetCurrentFrameID()
	{
		return m_pTripleBuffer->GetLastFrameID();
	}

	/*
	* Notifies that write buffer has overflowed, logging a warning and reseting it.
	*/
	void WriteBufferOverflowed();

	/*
	* Checks if write buffer has overflowed, if so, a log will be issued and buffer will reset.
	*/
	inline XnBool CheckWriteBufferForOverflow(XnUInt32 nWriteSize)
	{
		if (GetWriteBuffer()->GetFreeSpaceInBuffer() < nWriteSize)
		{
			WriteBufferOverflowed();
			return FALSE;
		}

		return TRUE;
	}

	/*
	* Marks current frame as corrupted.
	*/
	void FrameIsCorrupted();

	void SetAllowDoubleSOFPackets(XnBool bAllow) { m_bAllowDoubleSOF = bAllow; }

private:
	//---------------------------------------------------------------------------
	// Class Members
	//---------------------------------------------------------------------------
	/* The type of start-of-frame packet. */
	XnUInt16 m_nTypeSOF;
	/* The type of end-of-frame packet. */
	XnUInt16 m_nTypeEOF;
	/* A pointer to the triple frame buffer of this stream. */
	XnFrameBufferManager* m_pTripleBuffer;

	XnChar m_csInDumpMask[100];
	XnChar m_csInternalDumpMask[100];
	XnDumpFile* m_InDump;
	XnDumpFile* m_InternalDump;
	XnBool m_bFrameCorrupted;
	XnBool m_bAllowDoubleSOF;
	XnUInt16 m_nLastSOFPacketID;
	XnUInt64 m_nFirstPacketTimestamp;
};

#endif //__XN_FRAME_STREAM_PROCESSOR_H__


text:
'''
The MIT License (MIT)
Copyright (c) 2016 Nordeus LLC

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.
'''
import pytest
from pushkin.request.requests import EventRequestSingle
from pushkin.protobuf import EventMessage_pb2
from pushkin.request.event_handlers import EventHandler, LoginEventHandler
from pushkin import config
from pushkin import context
from pushkin import test_config_ini_path

context.setup_configuration(test_config_ini_path)

@pytest.fixture
def mock_log(mocker):
    '''Mock request processor'''
    mocker.patch('pushkin.context.main_logger')

def test_valid_event_proto(mock_log, ):
    '''Test that a valid event proto is validated correctly.'''
    event = EventRequestSingle(123, 1, None, 12345)
    event_handler = EventHandler(1)
    assert event_handler.validate(event, {})

def test_event_proto_without_user_id(mock_log):
    '''Test that an event proto without user_id fails validation'''
    event = EventRequestSingle(None, 1, None, 12345)
    event_handler = EventHandler(1)
    assert not event_handler.validate(event, {})

def test_event_proto_without_timestamp(mock_log):
    '''Test that an event proto without timestamp fails validation'''
    event = EventRequestSingle(None, 1, None)
    event_handler = EventHandler(1)
    assert not event_handler.validate(event, {})

def test_valid_login_proto(mock_log):
    '''Test that a valid login proto is validated correctly.'''
    event_proto = EventMessage_pb2.Event()
    pair = event_proto.pairs.add()
    pair.key = 'platformId'
    pair.value = '1'
    pair = event_proto.pairs.add()
    pair.key = 'deviceToken'
    pair.value = '1234'
    pair = event_proto.pairs.add()
    pair.key = 'applicationVersion'
    pair.value = '1'
    params = dict((pair.key, pair.value) for pair in event_proto.pairs)
    event = EventRequestSingle(123, config.login_event_id, params, 12345)
    assert LoginEventHandler().validate(event, params)

def test_login_proto_without_platform_id(mock_log):
    '''Test that a login proto without platform id fails validation.'''
    event_proto = EventMessage_pb2.Event()
    pair = event_proto.pairs.add()
    pair.key = 'deviceToken'
    pair.value = '1234'
    pair = event_proto.pairs.add()
    pair.key = 'applicationVersion'
    pair.value = '1'
    params = dict((pair.key, pair.value) for pair in event_proto.pairs)
    event = EventRequestSingle(123, config.login_event_id, params, 12345)
    assert not LoginEventHandler().validate(event, params)

def test_login_proto_empty_platform_id(mock_log):
    '''Test that a login proto with empty platform id fails validation.'''
    event_proto = EventMessage_pb2.Event()
    pair = event_proto.pairs.add()
    pair.key = 'platformId'
    pair.value = ''
    pair = event_proto.pairs.add()
    pair.key = 'deviceToken'
    pair.value = '1234'
    pair = event_proto.pairs.add()
    pair.key = 'applicationVersion'
    pair.value = '1'
    params = dict((pair.key, pair.value) for pair in event_proto.pairs)
    event = EventRequestSingle(123, config.login_event_id, params, 12345)
    assert not LoginEventHandler().validate(event, params)

def test_login_proto_non_numeric_platform_id(mock_log):
    '''Test that a login proto with non numeric platform id fails validation.'''
    event_proto = EventMessage_pb2.Event()
    pair = event_proto.pairs.add()
    pair.key = 'platformId'
    pair.value = 'asd'
    pair = event_proto.pairs.add()
    pair.key = 'deviceToken'
    pair.value = '1234'
    pair = event_proto.pairs.add()
    pair.key = 'applicationVersion'
    pair.value = '1'
    params = dict((pair.key, pair.value) for pair in event_proto.pairs)
    event = EventRequestSingle(123, config.login_event_id, params, 12345)
    assert not LoginEventHandler().validate(event, params)

def test_login_proto_without_device_token(mock_log):
    '''Test that a login proto without device token fails validation.'''
    event_proto = EventMessage_pb2.Event()
    pair = event_proto.pairs.add()
    pair.key = 'platformId'
    pair.value = '1'
    pair = event_proto.pairs.add()
    pair.key = 'applicationVersion'
    pair.value = '1'
    params = dict((pair.key, pair.value) for pair in event_proto.pairs)
    event = EventRequestSingle(123, config.login_event_id, params, 12345)
    assert LoginEventHandler().validate(event, params)

def test_login_proto_empty_device_token(mock_log):
    '''Test that a login proto with empty device token fails validation.'''
    event_proto = EventMessage_pb2.Event()
    pair = event_proto.pairs.add()
    pair.key = 'platformId'
    pair.value = '1'
    pair = event_proto.pairs.add()
    pair.key = 'deviceToken'
    pair.value = ''
    pair = event_proto.pairs.add()
    pair.key = 'applicationVersion'
    pair.value = '1'
    params = dict((pair.key, pair.value) for pair in event_proto.pairs)
    event = EventRequestSingle(123, config.login_event_id, params, 12345)
    assert LoginEventHandler().validate(event, params)


text:
class AddStateExplanationToAppliance < ActiveRecord::Migration
  def change
    change_table :atmosphere_appliances do |t|
      t.column :state_explanation, :string, null: true
    end
  end
end