text:
package voldemort.utils.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;

import voldemort.utils.Utils;

/**
 * A simple implementation of a per-key resource pool.

 *

 *
blocks if resource is not available.
 *
allocates resources in FIFO order
 *
Pools are per key and there is no global maximum pool limit.
 *

 *
 * Invariants that this implementation does not guarantee:
 *

 *
A checked in resource was previously checked out. (I.e., user can use
 * ResourceFactory and then check in a resource that this pool did not create.)
 *
A checked out resource is checked in at most once. (I.e., a user does not
 * call check in on a checked out resource more than once.)
 *
User no longer has a reference to a checked in resource. (I.e., user can
 * keep using the resource after it invokes check in.)
 *
A resource that is checked out is eventually either checked in or
 * destroyed via objectFactory.destroy(). (I.e., a user can squat on a resource
 * or let its reference to the resource lapse without checking the resource in
 * or destroying the resource.)
 *

 *
 * Phrased differently, the following is expected of the user of this class:
 *

 *
A checked out resource is checked in exactly once.
 *
A resource that is checked in was previously checked out.
 *
A resource that is checked in is never used again. / No reference is
 * retained to a checked in resource.
 *
Also, checkout is never called after close.
 *

 */
public class KeyedResourcePool<K, V> {

    private static final Logger logger = Logger.getLogger(KeyedResourcePool.class.getName());

    private final AtomicBoolean isOpen = new AtomicBoolean(true);
    private final ResourceFactory<K, V> objectFactory;
    private final ResourcePoolConfig resourcePoolConfig;
    private final ConcurrentMap<K, Pool<V>> resourcePoolMap;

    public KeyedResourcePool(ResourceFactory<K, V> objectFactory,
                             ResourcePoolConfig resourcePoolConfig) {
        this.objectFactory = Utils.notNull(objectFactory);
        this.resourcePoolConfig = Utils.notNull(resourcePoolConfig);
        this.resourcePoolMap = new ConcurrentHashMap<K, Pool<V>>();
    }

    /**
     * Create a new pool
     *
     * @param <K> The type of the keys
     * @param <V> The type of the values
     * @param factory The factory that creates objects
     * @param config The pool config
     * @return The created pool
     */
    public static <K, V> KeyedResourcePool<K, V> create(ResourceFactory<K, V> factory,
                                                        ResourcePoolConfig config) {
        return new KeyedResourcePool<K, V>(factory, config);
    }

    /**
     * Create a new pool using the defaults
     *
     * @param <K> The type of the keys
     * @param <V> The type of the values
     * @param factory The factory that creates objects
     * @return The created pool
     */
    public static <K, V> KeyedResourcePool<K, V> create(ResourceFactory<K, V> factory) {
        return create(factory, new ResourcePoolConfig());
    }

    /**
     * Checkout a resource if one is immediately available. If none is available
     * and we have created fewer than the max size resources, then create a new
     * one. If no resources are available and we are already at the max size
     * then block for up to the maximum time specified. When we hit the maximum
     * time, if we still have not retrieved a valid resource throw an exception.
     *
     * This method is guaranteed to either return a valid resource in the pool
     * timeout + object creation time or throw an exception. If an exception is
     * thrown, resource is guaranteed to be destroyed.
     *
     * @param key The key to checkout the resource for
     * @return The resource
     */
    public V checkout(K key) throws Exception {
        checkNotClosed();

        long startNs = System.nanoTime();
        Pool<V> resourcePool = getResourcePoolForKey(key);
        V resource = null;
        try {
            checkNotClosed();
            // Must attempt a non blocking checkout before blockingGet to ensure
            // resources are created for the pool.
            resource = attemptNonBlockingCheckout(key, resourcePool);

            if(resource == null) {
                long nonBlockingElapsedNs = System.nanoTime() - startNs;
                long timeRemainingNs = resourcePoolConfig.getTimeout(TimeUnit.NANOSECONDS)
                                       - nonBlockingElapsedNs;

                if(timeRemainingNs > 0) {
                    resource = resourcePool.blockingGet(timeRemainingNs);
                }

                if(resource == null) {
                    long totalElapsedNs = System.nanoTime() - startNs;
                    long blockingElapsedNs = totalElapsedNs - nonBlockingElapsedNs;
                    String errorMessage = String.format("Timeout while checking out resource (%s). Configured time (%d) ns NonBlocking time (%d) ns Blocking time (%d) ns ",
                                                        key,
                                                        resourcePoolConfig.getTimeout(TimeUnit.NANOSECONDS),
                                                        nonBlockingElapsedNs,
                                                        blockingElapsedNs);
                    throw new TimeoutException(errorMessage);
                }
            }

            if(!objectFactory.validate(key, resource))
                throw new ExcessiveInvalidResourcesException(1);
        } catch(Exception e) {
            destroyResource(key, resourcePool, resource);
            throw e;
        }
        return resource;
    }

    /**
     * Get a free resource if one exists. If there are no free resources,
     * attempt to create a new resource (up to the max allowed for the pool).
     * This method does not block per se. However, creating a resource may be
     * (relatively) expensive. This method either returns null or a resource.
     *
     * This method is the only way in which new resources are created for the
     * pool. So, non blocking checkouts must be attempted to populate the
     * resource pool.
     */
    protected V attemptNonBlockingCheckout(K key, Pool<V> pool) throws Exception {
        V resource = pool.nonBlockingGet();
        if(resource == null) {
            while(pool.attemptGrow(key, this.objectFactory)) {
                resource = pool.nonBlockingGet();
                if(resource != null)
                    break;
            }
        }
        return resource;
    }

    /**
     * Get the pool for the given key. If no pool exists, create one.
     */
    protected Pool<V> getResourcePoolForKey(K key) {
        Pool<V> resourcePool = resourcePoolMap.get(key);
        if(resourcePool == null) {
            Pool<V> newResourcePool = new Pool<V>(this.resourcePoolConfig);
            resourcePool = resourcePoolMap.putIfAbsent(key, newResourcePool);
            if(resourcePool == null) {
                resourcePool = newResourcePool;
            }
        }
        return resourcePool;
    }

    /**
     * Get the pool for the given key. If no pool exists, throw an exception.
     */
    protected Pool<V> getResourcePoolForExistingKey(K key) {
        Pool<V> resourcePool = resourcePoolMap.get(key);
        if(resourcePool == null) {
            throw new IllegalArgumentException("Invalid key '" + key
                                               + "': no resource pool exists for that key.");
        }
        return resourcePool;
    }

    /*
     * A "safe" wrapper to destroy the given resource that catches any user
     * exceptions. This wrapper is safe in that it does not throw any
     * exceptions. However, this wrapper updates the size of the resource pool
     * and so should be called no more than once for any resource.
     */
    protected void destroyResource(K key, Pool<V> resourcePool, V resource) {
        if(resource != null) {
            try {
                objectFactory.destroy(key, resource);
            } catch(Exception e) {
                logger.error("Exception while destroying invalid resource: ", e);
            } finally {
                // Assumes destroyed resource was in fact checked out of the
                // pool. Also assumes that this method will be called no more
                // than once for any given checked out resource.
                resourcePool.size.decrementAndGet();
            }
        }
    }

    /**
     * Check the given resource back into the pool
     *
     * @param key The key for the resource
     * @param resource The resource
     */
    public void checkin(K key, V resource) throws Exception {
        if(isOpenAndValid(key, resource)) {
            Pool<V> resourcePool = getResourcePoolForExistingKey(key);
            boolean success = resourcePool.nonBlockingPut(resource);
            if(!success) {
                destroyResource(key, resourcePool, resource);
                throw new IllegalStateException("Checkin failed. Is the pool already full? (NB: see if KeyedResourcePool::destroyResource is being called multiple times.)");
            }
        }
    }

    protected boolean isOpenAndValid(K key, V resource) throws Exception {
        if(isOpen.get() && objectFactory.validate(key, resource)) {
            return true;
        } else {
            Pool<V> resourcePool = getResourcePoolForExistingKey(key);
            destroyResource(key, resourcePool, resource);
            return false;
        }
    }

    protected boolean internalClose() {
        boolean wasOpen = isOpen.compareAndSet(true, false);
        // change state to false and allow one thread.
        if(wasOpen) {
            for(Entry<K, Pool<V>> entry: resourcePoolMap.entrySet()) {
                Pool<V> pool = entry.getValue();
                // destroy each resource in the queue
                for(V value = pool.nonBlockingGet(); value != null; value = pool.nonBlockingGet())
                    destroyResource(entry.getKey(), entry.getValue(), value);
                resourcePoolMap.remove(entry.getKey());
            }
        }
        return wasOpen;
    }

    /**
     * Close the pool. This will destroy all checked in resource immediately.
     * Once closed all attempts to checkout a new resource will fail. All
     * resources checked in after close is called will be immediately destroyed.
     */
    public void close() {
        internalClose();
    }

    /**
     * Reset a specific resource pool. Destroys all of the idle resources in the
     * pool. This method does not affect whether the pool is "open" in the sense
     * of permitting new resources to be added to it.
     *
     * @param key The key for the pool to reset.
     */
    public void reset(K key) {
        if(resourcePoolMap.containsKey(key)) {
            Pool<V> resourcePool = getResourcePoolForExistingKey(key);
            List<V> list = resourcePool.close();
            for(V value: list)
                destroyResource(key, resourcePool, value);
        }
    }

    /**
     * Count the number of existing resources for a specific pool.
     *
     * @param key The key
     * @return The count of existing resources. Returns 0 if no pool exists for
     *         given key.
     */
    public int getTotalResourceCount(K key) {
        if(resourcePoolMap.containsKey(key)) {
            try {
                Pool<V> resourcePool = getResourcePoolForExistingKey(key);
                return resourcePool.size.get();
            } catch(IllegalArgumentException iae) {
                if(logger.isDebugEnabled()) {
                    logger.debug("getTotalResourceCount called on invalid key: ", iae);
                }
            }
        }
        return 0;
    }

    /**
     * Count the total number of existing resources for all pools. The result is
     * "approximate" in the face of concurrency since individual pools can
     * change size during the aggregate count.
     *
     * @return The (approximate) aggregate count of existing resources.
     */
    public int getTotalResourceCount() {
        int count = 0;
        for(Entry<K, Pool<V>> entry: this.resourcePoolMap.entrySet())
            count += entry.getValue().size.get();
        return count;
    }

    /**
     * Count the number of checked in (idle) resources for a specific pool.
     *
     * @param key The key
     * @return The count of checked in resources. Returns 0 if no pool exists
     *         for given key.
     */
    public int getCheckedInResourcesCount(K key) {
        if(resourcePoolMap.containsKey(key)) {
            try {
                Pool<V> resourcePool = getResourcePoolForExistingKey(key);
                return resourcePool.queue.size();
            } catch(IllegalArgumentException iae) {
                if(logger.isDebugEnabled()) {
                    logger.debug("getCheckedInResourceCount called on invalid key: ", iae);
                }
            }
        }
        return 0;
    }

    /**
     * Count the total number of checked in (idle) resources across all pools.
     * The result is "approximate" in the face of concurrency since individual
     * pools can have resources checked in, or out, during the aggregate count.
     *
     * @return The (approximate) aggregate count of checked in resources.
     */
    public int getCheckedInResourceCount() {
        int count = 0;
        for(Entry<K, Pool<V>> entry: this.resourcePoolMap.entrySet())
            count += entry.getValue().queue.size();
        return count;
    }

    /**
     * Count the number of blocking gets for a specific key.
     *
     * @param key The key
     * @return The count of blocking gets. Returns 0 if no pool exists for given
     *         key.
     */
    public int getBlockingGetsCount(K key) {
        if(resourcePoolMap.containsKey(key)) {
            try {
                Pool<V> resourcePool = getResourcePoolForExistingKey(key);
                return resourcePool.blockingGets.get();
            } catch(IllegalArgumentException iae) {
                if(logger.isDebugEnabled()) {
                    logger.debug("getBlockingGetsCount called on invalid key: ", iae);
                }
            }
        }
        return 0;
    }

    /**
     * Count the total number of blocking gets across all pools. The result is
     * "approximate" in the face of concurrency since blocking gets for
     * individual pools can be issued or serviced during the aggregate count.
     *
     * @return The (approximate) aggregate count of blocking gets.
     */
    public int getBlockingGetsCount() {
        int count = 0;
        for(Entry<K, Pool<V>> entry: this.resourcePoolMap.entrySet())
            count += entry.getValue().blockingGets.get();
        return count;
    }

    /**
     * Check that the pool is not closed, and throw an IllegalStateException if
     * it is.
     */
    protected void checkNotClosed() {
        if(!isOpen.get())
            throw new IllegalStateException("Pool is closed!");
    }

    /**
     * A fixed size pool that uses an ArrayBlockingQueue. The pool grows to no
     * more than some specified maxPoolSize. The pool creates new resources in
     * the face of existing resources being destroyed.
     *
     */
    protected static class Pool<V> {

        final private AtomicInteger size = new AtomicInteger(0);
        final private AtomicInteger blockingGets = new AtomicInteger(0);
        final private int maxPoolSize;
        final private BlockingQueue<V> queue;

        public Pool(ResourcePoolConfig resourcePoolConfig) {
            this.maxPoolSize = resourcePoolConfig.getMaxPoolSize();
            queue = new ArrayBlockingQueue<V>(this.maxPoolSize, resourcePoolConfig.isFair());
        }

        /**
         * If there is room in the pool, attempt to to create a new resource and
         * add it to the pool. This method is cheap to call even if the pool is
         * full (i.e., the first thing it does is looks a the current size of
         * the pool relative to the max pool size.
         *
         * @param key
         * @param objectFactory
         * @return True if and only if a resource was successfully added to the
         *         pool.
         * @throws Exception if there are issues creating a new object, or
         *         destroying newly created object that could not be added to
         *         the pool.
         *
         */
        public <K> boolean attemptGrow(K key, ResourceFactory<K, V> objectFactory) throws Exception {
            if(this.size.get() >= this.maxPoolSize) {
                return false;
            }

            if(this.size.incrementAndGet() <= this.maxPoolSize) {
                try {
                    V resource = objectFactory.create(key);
                    if(resource != null) {
                        if(!nonBlockingPut(resource)) {
                            this.size.decrementAndGet();
                            objectFactory.destroy(key, resource);
                            if(logger.isInfoEnabled()) {
                                logger.info("attemptGrow established new connection for key "
                                            + key.toString()
                                            + " and immediately destroyed the new connection "
                                            + "because there were too many connections already established.");
                            }
                            return false;
                        }
                        if(logger.isDebugEnabled()) {
                            logger.debug("attemptGrow established new connection for key "
                                         + key.toString() + ". "
                                         + " After checking in to KeyedResourcePool, there are "
                                         + queue.size() + " destinations checked in.");
                        }
                    }
                } catch(Exception e) {
                    // If nonBlockingPut throws an exception, then we could leak
                    // the resource created by objectFactory.create().
                    this.size.decrementAndGet();
                    throw e;
                }
            } else {
                this.size.decrementAndGet();
                return false;
            }
            return true;
        }

        public V nonBlockingGet() {
            return this.queue.poll();
        }

        public V blockingGet(long timeoutNs) throws InterruptedException {
            V v;
            try {
                blockingGets.incrementAndGet();
                v = this.queue.poll(timeoutNs, TimeUnit.NANOSECONDS);
            } finally {
                blockingGets.decrementAndGet();
            }
            return v;
        }

        public boolean nonBlockingPut(V v) {
            return this.queue.offer(v);
        }

        public List<V> close() {
            List<V> list = new ArrayList<V>();
            queue.drainTo(list);
            return list;
        }

    }
}


text:
package com.rmn.testrail.entity;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * @author Colin McCormack
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestRunCreator extends BaseEntity {

    @JsonProperty("name")
    private String name;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @JsonProperty("description")
    private String description;
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }

    @JsonProperty("suite_id")
    private Integer suiteId;
    public Integer getSuiteId() { return suiteId; }
    public void setSuiteId(Integer suiteId) { this.suiteId = suiteId; }

    @JsonProperty("milestone_id")
    private Integer milestoneId;
    public Integer getMilestoneId() { return milestoneId; }
    public void setMilestoneId(Integer milestoneId) { this.milestoneId = milestoneId; }

    @JsonProperty("include_all")
    private Boolean includeAll;
    public Boolean isIncludeAll() { return includeAll; }
    public void setIncludeAll(Boolean includeAll) { this.includeAll = includeAll; }

}

redpajama_set_name: RedPajamaGithub


text:
import re

import page_sets

from core import perf_benchmark
from telemetry import benchmark
from telemetry.page import legacy_page_test
from telemetry.value import scalar
from telemetry.value import improvement_direction
from telemetry.timeline import chrome_trace_category_filter
from telemetry.web_perf import timeline_based_measurement

class _OortOnlineMeasurement(legacy_page_test.LegacyPageTest):

  def __init__(self):
    super(_OortOnlineMeasurement, self).__init__()

  def ValidateAndMeasurePage(self, page, tab, results):
    del page  # unused
    tab.WaitForJavaScriptExpression('window.benchmarkFinished', 1000)
    scores = tab.EvaluateJavaScript('window.benchmarkScore')
    for score in scores:
      valid = score['valid']
      if valid:
        results.AddValue(scalar.ScalarValue(
            results.current_page, score['name'], 'score', score['score'],
            important=True, improvement_direction=improvement_direction.UP))

@benchmark.Disabled('android')
class OortOnline(perf_benchmark.PerfBenchmark):
  """OortOnline benchmark that measures WebGL and V8 performance.
  URL: http://oortonline.gl/#run
  Info: http://v8project.blogspot.de/2015/10/jank-busters-part-one.html
  """
  test = _OortOnlineMeasurement

  @classmethod
  def Name(cls):
    return 'oortonline'

  def CreateStorySet(self, options):
    return page_sets.OortOnlinePageSet()

# Disabled on reference builds because they don't support the new
# Tracing.requestMemoryDump DevTools API. See http://crbug.com/540022.
@benchmark.Disabled('reference')
@benchmark.Disabled('android')
@benchmark.Disabled('win')
class OortOnlineTBMv2(perf_benchmark.PerfBenchmark):
  """OortOnline benchmark that measures WebGL and V8 performance.
  URL: http://oortonline.gl/#run
  Info: http://v8project.blogspot.de/2015/10/jank-busters-part-one.html
  """

  # Report only V8-specific and overall renderer memory values. Note that
  # detailed values reported by the OS (such as native heap) are excluded.
  _V8_AND_OVERALL_MEMORY_RE = re.compile(
      r'renderer_processes:'
      r'(reported_by_chrome:v8|reported_by_os:system_memory:[^:]+$)')

  page_set = page_sets.OortOnlineTBMPageSet

  def SetExtraBrowserOptions(self, options):
    options.AppendExtraBrowserArgs([
        # TODO(perezju): Temporary workaround to disable periodic memory dumps.
        # See: http://crbug.com/513692
        '--enable-memory-benchmarking',
    ])

  def CreateTimelineBasedMeasurementOptions(self):
    categories = [
      # Implicitly disable all categories.
      '-*',
      # V8.
      'blink.console',
      'disabled-by-default-v8.gc',
      'renderer.scheduler',
      'v8',
      'webkit.console',
      # Smoothness.
      'benchmark',
      'blink',
      'blink.console',
      'trace_event_overhead',
      'webkit.console',
      # Memory.
      'blink.console',
      'disabled-by-default-memory-infra'
    ]
    category_filter = chrome_trace_category_filter.ChromeTraceCategoryFilter(
        ','.join(categories))
    options = timeline_based_measurement.Options(category_filter)
    options.SetTimelineBasedMetrics([
        'gcMetric', 'memoryMetric', 'responsivenessMetric'])
    return options

  @classmethod
  def Name(cls):
    return 'oortonline_tbmv2'

  @classmethod
  def ValueCanBeAddedPredicate(cls, value, _):
    if 'memory:chrome' in value.name:
      return bool(cls._V8_AND_OVERALL_MEMORY_RE.search(value.name))
    if 'animation ' in value.name:
      return 'throughput' in value.name or 'frameTimeDiscrepancy' in value.name
    return 'v8' in value.name


text:
require 'test_helper'

class ScryptoTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Scrypto
  end
end


text:
layout: post
title: How I Intend to Help Steer GHC
date: 2019-07-11 17:40
comments: true
tags: goals
---

Yesterday I was (somewhat surprisingly) brought on as a new member of the GHC
steering committee. I believe transparency is very important in situations like
these, and so I'd like to outline my intentions for my tenure in the committee.

I nominated myself because of problems I perceived in the status-quo. Lately,
there have been a few notable cases of dissatisfaction in the community with the
proposal process. I have certainly had my qualms with it in the past, but I
decided that rather than complain about it, I should just get involved and try
my best to help.

Which takes us to today.

I'm extremely humbled to be included with such a group of incredible individuals
as my co-committee members are. I don't claim to know everything about writing
industrial-grade compilers, nor about the intricacies of cutting-edge type
system research. Most of the time I'm only barely smart enough to keep up with
the conversation, let alone have a strongly informed opinion on the topic. WIth
that in mind...

---

**I don't intend to be a gatekeeper.**  Instead, I intend to be a facilitator;
someone whose job it is is to know the right people to bring into the
discussion. Nobody in this community is an expert at everything, but everyone
has a niche in which they are an expert. I want to make sure that those people
are involved in the process in which their expertise can be used.

That's not to say I'm not going to do everything in my power to understand each
and every proposal under my stewardship. Just that I'll be the first to admit
that I don't know everything, and I don't want *my* understanding to get in the
way of good ideas!

---

**I intend to inspire the committee to *move faster.*** I think any process which
can take upwards of two years is too slow --- it's a waste of everyone's time,
energy and attention. My preference is fast responses to proposals, whether it
be yea or nay. I don't want to railroad any decisions, but I also don't want to
sit on the fence out of fear of making the wrong move.

Along those lines, I intend to enthusiastically support any quality-of-life
improvements to the language that are small in scope, compose well, and don't
get in the way of *active*, longer-term goals. Delaying a decision on the basis
of "there's probably a more general solution here that nobody has time to think
about, nor do they plan to actually propose" seems like a bad strategy for me. I
don't want to let perfect be the enemy of the *much better.*

---

**I intend to preemptively shut down discussions around bikeshedding.** Too
often bikeshedding completely derails the conversation. It's an enormous waste
of time. Feelings get hurt, and everyone just talks past one another anyway. I
intend to give the proposal author and the Simons the only say on bikeshedding
matters. They can canvas for opinions if they'd like, but in my opinion, should
do so outside the official proposal channels.

To be clear, I am *not* saying you shouldn't offer suggestions if they improve a
proposals' composability, type-safety, elegance or parsimony. But let's agree as
a community that opinions of style are just opinions, and are never going to
convince anyone anyway.

---

**I intend to remove as many barriers to entry as humanly possible.** The Haskell
community is by far the smartest, kindest, most incredible group of people I've
ever had the good fortune to be a part of. I firmly believe that each and every
one of us has great things to contribute to this community, and I suspect the
world would be a better place if more of us felt like we had some ownership over
the language.

Please take a moment to remember that Haskell is only as great as we make it.
There is no "community," nor is there a "GHCHQ." There are just people who step
up to solve the problems that they see. I encourage you to be one of those
people. You don't need permission. You just need to be kind, genuine and
hard-working. Remember that nobody involved in our community is stupid, and if
they "just don't get it," maybe your argument wasn't as persuasive as you
thought.

All of this goes beyond making proposals to the compiler. Be the community you
want to see. Don't assume somebody else is going to do it for you.

---

Last but not least, **I intend to be a good addition to this committee.** [I
solicit anonymous feedback](https://whatiswrongwith.me/isovector), so please
don't hesitate to call me out if you're ever unhappy with my behavior. I promise
to not be offended by any constructive feedback you send my way.

I will do my best to stay honest to these intentions, but help keep me in tow
when I slip up.

---

The GHC steering committee is a thankless job. I'd like to take a moment to
explicitly call out every member of the committee, past and present, for their
selfless commitments to the community. These are people who are taking time out
of their own research and projects in order to make our fantastic language much
more transparent than it would be otherwise. Really and truly, these people are
heroes, even if we don't always agree with their decisions. *Thank you,* from
the very bottom of my heart.

Finally, **I intend to live up to everyone's expectations.** Thanks for your
time.


text:
$(function() {
  $(".comments").each(function() {
    var container = $(this);
    $.get("/" +
          $(this).attr('data-commentable-type') +
          "/" +
          $(this).attr('data-commentable-id') +
          "/comments", function(response) {
            $(container).html(response);
          });
  });

  $(".cancel-new-comment").live("click", function(event) {
    event.preventDefault();
    $(this).parents("#new_comment").remove();
  });
});


text:
"""Cinder common internal object model"""

import contextlib
import datetime

from oslo_log import log as logging
from oslo_utils import versionutils
from oslo_versionedobjects import base
from oslo_versionedobjects import fields

from cinder import db
from cinder import exception
from cinder.i18n import _
from cinder import objects

LOG = logging.getLogger('object')
obj_make_list = base.obj_make_list

class CinderObjectVersionsHistory(dict):
    """Helper class that maintains objects version history.

    Current state of object versions is aggregated in a single version number
    that explicitly identifies a set of object versions. That way a service
    is able to report what objects it supports using a single string and all
    the newer services will know exactly what that mean for a single object.
    """

    def __init__(self):
        super(CinderObjectVersionsHistory, self).__init__()
        # NOTE(dulek): This is our pre-history and a starting point - Liberty.
        # We want Mitaka to be able to talk to Liberty services, so we need to
        # handle backporting to these objects versions (although I don't expect
        # we've made a lot of incompatible changes inside the objects).
        #
        # If an object doesn't exist in Liberty, RPC API compatibility layer
        # shouldn't send it or convert it to a dictionary.
        #
        # Please note that we do not need to add similar entires for each
        # release. Liberty is here just for historical reasons.
        self.versions = ['liberty']
        self['liberty'] = {
            'Backup': '1.1',
            'BackupImport': '1.1',
            'BackupList': '1.0',
            'ConsistencyGroup': '1.1',
            'ConsistencyGroupList': '1.0',
            'Service': '1.0',
            'ServiceList': '1.0',
            'Snapshot': '1.0',
            'SnapshotList': '1.0',
            'Volume': '1.1',
            'VolumeAttachment': '1.0',
            'VolumeAttachmentList': '1.0',
            'VolumeList': '1.1',
            'VolumeType': '1.0',
            'VolumeTypeList': '1.0',
        }

    def get_current(self):
        return self.versions[-1]

    def get_current_versions(self):
        return self[self.get_current()]

    def add(self, ver, updates):
        if ver in self.versions:
            msg = 'Version %s already exists in history.' % ver
            raise exception.ProgrammingError(reason=msg)

        self[ver] = self[self.get_current()].copy()
        self.versions.append(ver)
        self[ver].update(updates)

OBJ_VERSIONS = CinderObjectVersionsHistory()
# NOTE(dulek): You should add a new version here each time you bump a version
# of any object. As a second parameter you need to specify only what changed.
#
# When dropping backward compatibility with an OpenStack release we can rework
# this and remove some history while keeping the versions order.
OBJ_VERSIONS.add('1.0', {'Backup': '1.3', 'BackupImport': '1.3',
                         'CGSnapshot': '1.0', 'CGSnapshotList': '1.0',
                         'ConsistencyGroup': '1.2',
                         'ConsistencyGroupList': '1.1', 'Service': '1.1',
                         'Volume': '1.3', 'VolumeTypeList': '1.1'})
OBJ_VERSIONS.add('1.1', {'Service': '1.2', 'ServiceList': '1.1'})
OBJ_VERSIONS.add('1.2', {'Backup': '1.4', 'BackupImport': '1.4'})
OBJ_VERSIONS.add('1.3', {'Service': '1.3'})
OBJ_VERSIONS.add('1.4', {'Snapshot': '1.1'})
OBJ_VERSIONS.add('1.5', {'VolumeType': '1.1'})
OBJ_VERSIONS.add('1.6', {'QualityOfServiceSpecs': '1.0',
                         'QualityOfServiceSpecsList': '1.0',
                         'VolumeType': '1.2'})
OBJ_VERSIONS.add('1.7', {'Cluster': '1.0', 'ClusterList': '1.0',
                         'Service': '1.4', 'Volume': '1.4',
                         'ConsistencyGroup': '1.3'})
OBJ_VERSIONS.add('1.8', {'RequestSpec': '1.0', 'VolumeProperties': '1.0'})
OBJ_VERSIONS.add('1.9', {'GroupType': '1.0', 'GroupTypeList': '1.0'})
OBJ_VERSIONS.add('1.10', {'Group': '1.0', 'GroupList': '1.0', 'Volume': '1.5',
                          'RequestSpec': '1.1', 'VolumeProperties': '1.1'})
OBJ_VERSIONS.add('1.11', {'GroupSnapshot': '1.0', 'GroupSnapshotList': '1.0',
                          'Group': '1.1'})
OBJ_VERSIONS.add('1.12', {'VolumeType': '1.3'})
OBJ_VERSIONS.add('1.13', {'CleanupRequest': '1.0'})
OBJ_VERSIONS.add('1.14', {'VolumeAttachmentList': '1.1'})
OBJ_VERSIONS.add('1.15', {'Volume': '1.6', 'Snapshot': '1.2'})
OBJ_VERSIONS.add('1.16', {'BackupDeviceInfo': '1.0'})
OBJ_VERSIONS.add('1.17', {'VolumeAttachment': '1.1'})
OBJ_VERSIONS.add('1.18', {'Snapshot': '1.3'})
OBJ_VERSIONS.add('1.19', {'ConsistencyGroup': '1.4', 'CGSnapshot': '1.1'})
OBJ_VERSIONS.add('1.20', {'Cluster': '1.1'})
OBJ_VERSIONS.add('1.21', {'ManageableSnapshot': '1.0',
                          'ManageableVolume': '1.0',
                          'ManageableVolumeList': '1.0',
                          'ManageableSnapshotList': '1.0'})
OBJ_VERSIONS.add('1.22', {'Snapshot': '1.4'})
OBJ_VERSIONS.add('1.23', {'VolumeAttachment': '1.2'})
OBJ_VERSIONS.add('1.24', {'LogLevel': '1.0', 'LogLevelList': '1.0'})
OBJ_VERSIONS.add('1.25', {'Group': '1.2'})
OBJ_VERSIONS.add('1.26', {'Snapshot': '1.5'})
OBJ_VERSIONS.add('1.27', {'Backup': '1.5', 'BackupImport': '1.5'})

class CinderObjectRegistry(base.VersionedObjectRegistry):
    def registration_hook(self, cls, index):
        """Hook called when registering a class.

        This method takes care of adding the class to cinder.objects namespace.

        Should registering class have a method called cinder_ovo_cls_init it
        will be called to support class initialization.  This is convenient
        for all persistent classes that need to register their models.
        """
        setattr(objects, cls.obj_name(), cls)

        # If registering class has a callable initialization method, call it.
        if callable(getattr(cls, 'cinder_ovo_cls_init', None)):
            cls.cinder_ovo_cls_init()

class CinderObject(base.VersionedObject):
    # NOTE(thangp): OBJ_PROJECT_NAMESPACE needs to be set so that nova,
    # cinder, and other objects can exist on the same bus and be distinguished
    # from one another.
    OBJ_PROJECT_NAMESPACE = 'cinder'

    def cinder_obj_get_changes(self):
        """Returns a dict of changed fields with tz unaware datetimes.

        Any timezone aware datetime field will be converted to UTC timezone
        and returned as timezone unaware datetime.

        This will allow us to pass these fields directly to a db update
        method as they can't have timezone information.
        """
        # Get dirtied/changed fields
        changes = self.obj_get_changes()

        # Look for datetime objects that contain timezone information
        for k, v in changes.items():
            if isinstance(v, datetime.datetime) and v.tzinfo:
                # Remove timezone information and adjust the time according to
                # the timezone information's offset.
                changes[k] = v.replace(tzinfo=None) - v.utcoffset()

        # Return modified dict
        return changes

    def obj_make_compatible(self, primitive, target_version):
        _log_backport(self, target_version)
        super(CinderObject, self).obj_make_compatible(primitive,
                                                      target_version)

    def __contains__(self, name):
        # We're using obj_extra_fields to provide aliases for some fields while
        # in transition period. This override is to make these aliases pass
        # "'foo' in obj" tests.
        return name in self.obj_extra_fields or super(CinderObject,
                                                      self).__contains__(name)

class CinderObjectDictCompat(base.VersionedObjectDictCompat):
    """Mix-in to provide dictionary key access compat.

    If an object needs to support attribute access using
    dictionary items instead of object attributes, inherit
    from this class. This should only be used as a temporary
    measure until all callers are converted to use modern
    attribute access.

    NOTE(berrange) This class will eventually be deleted.
    """

    def get(self, key, value=base._NotSpecifiedSentinel):
        """For backwards-compatibility with dict-based objects.

        NOTE(danms): May be removed in the future.
        """
        if key not in self.obj_fields:
            # NOTE(jdg): There are a number of places where we rely on the
            # old dictionary version and do a get(xxx, None).
            # The following preserves that compatibility but in
            # the future we'll remove this shim altogether so don't
            # rely on it.
            LOG.debug('Cinder object %(object_name)s has no '
                      'attribute named: %(attribute_name)s',
                      {'object_name': self.__class__.__name__,
                       'attribute_name': key})
            return None
        if (value != base._NotSpecifiedSentinel and
                key not in self.obj_extra_fields and
                not self.obj_attr_is_set(key)):
            return value
        else:
            try:
                return getattr(self, key)
            except (exception.ObjectActionError, NotImplementedError):
                # Exception when haven't set a value for non-lazy
                # loadable attribute, but to mimic typical dict 'get'
                # behavior we should still return None
                return None

class CinderPersistentObject(object):
    """Mixin class for Persistent objects.

    This adds the fields that we use in common for all persistent objects.
    """
    OPTIONAL_FIELDS = []

    Not = db.Not
    Case = db.Case

    fields = {
        'created_at': fields.DateTimeField(nullable=True),
        'updated_at': fields.DateTimeField(nullable=True),
        'deleted_at': fields.DateTimeField(nullable=True),
        'deleted': fields.BooleanField(default=False,
                                       nullable=True),
    }

    @classmethod
    def cinder_ovo_cls_init(cls):
        """This method is called on OVO registration and sets the DB model."""
        # Persistent Versioned Objects Classes should have a DB model, and if
        # they don't, then we have a problem and we must raise an exception on
        # registration.
        try:
            cls.model = db.get_model_for_versioned_object(cls)
        except (ImportError, AttributeError):
            msg = _("Couldn't find ORM model for Persistent Versioned "
                    "Object %s.") % cls.obj_name()
            raise exception.ProgrammingError(reason=msg)

    @contextlib.contextmanager
    def obj_as_admin(self):
        """Context manager to make an object call as an admin.

        This temporarily modifies the context embedded in an object to
        be elevated() and restores it after the call completes. Example
        usage:

           with obj.obj_as_admin():
               obj.save()
        """
        if self._context is None:
            raise exception.OrphanedObjectError(method='obj_as_admin',
                                                objtype=self.obj_name())

        original_context = self._context
        self._context = self._context.elevated()
        try:
            yield
        finally:
            self._context = original_context

    @classmethod
    def _get_expected_attrs(cls, context, *args, **kwargs):
        return None

    @classmethod
    def get_by_id(cls, context, id, *args, **kwargs):
        # To get by id we need to have a model and for the model to
        # have an id field
        if 'id' not in cls.fields:
            msg = (_('VersionedObject %s cannot retrieve object by id.') %
                   (cls.obj_name()))
            raise NotImplementedError(msg)

        orm_obj = db.get_by_id(context, cls.model, id, *args, **kwargs)
        # We pass parameters because fields to expect may depend on them
        expected_attrs = cls._get_expected_attrs(context, *args, **kwargs)
        kargs = {}
        if expected_attrs:
            kargs = {'expected_attrs': expected_attrs}
        return cls._from_db_object(context, cls(context), orm_obj, **kargs)

    def update_single_status_where(self, new_status,
                                   expected_status, filters=()):
        values = {'status': new_status}
        expected_status = {'status': expected_status}
        return self.conditional_update(values, expected_status, filters)

    def conditional_update(self, values, expected_values=None, filters=(),
                           save_all=False, session=None, reflect_changes=True,
                           order=None):
        """Compare-and-swap update.

        A conditional object update that, unlike normal update, will SAVE the
        contents of the update to the DB.

        Update will only occur in the DB and the object if conditions are met.

        If no expected_values are passed in we will default to make sure that
        all fields have not been changed in the DB. Since we cannot know the
        original value in the DB for dirty fields in the object those will be
        excluded.

        We have 4 different condition types we can use in expected_values:
         - Equality:  {'status': 'available'}
         - Inequality: {'status': vol_obj.Not('deleting')}
         - In range: {'status': ['available', 'error']
         - Not in range: {'status': vol_obj.Not(['in-use', 'attaching'])

        Method accepts additional filters, which are basically anything that
        can be passed to a sqlalchemy query's filter method, for example:

        .. code-block:: python

         [~sql.exists().where(models.Volume.id == models.Snapshot.volume_id)]

        We can select values based on conditions using Case objects in the
        'values' argument. For example:

        .. code-block:: python

         has_snapshot_filter = sql.exists().where(
             models.Snapshot.volume_id == models.Volume.id)
         case_values = volume.Case([(has_snapshot_filter, 'has-snapshot')],
                                   else_='no-snapshot')
         volume.conditional_update({'status': case_values},
                                   {'status': 'available'}))

        And we can use DB fields using model class attribute for example to
        store previous status in the corresponding field even though we don't
        know which value is in the db from those we allowed:

        .. code-block:: python

         volume.conditional_update({'status': 'deleting',
                                    'previous_status': volume.model.status},
                                   {'status': ('available', 'error')})

        :param values: Dictionary of key-values to update in the DB.
        :param expected_values: Dictionary of conditions that must be met for
                                the update to be executed.
        :param filters: Iterable with additional filters
        :param save_all: Object may have changes that are not in the DB, this
                         will say whether we want those changes saved as well.
        :param session: Session to use for the update
        :param reflect_changes: If we want changes made in the database to be
                                reflected in the versioned object.  This may
                                mean in some cases that we have to reload the
                                object from the database.
        :param order: Specific order of fields in which to update the values
        :returns: number of db rows that were updated, which can be used as a
                  boolean, since it will be 0 if we couldn't update the DB and
                  1 if we could, because we are using unique index id.
        """
        if 'id' not in self.fields:
            msg = (_('VersionedObject %s does not support conditional update.')
                   % (self.obj_name()))
            raise NotImplementedError(msg)

        # If no conditions are set we will require object in DB to be unchanged
        if expected_values is None:
            changes = self.obj_what_changed()

            expected = {key: getattr(self, key)
                        for key in self.fields.keys()
                        if self.obj_attr_is_set(key) and key not in changes and
                        key not in self.OPTIONAL_FIELDS}
        else:
            # Set the id in expected_values to limit conditional update to only
            # change this object
            expected = expected_values.copy()
            expected['id'] = self.id

        # If we want to save any additional changes the object has besides the
        # ones referred in values
        if save_all:
            changes = self.cinder_obj_get_changes()
            changes.update(values)
            values = changes

        result = db.conditional_update(self._context, self.model, values,
                                       expected, filters, order=order)

        # If we were able to update the DB then we need to update this object
        # as well to reflect new DB contents and clear the object's dirty flags
        # for those fields.
        if result and reflect_changes:
            # If we have used a Case, a db field or an expression in values we
            # don't know which value was used, so we need to read the object
            # back from the DB
            if any(isinstance(v, self.Case) or db.is_orm_value(v)
                   for v in values.values()):
                # Read back object from DB
                obj = type(self).get_by_id(self._context, self.id)
                db_values = obj.obj_to_primitive()['versioned_object.data']
                # Only update fields were changes were requested
                values = {field: db_values[field]
                          for field, value in values.items()}

            # NOTE(geguileo): We don't use update method because our objects
            # will eventually move away from VersionedObjectDictCompat
            for key, value in values.items():
                setattr(self, key, value)
            self.obj_reset_changes(values.keys())
        return result

    def refresh(self):
        # To refresh we need to have a model and for the model to have an id
        # field
        if 'id' not in self.fields:
            msg = (_('VersionedObject %s cannot retrieve object by id.') %
                   (self.obj_name()))
            raise NotImplementedError(msg)

        current = self.get_by_id(self._context, self.id)

        # Copy contents retrieved from the DB into self
        my_data = vars(self)
        my_data.clear()
        my_data.update(vars(current))

    @classmethod
    def exists(cls, context, id_):
        return db.resource_exists(context, cls.model, id_)

class CinderComparableObject(base.ComparableVersionedObject):
    def __eq__(self, obj):
        if hasattr(obj, 'obj_to_primitive'):
            return self.obj_to_primitive() == obj.obj_to_primitive()
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

class ObjectListBase(base.ObjectListBase):
    def obj_make_compatible(self, primitive, target_version):
        _log_backport(self, target_version)
        super(ObjectListBase, self).obj_make_compatible(primitive,
                                                        target_version)

class ClusteredObject(object):
    @property
    def service_topic_queue(self):
        return self.cluster_name or self.host

    @property
    def is_clustered(self):
        return bool(self.cluster_name)

    def assert_not_frozen(self):
        ctxt = self._context.elevated()
        if db.is_backend_frozen(ctxt, self.host, self.cluster_name):
            msg = _('Modification operations are not allowed on frozen '
                    'storage backends.')
            raise exception.InvalidInput(reason=msg)

class CinderObjectSerializer(base.VersionedObjectSerializer):
    OBJ_BASE_CLASS = CinderObject

    def __init__(self, version_cap=None):
        super(CinderObjectSerializer, self).__init__()
        self.version_cap = version_cap

        # NOTE(geguileo): During upgrades we will use a manifest to ensure that
        # all objects are properly backported.  This allows us to properly
        # backport child objects to the right version even if parent version
        # has not been bumped.
        if not version_cap or version_cap == OBJ_VERSIONS.get_current():
            self.manifest = None
        else:
            if version_cap not in OBJ_VERSIONS:
                raise exception.CappedVersionUnknown(version=version_cap)
            self.manifest = OBJ_VERSIONS[version_cap]

    def _get_capped_obj_version(self, obj):
        objname = obj.obj_name()
        version_dict = OBJ_VERSIONS.get(self.version_cap, {})
        version_cap = version_dict.get(objname, None)

        if version_cap:
            cap_tuple = versionutils.convert_version_to_tuple(version_cap)
            obj_tuple = versionutils.convert_version_to_tuple(obj.VERSION)
            if cap_tuple > obj_tuple:
                # NOTE(dulek): Do not set version cap to be higher than actual
                # object version as we don't support "forwardporting" of
                # objects. If service will receive an object that's too old it
                # should handle it explicitly.
                version_cap = None

        return version_cap

    def serialize_entity(self, context, entity):
        if isinstance(entity, (tuple, list, set, dict)):
            entity = self._process_iterable(context, self.serialize_entity,
                                            entity)
        elif (hasattr(entity, 'obj_to_primitive') and
              callable(entity.obj_to_primitive)):
            # NOTE(dulek): Backport outgoing object to the capped version.
            backport_ver = self._get_capped_obj_version(entity)
            entity = entity.obj_to_primitive(backport_ver, self.manifest)
        return entity

def _log_backport(ovo, target_version):
    """Log backported versioned objects."""
    if target_version and target_version != ovo.VERSION:
        LOG.debug('Backporting %(obj_name)s from version %(src_vers)s '
                  'to version %(dst_vers)s',
                  {'obj_name': ovo.obj_name(),
                   'src_vers': ovo.VERSION,
                   'dst_vers': target_version})


text:
*Accelerating the Process of Discovery*<br>
by Frances Haugen, Patrick Phelps

- [Abstract](https://us.pycon.org/2016/schedule/presentation/2245/)

How Yelp's Search and Ads teams use IPython notebooks for data science and data engineering.


text:
WinQueueStream::WinQueueStream():base_(0){
}

bool
WinQueueStream::initialize(){
	base_ = SHCreateMemStream(NULL, 0);
	if (base_ == 0)
		return false;
	base_->AddRef();
	return true;
}

IStream*
WinQueueStream::getBaseStream(){
	return base_;
}

void
WinQueueStream::startWritingPhase(){
	LARGE_INTEGER zero = { 0 };
	base_->Seek(zero, STREAM_SEEK_SET, NULL);
	base_->SetSize(*reinterpret_cast<ULARGE_INTEGER*>(&zero));
}

void
WinQueueStream::endWritingPhase(){
	LARGE_INTEGER zero = { 0 };
	base_->Seek(zero, STREAM_SEEK_SET, NULL);
}

int WinQueueStream::in_avail(){
	if (base_ == 0)
		return 0;
	STATSTG stats;
	base_->Stat(&stats, STATFLAG_NONAME);
	return (stats.cbSize.HighPart == 0 ? stats.cbSize.LowPart : stats.cbSize.HighPart); //agnostic to endianness
}

const char*
WinQueueStream::nextChunk(int* size){
	ULONG read = 0;
	base_->Read(audio_, AUDIO_CHUNK_SIZE, &read);
	if (read == 0)
		return 0;
	*size = (int) read;
	return audio_;
}

void WinQueueStream::dispose(){
	if (base_ != 0){
		base_->Release();
		base_ = 0;
	}
}


text:
#![allow(dead_code)]
use std::io::Error as IoError;
use std::ffi::CString;
use std::ptr::null;
use std::path::Path;
use libc::{c_ulong, c_int};

use super::itertools::{NextValue, NextStr, words};
use super::utils::cpath;

// sys/mount.h
static MS_RDONLY: c_ulong = 1;                /* Mount read-only.  */
static MS_NOSUID: c_ulong = 2;                /* Ignore suid and sgid bits.  */
static MS_NODEV: c_ulong = 4;                 /* Disallow access to device special files.  */
static MS_NOEXEC: c_ulong = 8;                /* Disallow program execution.  */
static MS_SYNCHRONOUS: c_ulong = 16;          /* Writes are synced at once.  */
static MS_REMOUNT: c_ulong = 32;              /* Alter flags of a mounted FS.  */
static MS_MANDLOCK: c_ulong = 64;             /* Allow mandatory locks on an FS.  */
static MS_DIRSYNC: c_ulong = 128;             /* Directory modifications are synchronous.  */
static MS_NOATIME: c_ulong = 1024;            /* Do not update access times.  */
static MS_NODIRATIME: c_ulong = 2048;         /* Do not update directory access times.  */
static MS_BIND: c_ulong = 4096;               /* Bind directory at different place.  */
static MS_MOVE: c_ulong = 8192;
static MS_REC: c_ulong = 16384;
static MS_SILENT: c_ulong = 32768;
static MS_POSIXACL: c_ulong = 1 << 16;        /* VFS does not apply the umask.  */
static MS_UNBINDABLE: c_ulong = 1 << 17;      /* Change to unbindable.  */
static MS_PRIVATE: c_ulong = 1 << 18;         /* Change to private.  */
static MS_SLAVE: c_ulong = 1 << 19;           /* Change to slave.  */
static MS_SHARED: c_ulong = 1 << 20;          /* Change to shared.  */
static MS_RELATIME: c_ulong = 1 << 21;        /* Update atime relative to mtime/ctime.  */
static MS_KERNMOUNT: c_ulong = 1 << 22;       /* This is a kern_mount call.  */
static MS_I_VERSION: c_ulong =  1 << 23;      /* Update inode I_version field.  */
static MS_STRICTATIME: c_ulong = 1 << 24;     /* Always perform atime updates.  */
static MS_ACTIVE: c_ulong = 1 << 30;
static MS_NOUSER: c_ulong = 1 << 31;

static MNT_FORCE: c_int = 1;           /* Force unmounting.  */
static MNT_DETACH: c_int = 2;          /* Just detach from the tree.  */
static MNT_EXPIRE: c_int = 4;          /* Mark for expiry.  */
static UMOUNT_NOFOLLOW: c_int = 8;     /* Don't follow symlink on umount.  */

extern {
    fn mount(source: *const i8, target: *const i8,
        filesystemtype: *const i8, flags: c_ulong,
        data: *const i8) -> c_int;
    fn umount(target: *const i8) -> c_int;
    fn umount2(target: *const i8, flags: c_int) -> c_int;
}

pub struct MountRecord<'a> {
    pub mount_id: usize,
    pub parent_id: usize,
    _device: &'a str,  // TODO(tailhook) parse if ever need
    pub relative_root: &'a str,
    pub mount_point: &'a str,
    pub mount_options: &'a str,
    pub tag_shared: Option<usize>,
    pub tag_master: Option<usize>,
    pub tag_propagate_from: Option<usize>,
    pub tag_unbindable: Option<()>,
    pub fstype: &'a str,
    pub mount_source: &'a str,
    pub super_options: &'a str,
}

impl<'a> MountRecord<'a> {
    pub fn from_str<'x>(line: &'x str) -> Result<MountRecord<'x>, ()> {
        let mut parts = words(line);
        let mount_id = try!(parts.next_value());
        let parent_id = try!(parts.next_value());
        let device = try!(parts.next_str());
        let relative_root = try!(parts.next_str());
        let mount_point = try!(parts.next_str());
        let mount_options = try!(parts.next_str());
        let mut tag_shared = None;
        let mut tag_master = None;
        let mut tag_propagate_from = None;
        let mut tag_unbindable = None;

        for name in &mut parts {
            if name == "-" { break; }
            let mut pair = name.splitn(2, ':');
            let key = pair.next();
            match key {
                Some("shared") => {
                    tag_shared = Some(try!(pair.next_value()));
                }
                Some("master") => {
                    tag_master = Some(try!(pair.next_value()));
                }
                Some("propagate_from") => {
                    tag_propagate_from = Some(try!(pair.next_value()));
                }
                Some("unbindable") => tag_unbindable = Some(()),
                _ => {}
            }
        }

        let fstype = try!(parts.next_str());
        let mount_source = try!(parts.next_str());
        let super_options = try!(parts.next_str());

        return Ok(MountRecord {
            mount_id: mount_id,
            parent_id: parent_id,
            _device: device,
            relative_root: relative_root,
            mount_point: mount_point,
            mount_options: mount_options,
            tag_shared: tag_shared,
            tag_master: tag_master,
            tag_propagate_from: tag_propagate_from,
            tag_unbindable: tag_unbindable,
            fstype: fstype,
            mount_source: mount_source,
            super_options: super_options,
            });
    }
    pub fn is_private(&self) -> bool {
        return self.tag_shared.is_none()
            && self.tag_master.is_none()
            && self.tag_propagate_from.is_none()
            && self.tag_unbindable.is_none();
    }
}

pub fn mount_ro_recursive(target: &Path) -> Result<(), String> {
    let none = CString::new("none").unwrap();
    debug!("Remount readonly: {:?}", target);
    let c_target = cpath(target);
    let rc = unsafe { mount(
       none.as_ptr(),
       c_target.as_ptr(),
       null(), MS_BIND|MS_REMOUNT|MS_RDONLY, null()) };
    if rc != 0 {
        let err = IoError::last_os_error();
        return Err(format!("Remount readonly {}: {}", target.display(), err));
    }
    return Ok(());
}

pub fn mount_private(target: &Path) -> Result<(), String> {
    let none = CString::new("none").unwrap();
    let c_target = cpath(target);
    debug!("Making private {:?}", target);
    let rc = unsafe { mount(
        none.as_ptr(),
        c_target.as_ptr(),
        null(), MS_REC|MS_PRIVATE, null()) };
    if rc == 0 {
        return Ok(());
    } else {
        let err = IoError::last_os_error();
        return Err(format!("Can't make {} a slave: {}",
            target.display(), err));
    }
}

pub fn mount_pseudo(target: &Path, name: &str, options: &str, readonly: bool)
    -> Result<(), String>
{
    let c_name = CString::new(name).unwrap();
    let c_target = cpath(target);
    let c_opts = CString::new(options).unwrap();
    let mut flags = MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_NOATIME;
    if readonly {
        flags |= MS_RDONLY;
    }
    debug!("Pseudofs mount {} {} {}", target.display(), name, options);
    let rc = unsafe { mount(
        c_name.as_ptr(),
        c_target.as_ptr(),
        c_name.as_ptr(),
        flags,
        c_opts.as_ptr()) };
    if rc == 0 {
        return Ok(());
    } else {
        let err = IoError::last_os_error();
        return Err(format!("Can't mount pseudofs {} ({}, options: {}): {}",
            target.display(), options, name, err));
    }
}

pub fn mount_pts(target: &Path)
    -> Result<(), String>
{
    let c_name = CString::new("devpts").unwrap();
    let c_target = cpath(target);
    let opts = "newinstance,ptmxmode=0666";
    let c_opts = CString::new(opts).unwrap();
    let flags = MS_NOSUID | MS_NOEXEC | MS_NOATIME;
    debug!("Pseudofs mount {} {} {}", target.display(), "devpts", opts);
    let rc = unsafe { mount(
        c_name.as_ptr(),
        c_target.as_ptr(),
        c_name.as_ptr(),
        flags,
        c_opts.as_ptr()) };
    if rc == 0 {
        return Ok(());
    } else {
        let err = IoError::last_os_error();
        return Err(format!("Can't mount pseudofs {} ({}, options: {}): {}",
            target.display(), opts, "devpts", err));
    }
}

pub fn unmount(target: &Path) -> Result<(), String> {
    let c_target = cpath(target);
    let rc = unsafe { umount2(c_target.as_ptr(), MNT_DETACH) };
    if rc == 0 {
        return Ok(());
    } else {
        let err = IoError::last_os_error();
        return Err(format!("Can't unmount {} : {}", target.display(), err));
    }
}


text:
require "cinch/exceptions"

module Cinch
  # @api private
  # @since 1.1.0
  module ModeParser
    ErrEmptyString = "Empty mode string"
    MalformedError = Struct.new(:modes)
    EmptySequenceError = Struct.new(:modes)
    NotEnoughParametersError = Struct.new(:op)
    TooManyParametersError = Struct.new(:modes, :params)

    # @param [String] modes The mode string as sent by the server
    # @param [Array<String>] params Parameters belonging to the modes
    # @param [Hash{:add, :remove => Array<String>}] param_modes
    #   A mapping describing which modes require parameters
    # @return [(Array<(Symbol<:add, :remove>, String<char>, String<param>), foo)]
    def self.parse_modes(modes, params, param_modes = {})
      if modes.size == 0
        return nil, ErrEmptyString
        # raise Exceptions::InvalidModeString, 'Empty mode string'
      end

      if modes[0] !~ /[+-]/
        return nil, MalformedError.new(modes)
        # raise Exceptions::InvalidModeString, "Malformed modes string: %s" % modes
      end

      changes = []

      direction = nil
      count = -1

      modes.each_char do |ch|
        if ch =~ /[+-]/
          if count == 0
            return changes, EmptySequenceError.new(modes)
            # raise Exceptions::InvalidModeString, 'Empty mode sequence: %s' % modes
          end

          direction = case ch
                      when "+"
                        :add
                      when "-"
                        :remove
                      end
          count = 0
        else
          param = nil
          if param_modes.has_key?(direction) && param_modes[direction].include?(ch)
            if params.size > 0
              param = params.shift
            else
              return changes, NotEnoughParametersError.new(ch)
              # raise Exceptions::InvalidModeString, 'Not enough parameters: %s' % ch.inspect
            end
          end
          changes << [direction, ch, param]
          count += 1
        end
      end

      if params.size > 0
        return changes, TooManyParametersError.new(modes, params)
        # raise Exceptions::InvalidModeString, 'Too many parameters: %s %s' % [modes, params]
      end

      if count == 0
        return changes, EmptySequenceError.new(modes)
        # raise Exceptions::InvalidModeString, 'Empty mode sequence: %s' % modes
      end

      return changes, nil
    end
  end
end


text:
"""Process methylation array data."""
import gzip
import shutil
from pathlib import Path

from plumbum import TEE

from resolwe.process import (
    Cmd,
    DataField,
    FileField,
    Persistence,
    SchedulingClass,
    StringField,
)

from resolwe_bio.process.runtime import ProcessBio

class MethylationArraySesame(ProcessBio):
    """Illumina methylation array SeSAMe process.

    Implemented SeSAMe method for analyzing methylation array from
    Illumina. For more information on the pipeline, please see
    https://www.bioconductor.org/packages/release/bioc/html/sesame.html

    This process will input IDAT methylation array files and
    produce two results. One is the quality control file with
    some basic statistics, such as mean beta, fraction of
    (un)methylated, GCT, predicted ethnicity, gender and age.
    Methylation data file holds betas, mvals and pvals for probe ids.
    In addition, Ensembl IDs and HGNC gene symbol names are provided,
    along with chromosome and start/end positions of CpG sites
    (1-based).
    """

    slug = "methylation-array-sesame"
    name = "Methylation analysis (SeSAMe)"
    process_type = "data:methylation:sesame"
    version = "1.4.0"
    category = "Methylation arrays"
    data_name = 'SeSAMe array ({{ idat_file.red_channel.file|default("?") }})'
    scheduling_class = SchedulingClass.BATCH
    persistence = Persistence.CACHED
    entity = {"type": "sample"}
    requirements = {
        "expression-engine": "jinja",
        "executor": {
            "docker": {
                "image": "public.ecr.aws/s4q6j6e8/resolwebio/methylation_arrays:1.1.0"
            }
        },
        "resources": {
            "cores": 8,
            "memory": 16384,
        },
    }

    class Input:
        """Input fields to process MethylationArraySesame."""

        idat_file = DataField(
            data_type="methylationarray:idat",
            label="Illumina methylation array IDAT file",
            description="Illumina methylation array BeadChip raw IDAT file.",
        )

    class Output:
        """Output fields to process MethylationArraySesame."""

        methylation_data = FileField(label="A gzipped tab delimited file (txt.gz)")
        qc_data = FileField(label="Quality control information from SeSAMe analysis")
        species = StringField(label="Species")
        platform = StringField(label="Platform used in the analysis")

    def run(self, inputs, outputs):
        """Run MethylationArraySesame process."""

        dirdata = Path("./data")
        if not dirdata.exists():
            dirdata.mkdir()

        red = inputs.idat_file.output.red_channel.path
        green = inputs.idat_file.output.green_channel.path
        # Decompress the input IDAT files to the destination folder. This
        # fixes an edge case where calling the sesame.R script using
        # Plumbum was failing for some compressed IDAT inputs due to the
        # file encoding issues
        for idat in [red, green]:
            with gzip.open(idat, "rb") as in_file:
                with open(
                    dirdata / Path(idat).name.rsplit(".", 1)[0], "wb"
                ) as out_file:
                    shutil.copyfileobj(in_file, out_file)

        platform = inputs.idat_file.output.platform
        manifest = f"{platform}.hg38.manifest"

        sesame_args = [
            f"--platform={platform}",
            f"--manifest={manifest}",
        ]
        rc, _, _ = Cmd["sesame.R"][sesame_args] & TEE(retcode=None)
        # Returns QC_data.txt and beta_values_annotated.txt.gz

        if rc:
            self.error(
                "An error was encountered during the running of SeSAMe pipeline."
            )

        outputs.qc_data = "QC_data.txt"
        outputs.methylation_data = "beta_values_annotated.txt.gz"
        outputs.species = inputs.idat_file.output.species
        outputs.platform = platform


text:
@interface MMViewController ()
- (void)setupImageForInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end

@implementation MMViewController
@synthesize imageView = _imageView;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

//    NSManagedObjectContext *context = [[MMDataManager sharedDataManager] managedObjectContext];
//
//    [DBShot shotsFromPlayersFollowingUsername:@"bjango" context:context resultBlock:^(NSArray *shots) {
//    } failureBlock:^(NSError *error) {
//    }];
//
//    [TWTweet tweetsForSearchString:@"mmdribbble" maxIdString:@"176862714361163776" context:context resultBlock:^(NSArray *tweets) {
//        [tweets
//         enumerateObjectsUsingBlock:^(TWTweet * tweet, NSUInteger idx, BOOL *stop) {
//             NSLog(@"%@",tweet.tweet);
//         }];
//    } failureBlock:^(NSError *error) {
//    }];
}

- (void)viewDidUnload
{
    [self setImageView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupImageForInterfaceOrientation:self.interfaceOrientation];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self setupImageForInterfaceOrientation:toInterfaceOrientation];
}

- (void)setupImageForInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
        [_imageView setImage:[UIImage imageNamed:@"iPad-landscape.png"]];
    }
    else {
        [_imageView setImage:[UIImage imageNamed:@"iPad-portrait.png"]];
    }
}

@end


text:
'''
  Author Alumet 2015
  https://github.com/Alumet/Codingame
'''

# w: number of columns.
# h: number of rows.
w, h = [int(i) for i in input().split()]

line=[]
for i in range(h):
    line.append(input().split(' '))  # represents a line in the grid and contains W integers. Each integer represents one room of a given type.
ex = int(input())  # the coordinate along the X axis of the exit (not useful for this first mission, but must be read).

left_type=["10"]
right_type=["11"]
down_type=["1","3","7","8","9","12","13"]
horizontal_type=["2","6"]
special_type=["4","5"]

# game loop
while 1:
    xi, yi, pos = input().split()
    xi = int(xi)
    yi = int(yi)

    # One line containing the X Y coordinates of the room in which you believe Indy will be on the next turn.ft["10"]
    tile=line[yi][xi]

    if line[yi][xi] in left_type:
        xi-=1
        direction="left"
    elif line[yi][xi] in right_type:
        xi+=1
        direction="right"
    elif line[yi][xi] in down_type:
        yi+=1
    elif line[yi][xi] in horizontal_type:
        if direction=="left":
            xi-=1
        if direction=="right":
            xi+=1
    elif line[yi][xi]==special_type[0]:
        if old_tile in down_type or direction=="down":
            xi-=1
            direction="left"
        else:
            yi+=1
            dierction="down"
    elif line[yi][xi]==special_type[1]:
        if old_tile in down_type or direction=="down":
            xi+=1
            direction="right"
        else:
            yi+=1
            direction="down"

    old_tile=tile
    print(xi,yi)


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/disk_cache/simple/simple_version_upgrade.h"

#include <cstring>

#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/memory_mapped_file.h"
#include "base/logging.h"
#include "base/pickle.h"
#include "net/disk_cache/simple/simple_backend_version.h"
#include "net/disk_cache/simple/simple_entry_format_history.h"
#include "third_party/zlib/zlib.h"

namespace {

// It is not possible to upgrade cache structures on disk that are of version
// below this, the entire cache should be dropped for them.
const uint32_t kMinVersionAbleToUpgrade = 5;

const char kFakeIndexFileName[] = "index";
const char kIndexFileName[] = "the-real-index";

void LogMessageFailedUpgradeFromVersion(int version) {
  LOG(ERROR) << "Failed to upgrade Simple Cache from version: " << version;
}

bool WriteFakeIndexFile(const base::FilePath& file_name) {
  base::File file(file_name, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
  if (!file.IsValid())
    return false;

  disk_cache::FakeIndexData file_contents;
  file_contents.initial_magic_number =
      disk_cache::simplecache_v5::kSimpleInitialMagicNumber;
  file_contents.version = disk_cache::kSimpleVersion;
  file_contents.zero = 0;
  file_contents.zero2 = 0;

  int bytes_written = file.Write(0, reinterpret_cast<char*>(&file_contents),
                                 sizeof(file_contents));
  if (bytes_written != sizeof(file_contents)) {
    LOG(ERROR) << "Failed to write fake index file: "
               << file_name.LossyDisplayName().c_str();
    return false;
  }
  return true;
}

}  // namespace

namespace disk_cache {

FakeIndexData::FakeIndexData() {
  // Make hashing repeatable: leave no padding bytes untouched.
  std::memset(this, 0, sizeof(*this));
}

// Migrates the cache directory from version 4 to version 5.
// Returns true iff it succeeds.
//
// The V5 and V6 caches differ in the name of the index file (it moved to a
// subdirectory) and in the file format (directory last-modified time observed
// by the index writer has gotten appended to the pickled format).
//
// To keep complexity small this specific upgrade code *deletes* the old index
// file. The directory for the new index file has to be created lazily anyway,
// so it is not done in the upgrader.
//
// Below is the detailed description of index file format differences. It is for
// reference purposes. This documentation would be useful to move closer to the
// next index upgrader when the latter gets introduced.
//
// Path:
//   V5: $cachedir/the-real-index
//   V6: $cachedir/index-dir/the-real-index
//
// Pickled file format:
//   Both formats extend Pickle::Header by 32bit value of the CRC-32 of the
//   pickled data.
//   <v5-index> ::= <v5-index-metadata> <entry-info>*
//   <v5-index-metadata> ::= UInt64(kSimpleIndexMagicNumber)
//                           UInt32(4)
//                           UInt64(<number-of-entries>)
//                           UInt64(<cache-size-in-bytes>)
//   <entry-info> ::= UInt64(<hash-of-the-key>)
//                    Int64(<entry-last-used-time>)
//                    UInt64(<entry-size-in-bytes>)
//   <v6-index> ::= <v6-index-metadata>
//                  <entry-info>*
//                  Int64(<cache-dir-mtime>)
//   <v6-index-metadata> ::= UInt64(kSimpleIndexMagicNumber)
//                           UInt32(5)
//                           UInt64(<number-of-entries>)
//                           UInt64(<cache-size-in-bytes>)
//   Where:
//     <entry-size-in-bytes> is equal the sum of all file sizes of the entry.
//     <cache-dir-mtime> is the last modification time with nanosecond precision
//       of the directory, where all files for entries are stored.
//     <hash-of-the-key> represent the first 64 bits of a SHA-1 of the key.
bool UpgradeIndexV5V6(const base::FilePath& cache_directory) {
  const base::FilePath old_index_file =
      cache_directory.AppendASCII(kIndexFileName);
  if (!base::DeleteFile(old_index_file, /* recursive = */ false))
    return false;
  return true;
}

// Some points about the Upgrade process are still not clear:
// 1. if the upgrade path requires dropping cache it would be faster to just
//    return an initialization error here and proceed with asynchronous cache
//    cleanup in CacheCreator. Should this hack be considered valid? Some smart
//    tests may fail.
// 2. Because Android process management allows for killing a process at any
//    time, the upgrade process may need to deal with a partially completed
//    previous upgrade. For example, while upgrading A -> A + 2 we are the
//    process gets killed and some parts are remaining at version A + 1. There
//    are currently no generic mechanisms to resolve this situation, co the
//    upgrade codes need to ensure they can continue after being stopped in the
//    middle. It also means that the "fake index" must be flushed in between the
//    upgrade steps. Atomicity of this is an interesting research topic. The
//    intermediate fake index flushing must be added as soon as we add more
//    upgrade steps.
SimpleCacheConsistencyResult UpgradeSimpleCacheOnDisk(
    const base::FilePath& path) {
  // There is a convention among disk cache backends: looking at the magic in
  // the file "index" it should be sufficient to determine if the cache belongs
  // to the currently running backend. The Simple Backend stores its index in
  // the file "the-real-index" (see simple_index_file.cc) and the file "index"
  // only signifies presence of the implementation's magic and version. There
  // are two reasons for that:
  // 1. Absence of the index is itself not a fatal error in the Simple Backend
  // 2. The Simple Backend has pickled file format for the index making it hacky
  //    to have the magic in the right place.
  const base::FilePath fake_index = path.AppendASCII(kFakeIndexFileName);
  base::File fake_index_file(fake_index,
                             base::File::FLAG_OPEN | base::File::FLAG_READ);

  if (!fake_index_file.IsValid()) {
    if (fake_index_file.error_details() == base::File::FILE_ERROR_NOT_FOUND) {
      return WriteFakeIndexFile(fake_index)
                 ? SimpleCacheConsistencyResult::kOK
                 : SimpleCacheConsistencyResult::kWriteFakeIndexFileFailed;
    }
    return SimpleCacheConsistencyResult::kBadFakeIndexFile;
  }

  FakeIndexData file_header;
  int bytes_read = fake_index_file.Read(0,
                                        reinterpret_cast<char*>(&file_header),
                                        sizeof(file_header));
  if (bytes_read != sizeof(file_header) ||
      file_header.initial_magic_number !=
          disk_cache::simplecache_v5::kSimpleInitialMagicNumber) {
    LOG(ERROR) << "File structure does not match the disk cache backend.";
    return SimpleCacheConsistencyResult::kBadInitialMagicNumber;
  }
  fake_index_file.Close();

  uint32_t version_from = file_header.version;
  if (version_from < kMinVersionAbleToUpgrade) {
    LOG(ERROR) << "Version " << version_from << " is too old.";
    return SimpleCacheConsistencyResult::kVersionTooOld;
  }

  if (version_from > kSimpleVersion) {
    LOG(ERROR) << "Version " << version_from << " is from the future.";
    return SimpleCacheConsistencyResult::kVersionFromTheFuture;
  }

  if (file_header.zero != 0 && file_header.zero2 != 0) {
    LOG(WARNING) << "Rebuilding cache due to experiment change";
    return SimpleCacheConsistencyResult::kBadZeroCheck;
  }

  bool new_fake_index_needed = (version_from != kSimpleVersion);

  // There should be one upgrade routine here for each incremental upgrade
  // starting at kMinVersionAbleToUpgrade.
  static_assert(kMinVersionAbleToUpgrade == 5, "upgrade routines don't match");
  DCHECK_LE(5U, version_from);
  if (version_from == 5) {
    // Upgrade only the index for V5 -> V6 move.
    if (!UpgradeIndexV5V6(path)) {
      LogMessageFailedUpgradeFromVersion(file_header.version);
      return SimpleCacheConsistencyResult::kUpgradeIndexV5V6Failed;
    }
    version_from++;
  }
  DCHECK_LE(6U, version_from);
  if (version_from == 6) {
    // No upgrade from V6 -> V7, because the entry format has not changed and
    // the V7 index reader is backwards compatible.
    version_from++;
  }

  if (version_from == 7) {
    // Likewise, V7 -> V8 is handled entirely by the index reader.
    version_from++;
  }

  DCHECK_EQ(kSimpleVersion, version_from);

  if (!new_fake_index_needed)
    return SimpleCacheConsistencyResult::kOK;

  const base::FilePath temp_fake_index = path.AppendASCII("upgrade-index");
  if (!WriteFakeIndexFile(temp_fake_index)) {
    base::DeleteFile(temp_fake_index, /* recursive = */ false);
    LOG(ERROR) << "Failed to write a new fake index.";
    LogMessageFailedUpgradeFromVersion(file_header.version);
    return SimpleCacheConsistencyResult::kWriteFakeIndexFileFailed;
  }
#if defined(STARBOARD)
  NOTIMPLEMENTED() << "Starboard does not support file replacement.";
  return SimpleCacheConsistencyResult::kReplaceFileFailed;
#else
  if (!base::ReplaceFile(temp_fake_index, fake_index, NULL)) {
    LOG(ERROR) << "Failed to replace the fake index.";
    LogMessageFailedUpgradeFromVersion(file_header.version);
    return SimpleCacheConsistencyResult::kReplaceFileFailed;
  }
  return SimpleCacheConsistencyResult::kOK;
#endif
}

}  // namespace disk_cache


text:
/*
 * code copy from libc 2.7.
 */
#ifndef PTHREAD_DEFS_H
#define PTHREAD_DEFS_H

typedef struct list_head
{
  struct list_head *next;
  struct list_head *prev;
} pt_list_t;

/* Get typed element from list at a given position.  */
#define pt_list_entry(ptr, type, member) \
  ((type *) ((char *) (ptr) - (unsigned long) (&((type *) 0)->member)))

/* Iterate forward over the elements of the list.  */
#define pt_list_for_each(pos, head) \
  for (pos = (head)->next; pos != (head); pos = pos->next)

/* Iterate forward over the elements of the list.  */
#define pt_list_for_each_prev(pos, head) \
  for (pos = (head)->prev; pos != (head); pos = pos->prev)

/* Iterate backwards over the elements list.  The list elements can be
   removed from the list while doing this.  */
#define pt_list_for_each_prev_safe(pos, p, head) \
  for (pos = (head)->prev, p = pos->prev; \
       pos != (head); \
       pos = p, p = pos->prev)

#endif


text:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\EntryForm;

class ServerController extends Controller
{

    public function actionIndex()
    {
        return $this->render('index');
    }

}


text:
package com.markfeeney.circlet.middleware

import java.util.Locale

import com.markfeeney.circlet.middleware.Cookies.Encoder
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, DateTimeZone, Duration}

import scala.collection.mutable.ListBuffer
import scala.language.implicitConversions

/**
 * Represents a Cookie value to be used in the Set-Cookie response header.
 * https://tools.ietf.org/html/rfc6265
 *
 * @param value Value of the cookie
 * @param expires Date at which cookie expires
 * @param maxAge Interval of time (relative to now) after which the cookie expires
 * @param domain Domain on which cookie is valid
 * @param path Path under which the cookies is valid
 * @param secure Tell UA to only send cookie over secure channel
 * @param httpOnly Tell UA to prevent scripts from seeing cookie
 */
case class Cookie(
    value: String,
    expires: Option[DateTime] = None,  // expires must be sane-cookie-date; https://tools.ietf.org/html/rfc6265#section-4.1.1
    maxAge: Option[Duration] = None,
    domain: Option[String] = None,
    path: Option[String] = None,
    secure: Boolean = false,
    httpOnly: Boolean = false) {
}

object Cookie {
  implicit def str2Cookie(s: String): Cookie = Cookie(value = s)

  private val rfc822Formatter = DateTimeFormat
    .forPattern("EEE, dd MMM yyyy HH:mm:ss Z")
    .withZone(DateTimeZone.UTC)
    .withLocale(Locale.US)

  /**
   * Format `cookie` with given `name` for use in Set-Cookie header.
   */
  def toHeaderValue(name: String, cookie: Cookie, valueEncoder: Encoder): Option[String] = {
    if (name.trim.isEmpty) {
      None
    } else {
      val parts = new ListBuffer[String]
      parts.append(s"$name=${valueEncoder(cookie.value).getOrElse("")}")
      cookie.expires.foreach { v => parts.append(s"Expires=${rfc822Formatter.print(v)}") }
      cookie.maxAge.foreach { v => parts.append(s"Max-Age=${v.getStandardSeconds}") }
      cookie.domain.foreach { v => parts.append(s"Domain=$v") }
      cookie.path.foreach { v => parts.append(s"Path=$v") }
      if (cookie.secure) { parts.append("Secure") }
      if (cookie.httpOnly) { parts.append("HttpOnly") }
      Some(parts.mkString("; "))
    }
  }
}


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

-->

<target	name="find-esmtp-src"
		depends="init">
	<condition	property="esmtp.dir" value="${with-libesmtp}">
		<available file="${with-libesmtp}" />
	</condition>
	<condition	property="esmtp.src.dir" value="${esmtp.dir}">
		<available file="${esmtp.dir}/${esmtp.sample.c}" />
	</condition>
	<condition	property="esmtp.src.dir" value="../libesmtp">
		<available file="../libesmtp/${esmtp.sample.c}" />
	</condition>
</target>

<target	name="find-esmtp-lib"
		depends="find-esmtp-src"
		if="has-libesmtp"
		unless="force-ant">
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.la">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.la" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.dylib">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.dylib" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.so">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.so" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.a">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.a" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/${esmtp.lib.name}.lib">
		<available file="${esmtp.dir}/${esmtp.lib.name}.lib" />
	</condition>
	<condition	property="esmtp.lib.file.dir"
				value="${esmtp.dir}">
		<isset property="esmtp.lib.file" />
	</condition>

	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.la">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.la" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.dylib">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.dylib" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.so">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.so" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.a">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.a" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/${esmtp.lib.name}.lib">
		<available file="${esmtp.dir}/.libs/${esmtp.lib.name}.lib" />
	</condition>
	<condition	property="esmtp.lib.file.dir" value="${esmtp.dir}/.libs">
		<isset property="esmtp.lib.file" />
	</condition>

	<!-- Start looking at candidates in /usr -->
	<condition	property="esmtp.lib.file"
				value="/usr/lib/lib${esmtp.lib.name}.la">
		<available file="/usr/lib/lib${esmtp.lib.name}.la" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="/usr/lib/lib${esmtp.lib.name}.dylib">
		<available file="/usr/lib/lib${esmtp.lib.name}.dylib" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="/usr/lib/lib${esmtp.lib.name}.so">
		<available file="/usr/lib/lib${esmtp.lib.name}.so" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="/usr/lib/lib${esmtp.lib.name}.a">
		<available file="/usr/lib/lib${esmtp.lib.name}.a" />
	</condition>
	<condition	property="esmtp.dir" value="/usr">
		<isset property="esmtp.lib.file" />
	</condition>
	<condition	property="esmtp.lib.file.dir" value="/usr/lib">
		<isset property="esmtp.lib.file" />
	</condition>

	<!-- Start looking at candidates in /usr/local -->
	<condition	property="esmtp.lib.file"
				value="/usr/local/lib/lib${esmtp.lib.name}.la">
		<available file="/usr/local/lib/lib${esmtp.lib.name}.la" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="/usr/local/lib/lib${esmtp.lib.name}.dylib">
		<available file="/usr/local/lib/lib${esmtp.lib.name}.dylib" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="/usr/local/lib/lib${esmtp.lib.name}.so">
		<available file="/usr/local/lib/lib${esmtp.lib.name}.so" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="/usr/local/lib/lib${esmtp.lib.name}.a">
		<available file="/usr/local/lib/lib${esmtp.lib.name}.a" />
	</condition>
	<condition	property="esmtp.dir" value="/usr/local">
		<isset property="esmtp.lib.file" />
	</condition>
	<condition	property="esmtp.lib.file.dir" value="/usr/local/lib">
		<isset property="esmtp.lib.file" />
	</condition>

	<property	name="relative-esmtp"
				location="../libesmtp"
	/>
	<condition	property="esmtp.dir" value="${relative-esmtp}">
		<available file="${relative-esmtp}" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.la">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.la" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.dylib">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.dylib" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.so">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.so" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/lib${esmtp.lib.name}.a">
		<available file="${esmtp.dir}/lib${esmtp.lib.name}.a" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/${esmtp.lib.name}.lib">
		<available file="${esmtp.dir}/${esmtp.lib.name}.lib" />
	</condition>
	<condition	property="esmtp.lib.file.dir" value="${esmtp.dir}">
		<isset property="esmtp.lib.file" />
	</condition>

	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.la">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.la" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.dylib">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.dylib" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.so">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.so" />
	</condition>
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/.libs/lib${esmtp.lib.name}.a">
		<available file="${esmtp.dir}/.libs/lib${esmtp.lib.name}.a" />
	</condition>
	<condition	property="esmtp.lib.file.dir" value="${esmtp.dir}/.libs">
		<isset property="esmtp.lib.file" />
	</condition>
	<fail unless="esmtp.dir">Unable to locate esmtp base directory.</fail>

	<!-- Static debug libraries in APR's VC6 projects typical location (ignored unless debug build) -->
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/LibD/${esmtp.lib.name}.lib">
		<and>
			<isset property="is-debug" />
			<available file="${esmtp.dir}/LibD/${esmtp.lib.name}.lib" />
		</and>
	</condition>
	<condition	property="esmtp.lib.file.dir"
				value="${esmtp.dir}/LibD">
		<isset property="esmtp.lib.file" />
	</condition>

	<!-- Shared debug libraries in APR's VC6 projects typical location (ignored unless debug build) -->
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/Debug/lib${esmtp.lib.name}.lib">
		<and>
			<isset property="is-debug" />
			<available file="${esmtp.dir}/Debug/lib${esmtp.lib.name}.lib" />
		</and>
	</condition>
	<condition	property="esmtp.lib.file.dir"
				value="${esmtp.dir}/Debug">
		<isset property="esmtp.lib.file" />
	</condition>

	<!-- Static release libraries in APR's VC6 projects typical location (ignored unless debug build) -->
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/LibR/${esmtp.lib.name}.lib">
		<available file="${esmtp.dir}/LibR/${esmtp.lib.name}.lib" />
	</condition>
	<condition	property="esmtp.lib.file.dir"
				value="${esmtp.dir}/LibR">
		<isset property="esmtp.lib.file" />
	</condition>

	<!-- Shared release libraries in APR's VC6 projects typical location -->
	<condition	property="esmtp.lib.file"
				value="${esmtp.dir}/Release/lib${esmtp.lib.name}.lib">
		<available file="${esmtp.dir}/Release/lib${esmtp.lib.name}.lib" />
	</condition>
	<condition	property="esmtp.lib.file.dir"
				value="${esmtp.dir}/Release">
		<isset property="esmtp.lib.file" />
	</condition>

	<condition	property="esmtp.lib.dir"
				value="${esmtp.lib.file.dir}">
		<and>
			<isset property="esmtp.lib.file.dir" />
			<not>
				<or>
					<!--  default search path -->
					<equals arg1="${esmtp.lib.file.dir}" arg2="/usr" />
				</or>
			</not>
		</and>
	</condition>

	<condition	property="esmtp.lib.suffix"
				value="d">
		<or>
			<contains	string="${esmtp.lib.file}"
						substring="/lib${esmtp.lib.name}d."
			/>
			<contains	string="${esmtp.lib.file}"
						substring="/${esmtp.lib.name}d."
			/>
		</or>
	</condition>
	<condition	property="esmtp.lib.suffix"
				value="D">
		<or>
			<contains	string="${esmtp.lib.file}"
						substring="/lib${esmtp.lib.name}D."
			/>
			<contains	string="${esmtp.lib.file}"
						substring="/${esmtp.lib.name}D."
			/>
		</or>
	</condition>
	<condition	property="esmtp.lib.suffix"
				value="">
		<isset property="esmtp.lib.file" />
	</condition>

	<condition	property="esmtp.lib.prefix"
				value="lib">
		<or>
			<contains	string="[${esmtp.lib.file}]"
						substring="/lib${esmtp.lib.name}.lib]"
			/>
		</or>
	</condition>
	<condition	property="esmtp.lib.prefix"
				value="">
		<isset property="esmtp.lib.file" />
	</condition>

	<condition	property="esmtp.lib.type"
				value="shared">
		<or>
			<contains	string="${esmtp.lib.file}]"
						substring=".dylib]"
						casesensitive="no"
			/>
			<contains	string="${esmtp.lib.file}]"
						substring=".so]"
						casesensitive="no"
			/>
			<contains	string="${esmtp.lib.file}]"
						substring=".la]"
						casesensitive="no"
			/>
			<and>
				<!--
					If we have just a .lib, guess based on file size. Import libs should be much
					smaller.
				 -->
				<contains	string="${esmtp.lib.file}]"
							substring=".lib]"
							casesensitive="no"
				/>
				<isfileselected file="${esmtp.lib.file}">
					<size value="250000" when="less" />
				</isfileselected>
			</and>
		</or>
	</condition>

	<condition	property="esmtp.lib.type"
				value="static">
		<isset property="esmtp.lib.file" />
	</condition>
</target>

<target	name="find-esmtp"
		depends="find-esmtp-lib">
	<!--
		Use character ref to prevent directory name from being changed on global search and
		replacements.
	 -->
	<condition	property="esmtp.include.dir"
				value="${esmtp.dir}/include">
		<available file="${esmtp.dir}/include/${esmtp.sample.h}" />
	</condition>
	<condition	property="esmtp.include.dir"
				value="${esmtp.dir}">
		<available file="${esmtp.dir}/${esmtp.sample.h}" />
	</condition>
	<condition	property="esmtp.include.dir"
				value="${esmtp.dir}/../usr/include">
		<available file="${esmtp.dir}/../usr/include/${esmtp.sample.h}" />
	</condition>
	<condition	property="esmtp.include.dir"
				value="${esmtp.src.dir}/include">
		<available file="${esmtp.src.dir}/include/${esmtp.sample.h}" />
	</condition>
	<condition	property="esmtp.include.dir"
				value="${esmtp.src.dir}">
		<available file="${esmtp.src.dir}/include/${esmtp.sample.h}" />
	</condition>

	<condition	property="esmtp.dir"
				value="${esmtp.src.dir}">
		<isset property="esmtp.src.dir" />
	</condition>

	<echo>esmtp-find:
esmtp.dir=${esmtp.dir}
esmtp.include.dir=${esmtp.include.dir}
esmtp.src.dir=${esmtp.src.dir}
esmtp.lib.file=${esmtp.lib.file}
esmtp.lib.file.dir=${esmtp.lib.file.dir}
esmtp.lib.dir=${esmtp.lib.dir}
esmtp.lib.prefix=${esmtp.lib.prefix}
esmtp.lib.suffix=${esmtp.lib.suffix}
esmtp.lib.type=${esmtp.lib.type}
	</echo>
</target>


text:
<resources>
    <string name="app_name">TrackingApp</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="openDrawer">Open Drawer</string>
    <string name="closeDrawer">Close Drawer</string>
    <string name="dashboard_tag">Home</string>
    <string name="settings_tag">Settings</string>
    <string name="logout_tag">Logout</string>

    <string name="facebook_id">101197600230923</string>
    <string name="parse_key">SHoDsvoE3dmdisIrW9AoYvItW1MtX9xePnv1e8AO</string>
    <string name="parse_secret">yKWIeNiIOQHcXTdkACkuKmOjqlbq7sXhgtIIFB2W</string>
    <string name="forgotPwd">FORGOT PASSWORD</string>
</resources>