text:
"""Modules encapsulate building stateful components."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import re

from tensorflow.python.framework import ops
from tensorflow.python.ops import variables
from tensorflow.python.training.tracking import tracking
from tensorflow.python.util import nest
from tensorflow.python.util import tf_decorator
from tensorflow.python.util.tf_export import tf_export

@tf_export("Module")
class Module(tracking.AutoTrackable):
  """Base neural network module class.

  A module is a named container for `tf.Variable`s, other `tf.Module`s and
  functions which apply to user input. For example a dense layer in a neural
  network might be implemented as a `tf.Module`:

  >>> class Dense(tf.Module):
  ...   def __init__(self, in_features, output_features, name=None):
  ...     super(Dense, self).__init__(name=name)
  ...     self.w = tf.Variable(
  ...         tf.random_normal([input_features, output_features]), name='w')
  ...     self.b = tf.Variable(tf.zeros([output_features]), name='b')
  ...
  ...   def __call__(self, x):
  ...     y = tf.matmul(x, self.w) + self.b
  ...     return tf.nn.relu(y)

  You can use the Dense layer as you would expect:

  >>> d = Dense(input_features=64, output_features=10)
  >>> d(tf.ones([100, 64]))
  <tf.Tensor: ...>

  By subclassing `tf.Module` instead of `object` any `tf.Variable` or
  `tf.Module` instances assigned to object properties can be collected using
  the `variables`, `trainable_variables` or `submodules` property:

  >>> d.variables
  (<tf.Variable 'b:0' ...>, <tf.Variable 'w:0' ...>)

  Subclasses of `tf.Module` can also take advantage of the `_flatten` method
  which can be used to implement tracking of any other types.

  All `tf.Module` classes have an associated `tf.name_scope` which can be used
  to group operations in TensorBoard and create hierarchies for variable names
  which can help with debugging. We suggest using the name scope when creating
  nested submodules/parameters or for forward methods whose graph you might want
  to inspect in TensorBoard. You can enter the name scope explicitly using
  `with self.name_scope:` or you can annotate methods (apart from `__init__`)
  with `@tf.Module.with_name_scope`.

  >>> class MLP(tf.Module):
  ...   def __init__(self, input_size, sizes, name=None):
  ...     super(MLP, self).__init__(name=name)
  ...     self.layers = []
  ...     with self.name_scope:
  ...       for size in sizes:
  ...         self.layers.append(Dense(input_size=input_size, output_size=size))
  ...         input_size = size
  ...
  ...   @tf.Module.with_name_scope
  ...   def __call__(self, x):
  ...     for layer in self.layers:
  ...       x = layer(x)
  ...     return x
  """

  def __init__(self, name=None):
    if name is None:
      name = camel_to_snake(type(self).__name__)
    else:
      if not valid_identifier(name):
        raise ValueError(
            "%r is not a valid module name. Module names must be valid Python "
            "identifiers (e.g. a valid class name)." % name)

    self._name = name
    with ops.name_scope(name) as scope_name:
      self._scope_name = scope_name

  @property
  def name(self):
    """Returns the name of this module as passed or determined in the ctor.

    NOTE: This is not the same as the `self.name_scope.name` which includes
    parent module names.
    """
    return self._name

  @property
  def name_scope(self):
    """Returns a `tf.name_scope` instance for this class."""
    # TODO(tomhennigan) Memoize once name scopes are re-entrant.
    return ops.name_scope(self._scope_name)

  @property
  def variables(self):
    """Sequence of variables owned by this module and it's submodules.

    Note: this method uses reflection to find variables on the current instance
    and submodules. For performance reasons you may wish to cache the result
    of calling this method if you don't expect the return value to change.

    Returns:
      A sequence of variables for the current module (sorted by attribute
      name) followed by variables from all submodules recursively (breadth
      first).
    """
    return tuple(self._flatten(predicate=_IS_VARIABLE))

  @property
  def trainable_variables(self):
    """Sequence of variables owned by this module and it's submodules.

    Note: this method uses reflection to find variables on the current instance
    and submodules. For performance reasons you may wish to cache the result
    of calling this method if you don't expect the return value to change.

    Returns:
      A sequence of variables for the current module (sorted by attribute
      name) followed by variables from all submodules recursively (breadth
      first).
    """
    return tuple(self._flatten(predicate=_IS_TRAINABLE_VARIABLE))

  @property
  def submodules(self):
    """Sequence of all sub-modules.

    Submodules are modules which are properties of this module, or found as
    properties of modules which are properties of this module (and so on).

    >>> a = tf.Module()
    >>> b = tf.Module()
    >>> c = tf.Module()
    >>> a.b = b
    >>> b.c = c
    >>> assert list(a.submodules) == [b, c]
    >>> assert list(b.submodules) == [c]
    >>> assert list(c.submodules) == []

    Returns:
      A sequence of all submodules.
    """
    return tuple(self._flatten(predicate=_IS_MODULE))

  def _flatten(self,
               recursive=True,
               predicate=None,
               attribute_traversal_key=None,
               with_path=False):
    """Flattened attribute values in sorted order by attribute name.

    Modules are flattened by first walking their attributes in name order.
    Each attribute value is then flattened to find leaf values. If flatten is
    to be applied `recursive`ly then if the leaf is a `Module` it will also be
    flattened to find leaves. Finally every leaf value is optionally tested
    against the given `predicate` and finally yielded.

    >>> class Foo(tf.Module):
    ...   def __init__(self):
    ...     super(Foo, self).__init__()
    ...     self.x = [tf.constant('a'), tf.constant('b')]
    ...     self.y = {'i': tf.constant('c'), 'j': tf.constant('d')}
    ...     self.z = tf.constant('e')
    ...
    ...   @property
    ...   def tensors(self):
    ...     return tuple(self._flatten(predicate=is_tensor, with_path=True))

    >>> foo = Foo()
    >>> foo.tensors
    ((('x', 0),   <tf.Tensor: ...'a'>),
     (('x', 1),   <tf.Tensor: ...'b'>),
     (('y', 'i'), <tf.Tensor: ...'c'>),
     (('y', 'j'), <tf.Tensor: ...'d'>),
     (('z',),     <tf.Tensor: ...'e'>))

    `attribute_traversal_key` controls the order object properties are visited.
    If not set objects are visited in ascending order by name.

    Args:
      recursive: Whether to recurse into child modules or not.
      predicate: (Optional) If set then only values matching predicate are
        yielded. A value of `None` (the default) means no items will be
        filtered.
      attribute_traversal_key: (Optional) Method to rekey object attributes
        before they are sorted. Contract is the same as `key` argument to
        builtin `sorted` and only applies to object properties.
      with_path: (Optional) Whether to include the path to the object as well
        as the object itself. If `with_path` is `True` then leaves will not be
        de-duplicated (e.g. if the same leaf instance is reachable via multiple
        modules then it will be yielded multiple times with different paths).

    Returns:
      Flat generator for leaves of the current module and optionally all
      submodules.
    """
    if predicate is None:
      predicate = lambda _: True

    return _flatten_module(
        self,
        recursive=recursive,
        predicate=predicate,
        attribute_traversal_key=attribute_traversal_key,
        with_path=with_path)

  @classmethod
  def with_name_scope(cls, method):
    """Decorator to automatically enter the module name scope.

    >>> class MyModule(tf.Module):
    ...   @tf.Module.with_name_scope
    ...   def __call__(self, x):
    ...     if not hasattr(self, 'w'):
    ...       self.w = tf.Variable(tf.random.normal([x.shape[1], 64]))
    ...     return tf.matmul(x, self.w)

    Using the above module would produce `tf.Variable`s and `tf.Tensor`s whose
    names included the module name:

    >>> mod = MyModule()
    >>> mod(tf.ones([8, 32]))
    <tf.Tensor: ...>
    >>> mod.w
    <tf.Variable ...'my_module/w:0'>

    Args:
      method: The method to wrap.

    Returns:
      The original method wrapped such that it enters the module's name scope.
    """
    def method_with_name_scope(self, *args, **kwargs):
      with self.name_scope:
        return method(self, *args, **kwargs)

    return tf_decorator.make_decorator(method, method_with_name_scope)

_IS_VARIABLE = lambda o: isinstance(o, variables.Variable)
_IS_TRAINABLE_VARIABLE = lambda o: (_IS_VARIABLE(o) and o.trainable)
_IS_MODULE = lambda o: isinstance(o, Module)
_CAMEL_TO_SNAKE_R = re.compile(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))")
_VALID_IDENTIFIER = re.compile(r"^[a-zA-Z_]([a-zA-Z0-9_])*$")

def valid_identifier(name):
  return bool(_VALID_IDENTIFIER.match(name))

def camel_to_snake(value):
  return _CAMEL_TO_SNAKE_R.sub(r"_\1", value).lower()

# AutoTrackable adds object attributes that users will not expect us to
# include when flattening (these reference dependencies reachable via other
# object attributes).
AUTO_CHECKPOINTABLE_ATTRS = ("_unconditional_checkpoint_dependencies",
                             "_unconditional_dependency_names")

def _flatten_module(module,
                    recursive,
                    predicate,
                    attribute_traversal_key,
                    with_path,
                    module_path=(),
                    seen=None):
  """Implementation of `flatten`."""
  if seen is None:
    seen = set([id(module)])

  module_dict = vars(module)
  submodules = []

  for key in sorted(module_dict, key=attribute_traversal_key):
    if key in AUTO_CHECKPOINTABLE_ATTRS:
      continue

    for leaf_path, leaf in nest.flatten_with_tuple_paths(module_dict[key]):
      leaf_path = (key,) + leaf_path

      # TODO(tomhennigan) Handle cycles for `with_path=True` (e.g. `a.a = a`).
      if not with_path:
        leaf_id = id(leaf)
        if leaf_id in seen:
          continue
        seen.add(leaf_id)

      if predicate(leaf):
        if with_path:
          yield module_path + leaf_path, leaf
        else:
          yield leaf

      if recursive and isinstance(leaf, Module):
        # Walk direct properties first then recurse.
        submodules.append((module_path + leaf_path, leaf))

  for submodule_path, submodule in submodules:
    subvalues = _flatten_module(
        submodule,
        recursive=recursive,
        predicate=predicate,
        attribute_traversal_key=attribute_traversal_key,
        with_path=with_path,
        module_path=submodule_path,
        seen=seen)

    for subvalue in subvalues:
      # Predicate is already tested for these values.
      yield subvalue


text:
import numpy as np
import pandas as pd
import cPickle as pickle
from functions import csv_parser
from itertools import combinations_with_replacement
from collections import OrderedDict,Counter

def load_pickle(infile):
	'''Read in pickled files'''
	with open(infile) as f:
		return pickle.load(f)

def all_by_all_dists(infile,node_distsD,nonePenalty=None):
	'''Read a csv file of node age calls and return a generator of OrderedDicts
	that give the distances between databases for each gene. These will be tallied
	by sum_dists.'''
	parsed = csv_parser(infile)
	for prot, dbAgeD in parsed:
		dbs = sorted(dbAgeD.keys())
		dbDists = Counter({db: Counter({}) for db in dbs})
		for db1, db2 in combinations_with_replacement(dbs,r=2): # corner matrix, off diagonal
			node1,node2 = dbAgeD[db1],dbAgeD[db2] # get inferred ages
			if node1 == 'None' or node2 == 'None': # If node == None make distance largest possible
				if nonePenalty == None:
					continue
				else:
					dbDists[db1][db2] = nonePenalty
					continue
			dbDists[db1][db2] = node_distsD[node1][node2] # get distance between nodes
		yield dbDists

def sum_dist(infile,nodeDistsFile,nonePenalty=None):
	'''Sum of patristic distances between database age calls'''
	dists = load_pickle(nodeDistsFile)
	is_first = True
	count = 0
	for distD in all_by_all_dists(infile,dists,nonePenalty):
		if is_first:
			D = distD
			dbCounts = {db:0 for db in distD.keys()}
			is_first = False
		else:
			D = D + distD # add Counter objects
		for db in distD:
			if distD[db] != Counter(): # skip dbs missing gene
				dbCounts[db] += 1
		count += 1
		if count % 100 == 0:
			print count
	return pd.DataFrame(D).fillna(np.nan), dbCounts # replace None with NaN

def avg_dist(infile,nodeDistsFile,nonePenalty=None):
	'''
	Return a pandas DataFrame holding average patristic distances between
	database age calls.

	Missing data is not penalized by default, but can be by setting nonePenalty
	to the number of branches (patristic distance) to penalize a database for
	missing data. When nonePenalty is None, the average for each pair of databases
	is calculated only on genes found in both databases.
	'''
	sumDistDF,counts = sum_dist(infile,nodeDistsFile)
	return pd.DataFrame(
		{col:sumDistDF[col].map(lambda x: x/float(counts[col]))
		for col in sumDistDF.columns})

redpajama_set_name: RedPajamaGithub


text:
#![allow(trivial_casts)]
#![allow(unused_unsafe)]
#![allow(dead_code)]
#![allow(unused_imports)]

use libc;
extern crate num;

#[cfg(windows)]
use super::win::winsock;

pub use libc::{
    AF_INET, AF_INET6, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW,
    IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, TCP_NODELAY,
    SOL_SOCKET, SO_KEEPALIVE, SO_ERROR,
    SO_REUSEADDR, SO_BROADCAST, SHUT_WR, IP_MULTICAST_LOOP,
    IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP,
    IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP,
    IP_MULTICAST_TTL, IP_TTL, IP_HDRINCL, SHUT_RD,
    IPPROTO_RAW,
};

use std::iter::{FromIterator, repeat, };
use std::io::{Error, ErrorKind, Result,};
use std::mem;
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs, SocketAddrV4};
use std::ops::Drop;
use std::vec::{Vec,};
use std::ptr;
use std::clone::Clone;

use libc::{
    c_void, size_t, in_addr, sockaddr, sockaddr_in, socklen_t,
    c_int, c_uchar,c_char, c_ushort,

    socket, setsockopt, bind, send, recv, recvfrom,
    close,
    listen, sendto, accept, connect, getsockname,
    shutdown,
};

#[cfg(windows)]
type SOCKET = libc::SOCKET;
#[cfg(not(windows))]
type SOCKET = c_int;

#[cfg(windows)]
type BuffLen = c_int;
#[cfg(not(windows))]
type BuffLen = size_t;

macro_rules! _try {
    ( $fun:ident, $( $x:expr ),* ) => {{
        let value = unsafe { $fun($($x,)*) };
        if value == -1 {
            return Err(Error::last_os_error());
        }
        value
    }};
}

#[inline]
pub fn htons(hostshort: u16) -> u16 {
    hostshort.to_be()
}

#[inline]
pub fn ntohs(netshort: u16) -> u16 {
    u16::from_be(netshort)
}

#[inline]
pub fn htonl(hostlong: u32) -> u32 {
    hostlong.to_be()
}

#[inline]
pub fn ntohl(netlong: u32) -> u32 {
    u32::from_be(netlong)
}

#[derive(Debug, Clone)]
pub struct Socket {
    fd: i32,
}

fn tosocketaddrs_to_socketaddr<T: ToSocketAddrs + ?Sized>(address: &T) -> Result<SocketAddr> {
    let addresses: Vec<SocketAddr> = FromIterator::from_iter(try!(address.to_socket_addrs()));

    match addresses.len() {
        1 => {
            Ok(addresses[0])
        },
        // TODO is this really possible?
        n => Err(Error::new(
            ErrorKind::InvalidInput,
            &format!(
                "Incorrect number of IP addresses passed, \
                1 address expected, got {}", n)[..],
        ))
    }
}

fn tosocketaddrs_to_sockaddr<T: ToSocketAddrs + ?Sized>(address: &T) -> Result<sockaddr> {
    Ok(socketaddr_to_sockaddr(&try!(tosocketaddrs_to_socketaddr(address))))
}

impl Socket {
    #[cfg(windows)]
    pub fn new(socket_family: i32, socket_type: i32, _protocol: i32) -> Result<Socket> {
        winsock::init();
        let socket = try!(unsafe {
            match winsock::WSASocketW(socket_family, socket_type, 0, ptr::null_mut(), 0,
                                winsock::WSA_FLAG_OVERLAPPED) {
                libc::INVALID_SOCKET => Err(Error::last_os_error()),
                n => Ok(Socket { fd : n as i32 }),
            }
        });
        Ok(socket)
    }

    #[cfg(not(windows))]
    pub fn new(socket_family: i32, socket_type: i32, protocol: i32) -> Result<Socket> {
        let fd = _try!(socket, socket_family, socket_type, protocol);
        Ok(Socket { fd: fd as i32 })
    }

    pub fn new_by_fd(fd : i32) -> Socket {
        Socket { fd : fd }
    }

    pub fn fileno(&self) -> i32 {
        self.fd
    }

    pub fn setsockopt<T>(&self, level: i32, name: i32, value: T) -> Result<()> {
        unsafe {
            let value = &value as *const T as *const c_void;
            _try!(
                setsockopt,
                self.fd as SOCKET, level, name, value, mem::size_of::<T>() as socklen_t);
        }
        Ok(())
    }

    pub fn bind<T: ToSocketAddrs + ?Sized>(&self, address: &T) -> Result<()> {
        let sa = try!(tosocketaddrs_to_sockaddr(address));
        _try!(bind, self.fd as SOCKET, &sa, num::cast(mem::size_of::<sockaddr>()).unwrap());
        Ok(())
    }

    pub fn getsockname(&self) -> Result<SocketAddr> {
        let mut sa: sockaddr = unsafe { mem::zeroed() };
        let mut len: socklen_t = mem::size_of::<sockaddr>() as socklen_t;
        _try!(getsockname, self.fd as SOCKET,
              &mut sa as *mut sockaddr, &mut len as *mut socklen_t);
        assert_eq!(len, mem::size_of::<sockaddr>() as socklen_t);
        Ok(sockaddr_to_socketaddr(&sa))
    }

    pub fn sendto<T: ToSocketAddrs + ?Sized>(&self, buffer: &[u8], flags: i32, address: &T)
            -> Result<usize> {
        let sa = try!(tosocketaddrs_to_sockaddr(address));
        let sent = _try!(
            sendto, self.fd as SOCKET, buffer.as_ptr() as *const c_void,
            buffer.len() as BuffLen, flags, &sa as *const sockaddr,
            num::cast(mem::size_of::<sockaddr>()).unwrap());
        Ok(sent as usize)
    }

    pub fn send(&self, buffer: &[u8], flags: i32)
            -> Result<usize> {
        let sent = _try!(
            send, self.fd as SOCKET, buffer.as_ptr() as *const c_void, buffer.len() as BuffLen, flags);
        Ok(sent as usize)
    }

    /// Receives data from a remote socket and returns it with the address of the socket.
    pub fn recvfrom(&self, bytes: usize, flags: i32) -> Result<(SocketAddr, Box<[u8]>)> {
        let mut a = Vec::with_capacity(bytes);

        // This is needed to get some actual elements in the vector, not just a capacity
        a.extend(repeat(0u8).take(bytes));

        let (socket_addr, received) = try!(self.recvfrom_into(&mut a[..], flags));

        a.truncate(received);
        Ok((socket_addr, a.into_boxed_slice()))
    }

    pub fn recvfrom_into(&self, buffer: &mut [u8], flags: i32) -> Result<(SocketAddr, usize)> {
        let mut sa: sockaddr = unsafe { mem::zeroed() };
        let mut sa_len: socklen_t = mem::size_of::<sockaddr>() as socklen_t;
        let received = _try!(
            recvfrom, self.fd as SOCKET, buffer.as_ptr() as *mut c_void, buffer.len() as BuffLen, flags,
            &mut sa as *mut sockaddr, &mut sa_len as *mut socklen_t);
        assert_eq!(sa_len, mem::size_of::<sockaddr>() as socklen_t);
        Ok((sockaddr_to_socketaddr(&sa), received as usize))
    }

    /// Returns up to `bytes` bytes received from the remote socket.
    pub fn recv(&self, bytes: usize, flags: i32) -> Result<Box<[u8]>> {
        let mut a = Vec::with_capacity(bytes);

        // This is needed to get some actual elements in the vector, not just a capacity
        a.extend(repeat(0u8).take(bytes));

        let received = try!(self.recv_into(&mut a[..], flags));

        a.truncate(received);
        Ok(a.into_boxed_slice())
    }

    /// Similar to `recv` but receives to predefined buffer and returns the number
    /// of bytes read.
    pub fn recv_into(&self, buffer: &mut [u8], flags: i32) -> Result<usize> {
        let received = _try!(recv, self.fd as SOCKET, buffer.as_ptr() as *mut c_void, buffer.len() as BuffLen, flags);
        Ok(received as usize)
    }

    pub fn connect<T: ToSocketAddrs + ?Sized>(&self, toaddress: &T) -> Result<()> {
        let address = try!(tosocketaddrs_to_sockaddr(toaddress));
        _try!(connect, self.fd as SOCKET, &address as *const sockaddr, num::cast(mem::size_of::<sockaddr>()).unwrap());
        Ok(())
    }

    pub fn listen(&self, backlog: i32) -> Result<()> {
        _try!(listen, self.fd as SOCKET, backlog);
        Ok(())
    }

    pub fn accept(&self) -> Result<(Socket, SocketAddr)> {
        let mut sa: sockaddr = unsafe { mem::zeroed() };
        let mut sa_len: socklen_t = mem::size_of::<sockaddr>() as socklen_t;

        let fd = _try!(
            accept, self.fd as SOCKET, &mut sa as *mut sockaddr, &mut sa_len as *mut socklen_t);
        assert_eq!(sa_len, mem::size_of::<sockaddr>() as socklen_t);
        Ok((Socket { fd: fd as i32 }, sockaddr_to_socketaddr(&sa)))
    }

    #[cfg(not(windows))]
    pub fn close(&self) -> Result<()> {
        _try!(close, self.fd as SOCKET);
        Ok(())
    }

    #[cfg(windows)]
    pub fn close(&self) -> Result<()> {
        use libc::closesocket;
        let _ = _try!(closesocket, self.fd as SOCKET);
        Ok(())
    }

    #[cfg(not(windows))]
    pub fn set_non_blocking(&self) -> Result<()> {
        use libc::fcntl;
        let mut cur_flag = _try!(fcntl, self.fd as SOCKET, libc::F_GETFL);
        cur_flag |= libc::O_NONBLOCK;
        _try!(fcntl, self.fd as SOCKET, libc::F_SETFL, cur_flag);
        Ok(())
    }

    #[cfg(not(windows))]
    pub fn set_blocking(&self) -> Result<()> {
        use libc::fcntl;
        let mut cur_flag = _try!(fcntl, self.fd as SOCKET, libc::F_GETFL);
        cur_flag &= !libc::O_NONBLOCK;
        _try!(fcntl, self.fd as SOCKET, libc::F_SETFL, cur_flag);
        Ok(())

    }

    #[cfg(windows)]
    pub fn set_non_blocking(&self) -> Result<()> {
        use libc::ioctlsocket;
        let mut set = 1 as libc::c_ulong;
        let _ = _try!(ioctlsocket, self.fd as SOCKET, libc::FIONBIO, &mut set);
        Ok(())
    }

    #[cfg(windows)]
    pub fn set_blocking(&self) -> Result<()> {
        use libc::ioctlsocket;
        let mut set = 0 as libc::c_ulong;
        let _ = _try!(ioctlsocket, self.fd as SOCKET, libc::FIONBIO, &mut set);
        Ok(())
    }

    pub fn shutdown(&self, how: i32) -> Result<()> {
        _try!(shutdown, self.fd as SOCKET, how as c_int);
        Ok(())
    }
}

impl Drop for Socket {
    fn drop(&mut self) {
        // let _ = self.close();
    }
}

fn socketaddr_to_sockaddr(addr: &SocketAddr) -> sockaddr {
    unsafe {
        match *addr {
            SocketAddr::V4(v4) => {
                let mut sa: sockaddr_in = mem::zeroed();
                sa.sin_family = num::cast(AF_INET).unwrap();
                sa.sin_port = htons(v4.port());
                sa.sin_addr = *(&v4.ip().octets() as *const u8 as *const in_addr);
                *(&sa as *const sockaddr_in as *const sockaddr)
            },
            SocketAddr::V6(_) => {
                panic!("Not supported");
                /*
                let mut sa: sockaddr_in6 = mem::zeroed();
                sa.sin6_family = AF_INET6 as u16;
                sa.sin6_port = htons(v6.port());
                (&sa as *const sockaddr_in6 as *const sockaddr)
                */
            },
        }
    }
}

fn sockaddr_to_socketaddr(sa: &sockaddr) -> SocketAddr {
    match sa.sa_family as i32 {
        AF_INET => {
            let sin: &sockaddr_in = unsafe { mem::transmute(sa) };
            let ip_parts: [u8; 4] = unsafe { mem::transmute(sin.sin_addr) };
            SocketAddr::V4(
                SocketAddrV4::new(Ipv4Addr::new(
                    ip_parts[0],
                    ip_parts[1],
                    ip_parts[2],
                    ip_parts[3],
                ),
                ntohs(sin.sin_port))
            )
        },
        AF_INET6 => {
            panic!("IPv6 not supported yet")
        },
        _ => {
            unreachable!("Should not happen")
        }
    }
}


text:
<?php

namespace phpDocumentor\Transformer\Template;

use JMS\Serializer\Serializer;
use Mockery as m;
use org\bovigo\vfs\vfsStream;
use phpDocumentor\Transformer\Template;

class FactoryTest extends \PHPUnit_Framework_TestCase
{
    /** @var m\MockInterface|PathResolver */
    private $pathResolverMock;

    /** @var m\MockInterface|Serializer */
    private $serializerMock;

    /** @var Factory */
    private $fixture;

    /**
     * Sets up the fixture with mocked dependencies.
     */
    public function setUp()
    {
        $this->pathResolverMock = m::mock('phpDocumentor\Transformer\Template\PathResolver');
        $this->serializerMock = m::mock('JMS\Serializer\Serializer');

        $this->fixture = new Factory($this->pathResolverMock, $this->serializerMock);
    }

    /**
     * @covers phpDocumentor\Transformer\Template\Factory::__construct
     */
    public function testIfDependenciesAreCorrectlyRegisteredOnInitialization()
    {
        $this->assertAttributeSame($this->pathResolverMock, 'pathResolver', $this->fixture);
        $this->assertAttributeSame($this->serializerMock, 'serializer', $this->fixture);
    }

    /**
     * @covers phpDocumentor\Transformer\Template\Factory::get
     * @covers phpDocumentor\Transformer\Template\Factory::fetchTemplateXmlFromPath
     * @covers phpDocumentor\Transformer\Template\Factory::createTemplateFromXml
     */
    public function testRetrieveInstantiatedTemplate()
    {
        // Arrange
        $templateName = 'clean';
        $template = new Template($templateName);
        vfsStream::setup('exampleDir')->addChild(vfsStream::newFile('template.xml')->setContent('xml'));
        $this->pathResolverMock->shouldReceive('resolve')->with($templateName)->andReturn(vfsStream::url('exampleDir'));
        $this->serializerMock
            ->shouldReceive('deserialize')
            ->with('xml', 'phpDocumentor\Transformer\Template', 'xml')
            ->andReturn($template);

        // Act
        $result = $this->fixture->get($templateName);

        // Assert
        $this->assertSame($template, $result);
    }

    /**
     * @covers phpDocumentor\Transformer\Template\Factory::getTemplatePath
     */
    public function testReturnTemplatePathFromResolver()
    {
        // Arrange
        $expected = 'test';
        $this->pathResolverMock->shouldReceive('getTemplatePath')->andReturn($expected);

        // Act
        $result = $this->fixture->getTemplatePath();

        // Assert
        $this->assertSame($expected, $result);
    }

    /**
     * @covers phpDocumentor\Transformer\Template\Factory::getAllNames
     */
    public function testRetrieveAllTemplateNames()
    {
        // Arrange
        $expected = array('template1', 'template2');
        $root = vfsStream::setup('exampleDir');
        $root->addChild(vfsStream::newDirectory($expected[0]));
        $root->addChild(vfsStream::newFile('aFile.txt'));
        $root->addChild(vfsStream::newDirectory($expected[1]));
        $this->pathResolverMock->shouldReceive('getTemplatePath')->andReturn(vfsStream::url('exampleDir'));

        // Act
        $result = $this->fixture->getAllNames();

        // Assert
        $this->assertSame($expected, $result);
    }
}


text:
Project Information

Please input the requested information regarding each project.

Project {{ project.number }}

      <form name="{{ 'project' + project.number + 'Form' }}" novalidate role="form">

          Name
          <input type="text" name="{{ project.number + 'Name' }}" ng-model="project['name']" />

            IP Preference

            <input type="radio" class="with-gap" name="{{ 'ip' + project.number }}" id="{{ project.number +  '_open' }}"  ng-model="project['ipPref']" value="OPEN" />
            Project does not care to retain IP rights

            <input type="radio" class="with-gap" name="{{ 'ip' + project.number }}" id="{{ project.number +   '_closed' }}" ng-model="project['ipPref']" value="CLOSED" />
            Project wishes to keep its IP rights

          <input type="checkbox" name="{{ 'paid' + project.number }}" id="{{ 'paid' + project.number }}" ng-model="project['paid']" />
          Check if this sponsor is paying and must be assigned a team

          Select skills required for this project.

            <input type="checkbox" name="{{ skill + project.number }}" id="{{ skill + project.number }}" ng-model="project['skills'][skill]" />
            {{ skill }}

      </form>

  Back
  <button type="submit" ng-click="updateProjects()" class="btn btn-default">Submit!</button>


text:
<?php

namespace Symfony\Component\Config\Definition\Dumpers;

use Symfony\Component\Config\Definition\BaseNode;

/**
 * Dumps a Symfony reference in PHP format.
 *
 * @author Maxime Fabre <ehtnam6@gmail.com>
 */
class PhpReferenceDumper extends AbstractReferenceDumper
{
    /**
     * @param BaseNode $node
     *
     * @return string
     */
    public function dumpNode(BaseNode $node)
    {
        return '<?php'.PHP_EOL.PHP_EOL.'return ['.parent::dumpNode($node).PHP_EOL.'];'.PHP_EOL;
    }

    /**
     * @param mixed $value
     *
     * @return string
     */
    protected function serializeValue($value)
    {
        $serialized = var_export($value, true);
        if ($serialized === 'NULL') {
            $serialized = strtolower($serialized);
        }

        return $serialized;
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { IconButton, ButtonIcon } from '../Button';
import { THEMES, getThemeClass } from '../../utils';

const ModalHeader = (props) => {
  const {
    id, onClose, theme, title, tagline
  } = props;
  const isEmpty = !tagline && !title;

  return (

      {onClose && (
        <IconButton
          className="slds-modal__close"
          flavor="inverse"
          onClick={onClose}
          tabIndex={0}
        >
          <ButtonIcon
            sprite="utility"
            icon="close"
            size="large"
          />
        </IconButton>
      )}
      {title && (

          {title}

      )}
      {tagline &&
{tagline}
}

  );
};

ModalHeader.defaultProps = {
  id: null,
  onClose: null,
  title: null,
  tagline: null,
  theme: null,
};

ModalHeader.propTypes = {
  id: PropTypes.string,
  onClose: PropTypes.func,
  theme: PropTypes.oneOf(THEMES),
  title: PropTypes.string,
  tagline: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
};

export default ModalHeader;


text:
from .base import DerivedType
from categorical import CategoricalComparator
from .categorical_type import CategoricalType
from dedupe import predicates

class ExistsType(CategoricalType) :
    type = "Exists"
    _predicate_functions = []

    def __init__(self, definition) :

        super(CategoricalType, self ).__init__(definition)

        self.cat_comparator = CategoricalComparator([0,1])

        self.higher_vars = []
        for higher_var in self.cat_comparator.dummy_names :
            dummy_var = DerivedType({'name' : higher_var,
                                     'type' : 'Dummy',
                                     'has missing' : self.has_missing})
            self.higher_vars.append(dummy_var)

    def comparator(self, field_1, field_2) :
        if field_1 and field_2 :
            return self.cat_comparator(1, 1)
        elif field_1 or field_2 :
            return self.cat_comparator(0, 1)
        else :
            return self.cat_comparator(0, 0)

    # This flag tells fieldDistances in dedupe.core to pass
    # missing values (None) into the comparator
    comparator.missing = True


text:
class Profile;

namespace apps {

class SavedFilesService;

// BrowserContextKeyedServiceFactory for SavedFilesService.
class SavedFilesServiceFactory : public BrowserContextKeyedServiceFactory {
 public:
  static SavedFilesService* GetForProfile(Profile* profile);

  static SavedFilesServiceFactory* GetInstance();

 private:
  SavedFilesServiceFactory();
  ~SavedFilesServiceFactory() override;
  friend struct base::DefaultSingletonTraits<SavedFilesServiceFactory>;

  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* profile) const override;
};

}  // namespace apps

#endif  // APPS_SAVED_FILES_SERVICE_FACTORY_H_


text:
@protocol CTransportDelegate;

@interface CTransport : CWireProtocol <CStreamConnectorDelegate> {
	CFReadStreamRef remoteReadStream;
	CFWriteStreamRef remoteWriteStream;

	id <CTransportDelegate> delegate; // Not retained.
	BOOL isOpen;

	CStreamConnector *streamConnector;
}

@property (readonly, nonatomic, assign) CFReadStreamRef remoteReadStream;
@property (readonly, nonatomic, assign) CFWriteStreamRef remoteWriteStream;
@property (readwrite, nonatomic, assign) id <CTransportDelegate> delegate; // Not retained.
@property (readonly, nonatomic, assign) BOOL isOpen;

- (id)initWithInputStream:(NSInputStream *)inInputStream outputStream:(NSOutputStream *)inOutputStream;

- (BOOL)open:(NSError **)outError;
- (void)close;

@end

#pragma mark -

@protocol CTransportDelegate <NSObject>

- (void)connectionWillOpen:(CTransport *)inConnection;
- (void)connectionDidOpen:(CTransport *)inConnection;

- (void)connectionWillClose:(CTransport *)inConnection;
- (void)connectionDidClose:(CTransport *)inConnection;

@end


text:
FROM golang:1.17-buster AS builder

RUN apt-get update && \
  apt-get install -y git gcc bash ssl-cert ca-certificates

WORKDIR /go/src/github.com/ory/hydra

ADD go.mod go.mod
ADD go.sum go.sum

ENV GO111MODULE on
ENV CGO_ENABLED 1

RUN go mod download

ADD . .

RUN go build -tags sqlite -o /usr/bin/hydra

VOLUME /var/lib/sqlite

# Exposing the ory home directory
VOLUME /home/ory

# Declare the standard ports used by hydra (4433 for public service endpoint, 4434 for admin service endpoint)
EXPOSE 4444 4445

RUN mv test/conformance/ssl/ory-ca.* /etc/ssl/certs/
RUN mv test/conformance/ssl/ory-conformity.crt /etc/ssl/certs/
RUN mv test/conformance/ssl/ory-conformity.key /etc/ssl/private/
RUN update-ca-certificates

ENTRYPOINT ["hydra"]
CMD ["serve"]


text:
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Route | myprofile', function(hooks) {
  setupTest(hooks);

  test('it exists', function(assert) {
    let route = this.owner.lookup('route:myprofile');
    assert.ok(route);
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="soaf-core" default="dist" basedir=".">

      	<!-- ====================================================================== -->
      	<!-- Build environment properties                                           -->
     	<!-- ====================================================================== -->
	<property name="module.name" value="soaf-core" />

      	<property name="src.dir" location="src/main/java" />
      	<property name="resource.dir" location="src/main/resources" />
      	<property name="test.src.dir" location="src/test/java"/>
      	<property name="resource.test,dir" location="src/test/resources"/>
      	<property name="test.resource.dir" location="src/test/resources"/>

	<property name="build.dir" location="build" />
	<property name="dist.dir" location="${build.dir}/bin" />
	<property name="soaf.dist.dir" location="../dist" />

	<property name="classes.dir" location="${build.dir}/classes" />
     	<property name="test.dir" location="${build.dir}/test" />
	<property name="test.classes.dir" location="${test.dir}/classes" />
     	<property name="test.report.dir" location="${test.dir}/reports" />

	<property name="lib.dir" location="lib" />

      	<!-- ====================================================================== -->
      	<!-- Defining classpaths                                                    -->
      	<!-- ====================================================================== -->

      	<path id="compile.classpath">
	  	<fileset dir="${lib.dir}" includes="*.jar"/>
      	</path>

      	<path id="test.classpath">
	  	<path refid="compile.classpath" />
      	</path>

      	<!-- ====================================================================== -->
      	<!-- Cleaning up target                                                     -->
      	<!-- ====================================================================== -->

     	 <target name="clean" description="Clean the output directory">
		<echo>removing ${build.dir} directory</echo>
        	<delete dir="${build.dir}"/>
      	</target>

      	<!-- ====================================================================== -->
      	<!-- Compilation target                                                     -->
      	<!-- ====================================================================== -->

     	<target name="compile" depends="clean" description="Compile the code">
		<echo>compiling src</echo>
		<mkdir dir="${classes.dir}" />
       		<javac srcdir="${src.dir}"
			destdir="${classes.dir}"
			classpathref="compile.classpath"
               		nowarn="false"
               		debug="true"
               		optimize="false"
               		deprecation="true"
               		verbose="false"
               		fork="false"
               		includeantruntime="false">
        	</javac>
		<echo>Adding resources from: ${resource.dir} to: ${classes.dir}</echo>
        	<copy todir="${classes.dir}">
          		<fileset dir="${resource.dir}"/>
       		</copy>
    	</target>

     	<!-- ====================================================================== -->
     	<!-- compile unit tests                                                     -->
      	<!-- ====================================================================== -->
	<target name="compile-tests" depends="compile" description="compile unit tests"  >
	    	<echo>compiling test src</echo>
	    	<mkdir dir="${test.classes.dir}"/>
  	    	<javac destdir="${test.classes.dir}"
			classpathref="test.classpath"
			classpath="${classes.dir}"
              		nowarn="false"
               		debug="$true"
               		optimize="false"
               		deprecation="true"
               		verbose="false"
               		fork="false"
               		includeantruntime="false">
			<src path="${test.src.dir}" />
			<src path="../security-modules/classification-module/src/main/java" />
			<src path="../security-modules/sci-module/src/main/java" />
			<src path="../security-modules/sap-module/src/main/java" />

		 </javac>

	   	<echo>copy test resources to ${test.classes.dir}</echo>
	    	<copy todir="${test.classes.dir}">
            		<fileset dir="${test.resource.dir}"/>
       	    	</copy>

	</target>

      	<!-- ====================================================================== -->
     	 <!-- run unit tests                                                        -->
      	<!-- ====================================================================== -->

	<target name="unit-tests" depends="compile-tests" description="run unit tests">
		<mkdir dir="${test.report.dir}" />
	        <echo>running unit tests</echo>
		<junit printsummary="yes" haltonfailure="yes">
			<jvmarg value="-Dcatalina.home=${test.dir}/test-logs" />
      			<classpath refid="test.classpath"/>
      			<classpath path="${classes.dir}"/>
      			<classpath path="${test.classes.dir}"/>
 			<formatter type="plain" />
			<formatter type="xml" />
			<batchtest fork="yes" todir="${test.report.dir}">
				<fileset dir="${test.classes.dir}" >
					<include name="**/*Test*" />
				</fileset>
			</batchtest>
		</junit>
	</target>

      	<!-- ====================================================================== -->
      	<!-- create jar                                                		    -->
      	<!-- ====================================================================== -->

     	<target name="jar" depends="compile,unit-tests" description="create ${dist.dir}/${module.name}.jar">
		<echo>create "${dist.dir}/${module.name}.jar</echo>
		<mkdir dir="${dist.dir}" />
		<jar destfile="${dist.dir}/${module.name}.jar">
			<fileset dir="${classes.dir}" >
				<exclude name="**/*Test*" />
				<exclude name="**/ldif-files/**" />
				<exclude name="**/mongo-database-files/**" />
			</fileset>
		</jar>

	   	<echo>copy resources to "${dist.dir}</echo>
	    	<copy todir="${dist.dir}">
            		<fileset dir="${resource.dir}" />
       	    	</copy>

      	</target>

      	<!-- ====================================================================== -->
     	<!-- dist module                                                            -->
      	<!-- ====================================================================== -->
      	<target name="dist" depends="jar" description="Package module">
	   	<echo>copy files from "${dist.dir} to ${soaf.dist.dir}</echo>
		<mkdir dir="${soaf.dist.dir}" />
	    	<copy todir="${soaf.dist.dir}">
            		<fileset dir="${dist.dir}" />
      	    	</copy>
     	 </target>

     	<!-- ====================================================================== -->
      	<!-- Javadoc target                                                         -->
      	<!-- ====================================================================== -->

      	<target name="javadoc" description="Generates the Javadoc of the application">
        	<javadoc sourcepath="${src.dir}"
			classpathref="compile.classpath"
		         packagenames="*"
		         destdir="${build.dir}/javadocs"
		         access="protected"
		         old="false"
		         verbose="false"
		         version="true"
		         use="true"
		         author="true"
		         splitindex="false"
		         nodeprecated="false"
		         nodeprecatedlist="false"
		         notree="false"
		         noindex="false"
		         nohelp="false"
		         nonavbar="false"
		         serialwarn="false"
		         charset="ISO-8859-1"
		         linksource="false"
                 breakiterator="false"/>
     	 </target>

</project>


text:
REG_FIDDLE(Difference, 256, 256, false, 5) {
void draw(SkCanvas* canvas) {
    canvas->drawImage(image, 0, 0);
    canvas->drawImage(image, 128, 0);
    canvas->drawImage(image, 0, 128);
    canvas->drawImage(image, 128, 128);
    SkPaint paint;
    paint.setBlendMode(SkBlendMode::kDstATop);
    SkColor alphas[] = { SK_ColorBLACK, SK_ColorTRANSPARENT };
    SkPoint vert[] = { { 0, 0 }, { 0, 256 } };
    paint.setShader(SkGradientShader::MakeLinear(vert, alphas, nullptr, SK_ARRAY_COUNT(alphas),
            SkTileMode::kClamp));
    canvas->drawPaint(paint);
    canvas->clipRect( { 30, 30, 226, 226 } );
    canvas->drawColor(0x80bb9977, SkBlendMode::kDifference);
}
}  // END FIDDLE


text:
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using Unity.Appodeal.Xcode;
using Unity.Appodeal.Xcode.PBX;

using System;
using System.Diagnostics;
using System.IO;
using System.Collections;

#if UNITY_IPHONE
public class AppodealPostProcess : MonoBehaviour
{
	private static string suffix = ".framework";
	private static string absoluteProjPath;

	#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
	private static string AppodealFramework = "Plugins/iOS/Appodeal.framework";
	private static string AppodealBundle = "Plugins/iOS/Appodeal.bundle";
	#endif

	private static string[] frameworkList = new string[] {
		"Twitter", "AdSupport", "AudioToolbox",
		"AVFoundation", "CoreFoundation", "CFNetwork",
		"CoreGraphics", "CoreImage", "CoreMedia",
		"CoreLocation", "CoreTelephony", "GLKit",
		"JavaScriptCore", "EventKitUI", "EventKit",
		"MediaPlayer", "MessageUI", "QuartzCore",
		"MobileCoreServices", "Security", "StoreKit",
		"SystemConfiguration", "Twitter", "UIKit",
		"CoreBluetooth"
	};

	private static string[] weakFrameworkList = new string[] {
		"CoreMotion", "WebKit", "Social"
	};

	private static string[] platformLibs = new string[] {
		"libc++.dylib",
		"libz.dylib",
		"libsqlite3.dylib",
		"libxml2.2.dylib"
	};

	[PostProcessBuild(100)]
	public static void OnPostProcessBuild (BuildTarget target, string pathToBuildProject)
	{
		if (target.ToString () == "iOS" || target.ToString () == "iPhone") {
			PrepareProject (pathToBuildProject);
			UpdatePlist(pathToBuildProject);
		}
	}

	private static void PrepareProject(string buildPath) {
		UnityEngine.Debug.Log("preparing your xcode project for appodeal");
		string projPath = Path.Combine (buildPath, "Unity-iPhone.xcodeproj/project.pbxproj");
		absoluteProjPath = Path.GetFullPath(buildPath);
		PBXProject project = new PBXProject ();
		project.ReadFromString (File.ReadAllText(projPath));
		string target = project.TargetGuidByName ("Unity-iPhone");

		AddProjectFrameworks (frameworkList, project, target, false);
		AddProjectFrameworks (weakFrameworkList, project, target, true);
		AddProjectLibs (platformLibs, project, target);
		project.AddBuildProperty (target, "OTHER_LDFLAGS", "-ObjC");
		project.AddBuildProperty (target, "ENABLE_BITCODE", "NO");
		project.AddBuildProperty (target, "LIBRARY_SEARCH_PATHS", "$(SRCROOT)/Libraries");

		string apdFolder = "Adapters";
		string fullPath = Path.Combine (Application.dataPath, string.Format ("Appodeal/{0}", apdFolder));
		if (Directory.Exists(fullPath)) {
			foreach (string file in System.IO.Directory.GetFiles(fullPath)) {
				if(Path.GetExtension(file).Equals(".zip")) {
					ExtractZip (file, Path.Combine (absoluteProjPath, apdFolder));
					AddAdaptersDirectory (apdFolder, project, target);
				}
			}
		}

		#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
		project.AddBuildProperty (target, "FRAMEWORK_SEARCH_PATHS", "$(PROJECT_DIR)/Frameworks/Plugins/iOS");
		project.SetBuildProperty (target, "LIBRARY_SEARCH_PATHS", "$(SRCROOT)/Libraries");
		CopyAndReplaceDirectory ("Assets/" + AppodealFramework, Path.Combine(buildPath, "Frameworks/" + AppodealFramework));
		project.AddFileToBuild(target, project.AddFile("Frameworks/" + AppodealFramework, "Frameworks/" + AppodealFramework, PBXSourceTree.Source));
		CopyAndReplaceDirectory ("Assets/" + AppodealBundle, Path.Combine(buildPath, "Frameworks/" + AppodealBundle));
		project.AddFileToBuild(target,  project.AddFile("Frameworks/" + AppodealBundle,  "Frameworks/" + AppodealBundle, PBXSourceTree.Source));
		#endif

		File.WriteAllText (projPath, project.WriteToString());
	}

	protected static void AddProjectFrameworks(string[] frameworks, PBXProject project, string target, bool weak)
	{
		foreach (string framework in frameworks) {
			if (!project.HasFramework (framework)) {
				project.AddFrameworkToProject (target, framework + suffix, weak);
			}
		}
	}

	protected static void AddProjectLibs(string[] libs, PBXProject project, string target)
	{
		foreach (string lib in libs) {
			string libGUID = project.AddFile ("usr/lib/" + lib, "Libraries/" + lib, PBXSourceTree.Sdk);
			project.AddFileToBuild (target, libGUID);
		}
	}

	private static void UpdatePlist (string buildPath)
	{
		#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
		string plistPath = Path.Combine (buildPath, "Info.plist");
		PlistDocument plist = new PlistDocument ();
		plist.ReadFromString(File.ReadAllText (plistPath));
		PlistElementDict dict = plist.root.CreateDict ("NSAppTransportSecurity");
		dict.SetBoolean ("NSAllowsArbitraryLoads", true);
		File.WriteAllText(plistPath, plist.WriteToString());
		#endif
	}

	private static void CopyAndReplaceDirectory(string srcPath, string dstPath)
	{
		if (Directory.Exists(dstPath)) {
			Directory.Delete(dstPath);
		}
		if (File.Exists(dstPath)) {
			File.Delete(dstPath);
		}

		Directory.CreateDirectory(dstPath);

		foreach (var file in Directory.GetFiles(srcPath)) {
			if(!file.Contains(".meta")) {
				File.Copy(file, Path.Combine(dstPath, Path.GetFileName(file)));
			}
		}

		foreach (var dir in Directory.GetDirectories(srcPath)) {
			CopyAndReplaceDirectory(dir, Path.Combine(dstPath, Path.GetFileName(dir)));
		}
	}

	private static void ExtractZip(string filePath, string destFolder){
		using(Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(filePath)){
			foreach(Ionic.Zip.ZipEntry z in zip){
				z.Extract(destFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
			}
		}
	}

	private static void AddAdaptersDirectory(string path, PBXProject proj, string targetGuid)
	{
		if (path.EndsWith ("__MACOSX",StringComparison.CurrentCultureIgnoreCase))
			return;

		if (path.EndsWith (".framework", StringComparison.CurrentCultureIgnoreCase)) {
			proj.AddFileToBuild (targetGuid, proj.AddFile (path, path));
			string tmp = Utils.FixSlashesInPath(string.Format ("$(PROJECT_DIR)/{0}", path.Substring (0, path.LastIndexOf (Path.DirectorySeparatorChar))));
			proj.AddBuildProperty (targetGuid, "FRAMEWORK_SEARCH_PATHS", tmp);
			return;
		} else if(path.EndsWith (".bundle", StringComparison.CurrentCultureIgnoreCase)){
			proj.AddFileToBuild (targetGuid, proj.AddFile (path, path));
			return;
		}

		string fileName;
		bool libPathAdded = false;
		bool headPathAdded = false;

		string realDstPath = Path.Combine (absoluteProjPath, path);
		foreach (var filePath in Directory.GetFiles(realDstPath)) {
			fileName = Path.GetFileName (filePath);

			if (fileName.EndsWith (".DS_Store"))
				continue;

			proj.AddFileToBuild (targetGuid, proj.AddFile (Path.Combine (path, fileName), Path.Combine (path, fileName), PBXSourceTree.Source));
			if(!libPathAdded && fileName.EndsWith(".a")){
				proj.AddBuildProperty(targetGuid, "LIBRARY_SEARCH_PATHS", Utils.FixSlashesInPath(string.Format("$(PROJECT_DIR)/{0}", path)));
				libPathAdded = true;
			}

			if(!headPathAdded && fileName.EndsWith(".h")){
						proj.AddBuildProperty(targetGuid, "HEADER_SEARCH_PATHS", Utils.FixSlashesInPath(string.Format("$(PROJECT_DIR)/{0}", path)));
				headPathAdded = true;
			}
		}

		foreach (var subPath in Directory.GetDirectories(realDstPath)){
			AddAdaptersDirectory(Path.Combine(path,Path.GetFileName(subPath)), proj, targetGuid);
		}
	}

}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:Dialog"
    helpPath="en/cq/current/wcm/default_components.html#Slideshow"
    xtype="tabpanel">
    <items jcr:primaryType="cq:WidgetCollection">
        <slides
            jcr:primaryType="cq:Widget"
            ddGroups="[media]"
            fileReferencePrefix="./image$"
            title="Slides"
            xtype="slideshow"/>
        <advanced
            jcr:primaryType="cq:Widget"
            title="Advanced"
            xtype="panel">
            <items jcr:primaryType="cq:WidgetCollection">
                <size
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Size"
                    heightParameter="./slideshowHeight"
                    widthParameter="./slideshowWidth"
                    xtype="sizefield"/>
            </items>
        </advanced>
    </items>
</jcr:root>


text:
const main = require('./webpack.config');
const example = require('./webpack.example.config');

module.exports = [main, example];


text:
module Morpher
  class Evaluator
    class Transformer
      class Domain < self
        # Abstract namespace class for domain objects via instance variables
        class InstanceVariables < self
          include AbstractType

          # Evaluator for dumping domain objects via instance variables
          class Dump < self
            include Domain::Dump

            register :dump_instance_variables

            # Call evaluator
            #
            # @param [Object] input
            #
            # @return [Hash<Symbol, Object>]
            #
            # @api private
            #
            def call(input)
              dump do |attribute, attributes|
                attributes[attribute.name] =
                  input.instance_variable_get(attribute.ivar_name)
              end
            end

          end # Dump

          # Evaluator for loading domain objects via instance variables
          class Load < self
            include Domain::Load

            register :load_instance_variables

            # Call evaluator
            #
            # @param [Object] input
            #
            # @return [Object]
            #
            # @api private
            #
            def call(input)
              load do |attribute, object|
                object.instance_variable_set(
                  attribute.ivar_name,
                  input.fetch(attribute.name)
                )
              end
            end

          end # Load
        end # Domain
      end # Anima
    end # Transformer
  end # Evaluator
end # Morpher


text:
//
//  MCSAssetExporterManager.m
//  SJMediaCacheServer
//
//  Created by BD on 2021/3/10.
//

#import "MCSAssetExporterManager.h"
#import "MCSAssetCacheManager.h"
#import "MCSAssetManager.h"
#import "MCSPrefetcherManager.h"
#import "NSFileManager+MCS.h"
#import "MCSDatabase.h"
#import "MCSURL.h"
#import "MCSUtils.h"
#import "FILEAsset.h"
#import "HLSAsset.h"

static NSNotificationName const MCSAssetExporterProgressDidChangeNotification = @"MCSAssetExporterProgressDidChangeNotification";
static NSNotificationName const MCSAssetExporterStatusDidChangeNotification = @"MCSAssetExporterStatusDidChangeNotification";

static NSString *const MCSAssetExporterErrorUserInfoKey = @"MCSAssetExporterErrorUserInfoKey";

@interface MCSAssetExporter : NSObject<MCSSaveable, MCSAssetExporter>
- (instancetype)initWithURLString:(NSString *)URLStr name:(NSString *)name type:(MCSAssetType)type;
@property (nonatomic, strong, readonly) NSURL *URL;
@property (nonatomic) MCSAssetExportStatus status;
@property (nonatomic) float progress;
- (void)synchronize;
- (void)resume;
- (void)suspend;
- (void)cancel;
- (void)willBeRemoved;
@end

@interface MCSAssetExporter () {
    dispatch_semaphore_t _semaphore;
    id<MCSPrefetchTask> _task;
}
@property (nonatomic) NSInteger id;
@property (nonatomic, strong) NSString *name; // asset name
@property (nonatomic, strong) NSString *URLString;
@property (nonatomic) MCSAssetType type;
@end

@implementation MCSAssetExporter
@synthesize URL = _URL;
@synthesize status = _status;
@synthesize progress = _progress;
@synthesize progressDidChangeExecuteBlock = _progressDidChangeExecuteBlock;
@synthesize statusDidChangeExecuteBlock = _statusDidChangeExecuteBlock;

- (instancetype)initWithURLString:(NSString *)URLStr name:(NSString *)name type:(MCSAssetType)type {
    self = [self init];
    if ( self ) {
        _URLString = URLStr;
        _name = name;
        _type = type;
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if ( self ) {
        _semaphore = dispatch_semaphore_create(1);
        _status = MCSAssetExportStatusSuspended;
    }
    return self;
}

+ (NSString *)sql_primaryKey {
    return @"id";
}

+ (NSArray<NSString *> *)sql_autoincrementlist {
    return @[self.sql_primaryKey];
}

+ (NSArray<NSString *> *)sql_blacklist {
    return @[@"URL", @"progress"];
}

- (NSURL *)URL {
    __block NSURL *URL = nil;
    [self _lockInBlock:^{
        if ( _URL == nil )
            _URL = [NSURL URLWithString:_URLString];
        URL = _URL;
    }];
    return URL;
}

- (MCSAssetExportStatus)status {
    __block MCSAssetExportStatus status;
    [self _lockInBlock:^{
        status = _status;
    }];
    return status;
}

- (float)progress {
    __block float progress = 0;
    [self _lockInBlock:^{
        progress = _status == MCSAssetExportStatusFinished ? 1.0 : _progress;
    }];
    return progress;
}

- (void)synchronize {
    __kindof id<MCSAsset> asset = [MCSAssetManager.shared assetWithName:_name type:_type];
    switch ( _type ) {
        case MCSAssetTypeFILE:
            [self _synchronizeForFILEAsset:asset];
            break;
        case MCSAssetTypeHLS:
            [self _synchronizeForHLSAsset:asset];
            break;
    }
}

- (void)resume {
    __block BOOL isChanged = NO;
    [self _lockInBlock:^{
        switch ( _status ) {
            case MCSAssetExportStatusFinished:
            case MCSAssetExportStatusWaiting:
            case MCSAssetExportStatusExporting:
            case MCSAssetExportStatusCancelled:
                return;
            case MCSAssetExportStatusUnknown:
            case MCSAssetExportStatusFailed:
            case MCSAssetExportStatusSuspended: {
                if ( _URL == nil )
                    _URL = [NSURL URLWithString:_URLString];
                if ( _task != nil )
                    return;

                __weak typeof(self) _self = self;
                _task = [MCSPrefetcherManager.shared prefetchWithURL:_URL progress:nil completed:^(NSError * _Nullable error) {
                    __strong typeof(_self) self = _self;
                    if ( self == nil ) return;
                    [self _prefetchTaskDidCompleteWithError:error];
                }];

                _task.startedExecuteBlock = ^(id<MCSPrefetchTask>  _Nonnull task) {
                    __strong typeof(_self) self = _self;
                    if ( self == nil ) return;
                    [self _prefetchTaskDidStart];
                };

                _status = MCSAssetExportStatusWaiting;
                isChanged = YES;
            }
                return;
        }
    }];
    if ( isChanged ) [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterStatusDidChangeNotification object:self];
}

- (void)suspend {
    __block BOOL isChanged = NO;
    [self _lockInBlock:^{
        switch ( _status ) {
            case MCSAssetExportStatusFinished:
            case MCSAssetExportStatusFailed:
            case MCSAssetExportStatusCancelled:
            case MCSAssetExportStatusSuspended:
                return;
            case MCSAssetExportStatusUnknown:
            case MCSAssetExportStatusWaiting:
            case MCSAssetExportStatusExporting: {
                if ( _task != nil ) {
                    [_task cancel];
                    _task = nil;
                }

                _status = MCSAssetExportStatusSuspended;
                isChanged = YES;
            }
        }
    }];
    if ( isChanged ) [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterStatusDidChangeNotification object:self];
}

- (void)cancel {
    __block BOOL isChanged = NO;
    [self _lockInBlock:^{
        switch ( _status ) {
            case MCSAssetExportStatusFinished:
            case MCSAssetExportStatusCancelled:
                return;
            case MCSAssetExportStatusUnknown:
            case MCSAssetExportStatusFailed:
            case MCSAssetExportStatusSuspended:
            case MCSAssetExportStatusWaiting:
            case MCSAssetExportStatusExporting: {
                if ( _task != nil ) {
                    [_task cancel];
                    _task = nil;
                }

                _status = MCSAssetExportStatusCancelled;
                isChanged = YES;
            }
        }
    }];
    if ( isChanged ) [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterStatusDidChangeNotification object:self];
}

- (void)willBeRemoved {
    [self _lockInBlock:^{
        if ( _task != nil ) {
            [_task cancel];
            _task = nil;
        }
    }];
}

#pragma mark - mark

- (void)_syncProgress {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        switch ( self->_status ) {
            case MCSAssetExportStatusUnknown:
            case MCSAssetExportStatusWaiting:
            case MCSAssetExportStatusFailed:
            case MCSAssetExportStatusSuspended:
            case MCSAssetExportStatusCancelled:
            case MCSAssetExportStatusFinished:
                break;
            case MCSAssetExportStatusExporting: {
                [self synchronize];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self performSelector:@selector(_syncProgress) withObject:nil afterDelay:0.5 inModes:@[NSRunLoopCommonModes]];
                });
            }
                break;
        }
    });
}

- (void)_prefetchTaskDidStart {
    [self _lockInBlock:^{
        _status = MCSAssetExportStatusExporting;
    }];
    [self _syncProgress];
    [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterStatusDidChangeNotification object:self];
}

- (void)_prefetchTaskDidCompleteWithError:(NSError *_Nullable)error {
    [self synchronize];
    [self _lockInBlock:^{
        _task = nil;
        _status = error != nil ? MCSAssetExportStatusFailed : MCSAssetExportStatusFinished;
    }];
    NSDictionary *userInfo = nil;
    if ( error != nil ) {
        userInfo = @{MCSAssetExporterErrorUserInfoKey: error};
    }
    [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterStatusDidChangeNotification object:self userInfo:userInfo];
}

- (void)_lockInBlock:(void(^NS_NOESCAPE)(void))task {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    task();
    dispatch_semaphore_signal(_semaphore);
}

- (void)_synchronizeForFILEAsset:(FILEAsset *)asset {
    __block BOOL isChanged = NO;
    [self _lockInBlock:^{
        if ( _status == MCSAssetExportStatusFinished )
            return;

        float progress = _progress;
        NSUInteger totalLength = asset.totalLength;
        if ( totalLength != 0 ) {
            __block id<MCSAssetContent> prev = nil;
            __block UInt64 length = 0;
            [asset enumerateContentNodesUsingBlock:^(id<FILEAssetContentNode>  _Nonnull node, BOOL * _Nonnull stop) {
                id<MCSAssetContent> cur = node.longestContent;
                length += cur.length;
                UInt64 prevPosition = prev.startPositionInAsset + prev.length;
                if ( prevPosition > cur.startPositionInAsset ) length -= (prevPosition - cur.startPositionInAsset);
                prev = cur;
            }];
            progress = length * 1.0 / totalLength;
        }
        isChanged = progress != _progress;
        if ( isChanged ) _progress = progress;
    }];

    if ( isChanged ) [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterProgressDidChangeNotification object:self];
}

- (void)_synchronizeForHLSAsset:(HLSAsset *)asset {
    __block BOOL isChanged = NO;
    [self _lockInBlock:^{
        if ( _status == MCSAssetExportStatusFinished )
            return;

        float progress = _progress;
        HLSAssetParser *parser = asset.parser;
        if ( parser != nil ) {
            // 获取所有相关的asset, 计算进度
            NSMutableArray<HLSAsset *> *allAssets = [NSMutableArray arrayWithObject:asset];
            NSArray<HLSAsset *> *subAssets = asset.subAssets;
            if ( subAssets != nil ) {
                [allAssets addObjectsFromArray:subAssets];
            }

            float all = 0;
            for ( HLSAsset *asset in allAssets ) {
                all += [self _calculateProgressWithHLSAsset:asset];
            }
            progress = all / allAssets.count;
        }

        isChanged = progress != _progress;
        if ( isChanged ) _progress = progress;
    }];

    if ( isChanged ) [NSNotificationCenter.defaultCenter postNotificationName:MCSAssetExporterProgressDidChangeNotification object:self];
}

- (float)_calculateProgressWithHLSAsset:(HLSAsset *)asset {
    if ( asset.parser != nil && asset.tsCount == 0 )
        return 1.0f;

    if ( asset.TsContents.count != 0 ) {
        NSMutableArray<id<HLSAssetTsContent>> *contents = [asset.TsContents mutableCopy];
        [contents sortUsingComparator:^NSComparisonResult(id<HLSAssetTsContent>obj1, id<HLSAssetTsContent>obj2) {
            if ( [obj1.name isEqualToString:obj2.name] && NSEqualRanges(obj1.rangeInAsset, obj2.rangeInAsset) ) {
                if ( obj1.length == obj2.length )
                    return NSOrderedSame;
                return obj1.length > obj2.length ? NSOrderedAscending : NSOrderedDescending;
            }
            return NSOrderedSame;
        }];

        float progress = 0;
        id<HLSAssetTsContent>pre = nil;
        for ( id<HLSAssetTsContent>content in contents ) {
            if ( pre == nil || !([content.name isEqualToString:pre.name] && NSEqualRanges(content.rangeInAsset, pre.rangeInAsset)) ) {
                progress += content.length * 1.0 / content.rangeInAsset.length;
            }
            pre = content;
        }

        return progress / asset.tsCount;
    }
    return 0.0f;
}
@end

@interface MCSAssetExporterManager () {
    SJSQLite3 *_sqlite3;
    NSHashTable<id<MCSAssetExportObserver>> *_Nullable _observers;
    dispatch_semaphore_t _semaphore;
    NSMutableArray<MCSAssetExporter *> *_exporters;

    id _progressDidChangeToken;
    id _statusDidChangeToken;
}
@end

@implementation MCSAssetExporterManager
+ (instancetype)shared {
    static id obj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        obj = [[self alloc] init];
    });
    return obj;
}

- (instancetype)init {
    self = [super init];
    if ( self ) {
        _semaphore = dispatch_semaphore_create(1);
        _exporters = NSMutableArray.array;

        _sqlite3 = MCSDatabase();

        __weak typeof(self) _self = self;
        _progressDidChangeToken = [NSNotificationCenter.defaultCenter addObserverForName:MCSAssetExporterProgressDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
            __strong typeof(_self) self = _self;
            if ( self == nil ) return;
                [self _progressDidChange:note.object];
            });
        }];
        _statusDidChangeToken = [NSNotificationCenter.defaultCenter addObserverForName:MCSAssetExporterStatusDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                __strong typeof(_self) self = _self;
                if ( self == nil ) return;
                NSError *error = [note.userInfo objectForKey:MCSAssetExporterErrorUserInfoKey];
                [self _statusDidChange:note.object error:error];
            });
        }];
    }
    return self;
}

- (void)dealloc {
    [NSNotificationCenter.defaultCenter removeObserver:_progressDidChangeToken];
    [NSNotificationCenter.defaultCenter removeObserver:_statusDidChangeToken];
}

- (void)setMaxConcurrentExportCount:(NSInteger)maxConcurrentExportCount {
    MCSPrefetcherManager.shared.maxConcurrentPrefetchCount = maxConcurrentExportCount;
}

- (NSInteger)maxConcurrentExportCount {
    return MCSPrefetcherManager.shared.maxConcurrentPrefetchCount;
}

- (nullable NSArray<id<MCSAssetExporter>> *)allExporters {
    __block NSArray<id<MCSAssetExporter>> *allExporters = nil;
    [self _lockInBlock:^{
        // memory
        NSMutableArray<NSNumber *> *exporterIdsInMemory = _exporters.count != 0 ? ([NSMutableArray arrayWithCapacity:_exporters.count]) : nil;
        for ( MCSAssetExporter *exporter in _exporters ) {
            [exporterIdsInMemory addObject:@(exporter.id)];
        }

        // disk
        NSArray<SJSQLite3Condition *> *conditions = nil;
        if ( exporterIdsInMemory.count != 0 ) {
            conditions = @[[SJSQLite3Condition conditionWithColumn:@"id" notIn:exporterIdsInMemory]];
        }
        NSArray<MCSAssetExporter *> *exportersInDisk = [_sqlite3 objectsForClass:MCSAssetExporter.class conditions:conditions orderBy:nil error:NULL];
        if ( exportersInDisk.count != 0 ) {
            [_exporters addObjectsFromArray:exportersInDisk];
        }

        // results
        if ( _exporters.count != 0 ) {
            allExporters = _exporters.copy;
        }
    }];
    return allExporters;
}

- (UInt64)countOfBytesAllExportedAssets {
    return MCSAssetCacheManager.shared.countOfBytesAllCaches - MCSAssetCacheManager.shared.countOfBytesRemovableCaches;
}

/// 注册观察者
///
///     导出的相关回调会通知该观察者.
///
- (void)registerObserver:(id<MCSAssetExportObserver>)observer {
    if ( observer == nil )
        return;
    [self _lockInBlock:^{
        if ( _observers == nil ) {
            _observers = NSHashTable.weakObjectsHashTable;
        }
        [_observers addObject:observer];
    }];
}

/// 移除观察
///
///     当不需要监听时, 可以调用该方法移除监听.
///
///     监听是自动移除的, 在观察者释放时并不需要显示的调用该方法
///
- (void)removeObserver:(id<MCSAssetExportObserver>)observer {
    if ( observer == nil )
        return;
    [self _lockInBlock:^{
        [_observers removeObject:observer];
    }];
}

/// 添加一个导出任务
///
/// \code
///         id<MCSAssetExporter> exporter = [session exportAssetWithURL:URL];
///         // 开启
///         [exporter resume];
/// \endcode
///
- (nullable id<MCSAssetExporter>)exportAssetWithURL:(NSURL *)URL {
    if ( URL.absoluteString.length == 0 )
        return nil;
    __block MCSAssetExporter *exporter = nil;
    [self _lockInBlock:^{
        exporter = [self _exportAssetWithURL:URL];
    }];
    [exporter synchronize];
    return exporter;
}

/// 删除导出的资源
///
- (void)removeAssetWithURL:(NSURL *)URL {
    if ( URL.absoluteString.length == 0 )
        return;

    __block BOOL isRemoved = NO;
    [self _lockInBlock:^{
        NSString *name = [MCSURL.shared assetNameForURL:URL];
        MCSAssetExporter *_Nullable exporter = [self _exporterInCachesForName:name];
        if ( exporter != nil ) {
            [exporter willBeRemoved];
            [_exporters removeObject:exporter];
            [_sqlite3 removeObjectForClass:MCSAssetExporter.class primaryKeyValue:@(exporter.id) error:NULL];
            [MCSAssetCacheManager.shared setProtected:NO forCacheWithURL:URL];
            [MCSAssetCacheManager.shared removeCacheForURL:URL];
            isRemoved = YES;
        }
    }];

    if ( isRemoved ) {
        for ( id<MCSAssetExportObserver> observer in MCSAllHashTableObjects(_observers) ) {
            if ( [observer respondsToSelector:@selector(exporterManager:didRemoveAssetWithURL:)] ) {
                [observer exporterManager:self didRemoveAssetWithURL:URL];
            }
        }
    }
}

/// 删除全部
///
- (void)removeAllAssets {
    __block BOOL isRemoved = NO;
    [self _lockInBlock:^{
        NSMutableArray<NSNumber *> *exporterIdsInMemory = _exporters.count != 0 ? ([NSMutableArray arrayWithCapacity:_exporters.count]) : nil;
        for ( MCSAssetExporter *exporter in _exporters ) {
            [exporterIdsInMemory addObject:@(exporter.id)];
        }

        NSArray<SJSQLite3Condition *> *conditions = nil;
        if ( exporterIdsInMemory.count != 0 ) {
            conditions = @[[SJSQLite3Condition conditionWithColumn:@"id" notIn:exporterIdsInMemory]];
        }
        NSArray<MCSAssetExporter *> *exportersInDisk = [_sqlite3 objectsForClass:MCSAssetExporter.class conditions:conditions orderBy:nil error:NULL];
        NSArray<MCSAssetExporter *> *exportersInMemory = _exporters;

        NSMutableArray<MCSAssetExporter *> *allExporters = [NSMutableArray arrayWithCapacity:exportersInDisk.count + exportersInMemory.count];
        if ( exportersInDisk.count != 0 ) {
            [allExporters addObjectsFromArray:exportersInDisk];
        }

        if ( exportersInMemory.count != 0 ) {
            [allExporters addObjectsFromArray:exportersInMemory];
        }

        if ( allExporters.count != 0 ) {
            [_exporters removeAllObjects];
            [_sqlite3 removeAllObjectsForClass:MCSAssetExporter.class error:NULL];
            for ( MCSAssetExporter *exporter in allExporters ) {
                [exporter willBeRemoved];
                id<MCSAsset> asset = [MCSAssetManager.shared assetWithName:exporter.name type:exporter.type];
                [MCSAssetCacheManager.shared setProtected:NO forCacheWithAsset:asset];
                [MCSAssetCacheManager.shared removeCacheForAsset:asset];
            }
            isRemoved = YES;
        }
    }];

    if ( isRemoved ) {
        for ( id<MCSAssetExportObserver> observer in MCSAllHashTableObjects(_observers) ) {
            if ( [observer respondsToSelector:@selector(exporterManagerDidRemoveAllAssets:)] ) {
                [observer exporterManagerDidRemoveAllAssets:self];
            }
        }
    }
}

/// 查询状态
///
- (MCSAssetExportStatus)statusWithURL:(NSURL *)URL {
    __block MCSAssetExportStatus status = MCSAssetExportStatusUnknown;
    if ( URL.absoluteString.length != 0 ) {
        [self _lockInBlock:^{
            NSString *name = [MCSURL.shared assetNameForURL:URL];
            MCSAssetExporter *exporter = [self _exporterInCachesForName:name];
            status = exporter.status;
        }];
    }
    return status;
}

/// 查询进度
///
- (float)progressWithURL:(NSURL *)URL {
    __block float progress = 0.0f;
    if ( URL.absoluteString.length != 0 ) {
        [self _lockInBlock:^{
            NSString *name = [MCSURL.shared assetNameForURL:URL];
            MCSAssetExporter *exporter = [self _exporterInCachesForName:name];
            progress = exporter.progress;
        }];
    }
    return progress;
}

/// 同步缓存, 更新缓存进度
///
- (void)synchronizeForExporterWithAssetURL:(NSURL *)URL {
    if ( URL.absoluteString.length != 0 ) {
        [self _lockInBlock:^{
            NSString *name = [MCSURL.shared assetNameForURL:URL];
            MCSAssetExporter *exporter = [self _exporterInCachesForName:name];
            [exporter synchronize];
        }];
    }
}

- (void)synchronize {
    [self _lockInBlock:^{
        for ( MCSAssetExporter *exporter in _exporters ) {
            [exporter synchronize];
        }
    }];
}

- (nullable NSArray<id<MCSAssetExporter>> *)exportsForMask:(MCSAssetExportStatusQueryMask)mask {
    __block NSArray<id<MCSAssetExporter>> *_Nullable retv = nil;;
    [self _lockInBlock:^{
        retv = [self _exportersInCachesForMask:mask];
    }];
    return retv;
}

#pragma mark - mark

- (void)_lockInBlock:(void(^NS_NOESCAPE)(void))task {
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    task();
    dispatch_semaphore_signal(_semaphore);
}

- (MCSAssetExporter *)_exportAssetWithURL:(NSURL *)URL {
    NSString *name = [MCSURL.shared assetNameForURL:URL];
    MCSAssetExporter *exporter = [self _exporterInCachesForName:name];
    if ( exporter == nil ) {
        MCSAssetType type = [MCSURL.shared assetTypeForURL:URL];
        exporter = [MCSAssetExporter.alloc initWithURLString:URL.absoluteString name:name type:type];
        [MCSAssetCacheManager.shared setProtected:YES forCacheWithURL:URL];
        [_sqlite3 save:exporter error:NULL];
        [_exporters addObject:exporter];
    }
    return exporter;
}

// memory + disk
- (nullable MCSAssetExporter *)_exporterInCachesForName:(NSString *)name {
    // memory
    MCSAssetExporter *exporter = [self _exporterInMemoryForName:name];
    if ( exporter == nil ) {
        // disk
        exporter = [_sqlite3 objectsForClass:MCSAssetExporter.class conditions:@[
            [SJSQLite3Condition conditionWithColumn:@"name" value:name]
        ] orderBy:nil error:NULL].firstObject;
        // add into memory
        if ( exporter != nil ) {
            [_exporters addObject:exporter];
        }
    }
    return exporter;
}

- (nullable MCSAssetExporter *)_exporterInMemoryForName:(NSString *)name {
    for ( MCSAssetExporter *exporter in _exporters ) {
        if ( [exporter.name isEqualToString:name] )
            return exporter;
    }
    return nil;
}

// memory + disk
- (nullable NSArray<MCSAssetExporter *> *)_exportersInCachesForMask:(MCSAssetExportStatusQueryMask)mask {
    // memory
    NSArray<MCSAssetExporter *> *_Nullable mem = [self _exportersInMemoryForMask:mask];
    NSMutableArray<NSNumber *> *notIn = [NSMutableArray arrayWithObject:@(0)];
    for ( MCSAssetExporter *exporter in mem ) {
        [notIn addObject:@(exporter.id)];
    }

    // disk
    NSMutableArray<NSNumber *> *queryStatus = NSMutableArray.array;
    if ( mask & MCSAssetExportStatusQueryMaskUnknown ) {
        [queryStatus addObject:@(MCSAssetExportStatusUnknown)];
    }
    if ( mask & MCSAssetExportStatusQueryMaskWaiting ) {
        [queryStatus addObject:@(MCSAssetExportStatusWaiting)];
    }
    if ( mask & MCSAssetExportStatusQueryMaskExporting ) {
        [queryStatus addObject:@(MCSAssetExportStatusExporting)];
    }
    if ( mask & MCSAssetExportStatusQueryMaskFinished ) {
        [queryStatus addObject:@(MCSAssetExportStatusFinished)];
    }
    if ( mask & MCSAssetExportStatusQueryMaskFailed ) {
        [queryStatus addObject:@(MCSAssetExportStatusFailed)];
    }
    if ( mask & MCSAssetExportStatusQueryMaskSuspended ) {
        [queryStatus addObject:@(MCSAssetExportStatusSuspended)];
    }
    if ( mask & MCSAssetExportStatusQueryMaskCancelled ) {
        [queryStatus addObject:@(MCSAssetExportStatusCancelled)];
    }
    NSArray<MCSAssetExporter *> *_Nullable disk = [_sqlite3 objectsForClass:MCSAssetExporter.class conditions:@[
        [SJSQLite3Condition conditionWithColumn:@"id" notIn:notIn],
        [SJSQLite3Condition conditionWithColumn:@"status" in:queryStatus]
    ] orderBy:nil error:NULL];
    // add into memory
    if ( disk.count != 0 ) {
        [_exporters addObjectsFromArray:disk];
    }

    NSMutableArray<MCSAssetExporter *> *_Nullable retv = nil;
    if ( mem.count != 0 || disk.count != 0 ) {
        retv = NSMutableArray.array;
        if ( mem.count != 0 )
            [retv addObjectsFromArray:mem];
        if ( disk.count != 0 )
            [retv addObjectsFromArray:disk];
    }
    return retv.copy;
}

- (nullable NSArray<MCSAssetExporter *> *)_exportersInMemoryForMask:(MCSAssetExportStatusQueryMask)mask {
    NSMutableArray<MCSAssetExporter *> *_Nullable retv = nil;
    for ( MCSAssetExporter *exporter in _exporters ) {
        if ( mask & (1 << exporter.status) ) {
            if ( retv == nil ) {
                retv = NSMutableArray.array;
            }
            [retv addObject:exporter];
        }
    }
    return retv.copy;
}

- (void)_statusDidChange:(MCSAssetExporter *)exporter error:(nullable NSError *)error {
    MCSAssetExportStatus status = exporter.status;
    if ( status == MCSAssetExportStatusCancelled ) {
        [self _lockInBlock:^{
            id<MCSAsset> asset = [MCSAssetManager.shared assetWithName:exporter.name type:exporter.type];
            [MCSAssetCacheManager.shared setProtected:NO forCacheWithAsset:asset];
            [_exporters removeObject:exporter];
            [_sqlite3 removeObjectForClass:MCSAssetExporter.class primaryKeyValue:@(exporter.id) error:NULL];
        }];
    }
    else {
        /// 将状态同步数据库
        ///
        /// 状态处于 Waiting, Exporting 时不需要同步至数据库, 仅维护 expoter 在内存中的状态即可.
        /// 当再次启动App时, 状态将在 Suspended, Failed, Finished 之间.
        ///
        switch ( exporter.status ) {
            case MCSAssetExportStatusFinished:
            case MCSAssetExportStatusFailed:
            case MCSAssetExportStatusSuspended:
                [_sqlite3 updateObjects:@[exporter] forKeys:@[@"status"] error:NULL];
                break;
            case MCSAssetExportStatusUnknown:
            case MCSAssetExportStatusCancelled:
            case MCSAssetExportStatusWaiting:
            case MCSAssetExportStatusExporting:
                break;
        }
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if ( exporter.statusDidChangeExecuteBlock != nil ) {
            exporter.statusDidChangeExecuteBlock(exporter);
        }

        for ( id<MCSAssetExportObserver> observer in MCSAllHashTableObjects(self->_observers) ) {
            if ( [observer respondsToSelector:@selector(exporter:statusDidChange:)] ) {
                [observer exporter:exporter statusDidChange:status];
            }
        }

        if ( status == MCSAssetExportStatusFailed ) {
            for ( id<MCSAssetExportObserver> observer in MCSAllHashTableObjects(self->_observers) ) {
                if ( [observer respondsToSelector:@selector(exporter:statusDidChange:)] ) {
                    [observer exporter:exporter failedWithError:error];
                }
            }
        }
    });
}

- (void)_progressDidChange:(MCSAssetExporter *)exporter {
    dispatch_async(dispatch_get_main_queue(), ^{
        if ( exporter.progressDidChangeExecuteBlock != nil ) {
            exporter.progressDidChangeExecuteBlock(exporter);
        }

        for ( id<MCSAssetExportObserver> observer in MCSAllHashTableObjects(self->_observers) ) {
            if ( [observer respondsToSelector:@selector(exporter:progressDidChange:)] ) {
                [observer exporter:exporter progressDidChange:exporter.progress];
            }
        }
    });
}
@end

/*
 v2:
    - 需要对缓存管理进行改造
        - asset增加常驻标记
        - removeAllCaches 将不可用
        - 需要重新提供删除相关的方法
        - 需要提供常驻资源占用的缓存
        - 需要提供正常请求占用的缓存
    - 增加syncFromCache方法, 用于同步进度
    - 增加自己的状态
 */


text:
@interface IMAdFormat () {
    IMRequestResponseManager *manager;
}

@end

@implementation IMAdFormat
@synthesize requestType,error;

- (id)init {
    if (self = [super init]) {
        manager = [[IMRequestResponseManager alloc] init];
        requestType = IMAdRequestTypeNone;
    }
    return self;
}

- (void)successCallback:(void (^)(NSArray *ads))success withAds:(NSArray *)ads {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (success != nil) {
            success(ads);
        }
    });
}
- (void)failureCallback:(void (^)(NSError *e))failed {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (failed != nil) {
            failed(error);
        }
    });
}

- (NSData *)loadRequestInternal:(IMRequest *)request {
    NSData *response = [manager sendInMobiAdRequest:[request toJSON] deviceIP:request.device.carrierIP deviceUserAgent:request.device.userAgent];
    //NSLog(@"response=%@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
    self.error = manager.error;
    _isRequestInProgress = NO;
    return response;
}
- (BOOL)canLoadRequest:(IMRequest *)request {

    BOOL load = YES;
    if (request != nil) {
        request.requestType = requestType;
        if ([request isValid]) {
            if (!_isRequestInProgress) {
                _isRequestInProgress = YES;
            } else {
                load = NO;
            }
        } else {
            load = NO;
        }
    } else {
        load = NO;
    }
    return load;
}

@end


text:
Snips Assistant - Basic Skills
======================================

|MIT License|

snips-assistant-basics combines a snips assistant vocabulary zip and a range of snips skills from pypi together with a Snipsfile

Installation
------------
First ensure snips and snipsskills is installed

https://github.com/snipsco/snips-platform-documentation

https://github.com/snipsco/snipsskills

Clone the repository and from inside the top level folder run snipsskills install and snipsskills run::

	cd /home/pi
	git clone https://github.com/syntithenai/snips-assistant-basics.git
	cd snips-assistant-basics
	snipsskills install
	(optionally run tests)   make
	snipsskills run

Usage
-----
Four skills are tied to voice commands

- https://github.com/syntithenai/snips_skill_maths
- https://github.com/syntithenai/snips_skill_spelling
- https://github.com/syntithenai/snips_skill_monitorcontrol
- https://github.com/syntithenai/snips_skill_usbpower

Maths

- "what is 4 plus 2"

Spelling

- "spell kitten"

MonitorControl

- "turn the monitor on", "turn the monitor off"
- "set the monitor volume to 70"
- "set the monitor brightness to 100"

UsbPower

- "turn on/off usb port 2","turn off the usb light" !!! Supported hubs only - https://github.com/mvp/uhubctl. By default a raspberry pi, this will turn off all usb power including the microphone and crash snips :(

Contributing
------------

.. |MIT License| image:: https://img.shields.io/badge/license-MIT-blue.svg
:target: https://raw.githubusercontent.com/snipsco/snips-skill-hue/master/LICENSE.txt
:alt: MIT License

.. _`pip`: http://www.pip-installer.org
.. _`Snips`: https://www.snips.ai
.. _`LICENSE.txt`: https://github.com/snipsco/snips-skill-hue/blob/master/LICENSE.txt
.. _`Contribution Guidelines`: https://github.com/snipsco/snips-skill-hue/blob/master/CONTRIBUTING.rst
.. _snipsskills: https://github.com/snipsco/snipsskills


text:
using CloudFoundry.CloudController.V2.Interfaces;
using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;

namespace CloudFoundry.CloudController.V2.Client.Data
{
    /// <summary>
    /// Data class used for serializing the "CloudFoundry.CloudController.V2.Client.PrivateDomainsEndpoint.CreatePrivateDomainOwnedByGivenOrganization()" Request
    /// <para>For usage information, see online documentation at "http://apidocs.cloudfoundry.org/195/private_domains/create_a_private_domain_owned_by_the_given_organization.html"</para>
    /// </summary>
    [GeneratedCodeAttribute("cf-sdk-builder", "1.0.0.0")]
    public partial class CreatePrivateDomainOwnedByGivenOrganizationRequest : CloudFoundry.CloudController.V2.Client.Data.Base.AbstractCreatePrivateDomainOwnedByGivenOrganizationRequest
    {
    }
}

namespace CloudFoundry.CloudController.V2.Client.Data.Base
{
    /// <summary>
    /// Base abstract data class used for serializing the "CloudFoundry.CloudController.V2.Client.PrivateDomainsEndpoint.CreatePrivateDomainOwnedByGivenOrganization()" Request
    /// <para>For usage information, see online documentation at "http://apidocs.cloudfoundry.org/195/private_domains/create_a_private_domain_owned_by_the_given_organization.html"</para>
    /// </summary>
    [GeneratedCodeAttribute("cf-sdk-builder", "1.0.0.0")]
    public abstract class AbstractCreatePrivateDomainOwnedByGivenOrganizationRequest
    {

        /// <summary>
        /// <para>The name of the domain.</para>
        /// </summary>
        [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// <para>The organization that owns the domain. If not specified, the domain is shared.</para>
        /// </summary>
        [JsonProperty("owning_organization_guid", NullValueHandling = NullValueHandling.Ignore)]
        public Guid? OwningOrganizationGuid
        {
            get;
            set;
        }

        /// <summary>
        /// <para>The guid of the domain.</para>
        /// </summary>
        [JsonProperty("guid", NullValueHandling = NullValueHandling.Ignore)]
        public Guid? Guid
        {
            get;
            set;
        }
    }
}


text:
(function () {

    module.exports = Home;

    var Location = require('../quote/Location')
    var Dependents = require('../quote/Dependents')

    function Home() {
        var self = this;

        var controls = {
            quote: $('a[ng-click ^= toQuote]'),
            dependentsContainer: $('[ng-form=quoteBoxForm]')
        }

        self.location = new Location();
        self.dependents = new Dependents(controls.dependentsContainer);

        self.load = function () {
            return browser.get('/').sleep(3000).then(self.location.clearZip);
        }

        self.quote = function () {
            return controls.quote.click()
        }
    }

    Home.login = function(zip) {
        zip = zip || '17012';
        var home = new Home();
        return home.load()
        .then(function () { return home.location.enterZip(zip) })
        .then(function() { return home.dependents.addSelf(true, '07/06/1986', false) })
        .then(home.quote)
		.sleep(7000)
    }

})();


text:
require "spec_helper"

describe "listing groups" do
  let!(:group) { create :group }

  before do
    visit "/detour/groups"
  end

  it "lists every group" do
    within "ul li.group" do
      page.should have_content group.name
    end
  end
end

describe "showing a group" do
  let(:user)       { create :user }
  let(:group)      { create :group }

  before do
    User.instance_variable_set "@detour_flaggable_find_by", :email
    create :membership, group: group, member: user
    visit "/detour/groups/#{group.to_param}"
  end

  it "shows the group name" do
    page.should have_content "User Group: #{group.name}"
  end

  it "lists every membership" do
    page.find("input[name=member_identifier]").value.should eq user.email
  end
end

describe "creating a group", js: true do
  before do
    visit "/detour/groups"
    page.find("[data-target='#create-group']").click
  end

  context "when successful" do
    before do
      fill_in "group[name]", with: "New Group"
      select "User", from: "group[flaggable_type]"
      click_button "Create Group"
    end

    it "displays a flash message" do
      page.should have_content "Your group has been successfully created."
    end

    it "shows the newly created group" do
      within "ul li.group" do
        page.should have_content "New Group"
      end
    end
  end

  context "when unsuccessful" do
    before do
      click_button "Create Group"
    end

    it "displays a correct error header" do
      within ".modal .panel-heading" do
        page.should have_content "Whoops! There were some errors saving your group:"
      end
    end

    it "displays error messages" do
      page.should have_content "Name can't be blank"
    end
  end
end

describe "updating a group" do
  let(:group) { create :group }

  before do
    visit "/detour/groups/#{group.to_param}"
  end

  context "when successful" do
    before do
      fill_in "group[name]", with: "New Group Name"
      click_button "Update Group"
    end

    it "displays a flash message" do
      page.should have_content "Your group has been successfully updated."
    end

    it "shows the newly updated group" do
      within "h1" do
        page.should have_content "New Group Name"
      end
    end
  end

  context "when unsuccessful" do
    before do
      fill_in "group[name]", with: ""
      click_button "Update Group"
    end

    it "displays error messages" do
      page.should have_content "Name can't be blank"
    end
  end
end

describe "adding a member to a group", js: true do
  let(:group) { create :group }
  let!(:user) { create :user }

  before do
    User.instance_variable_set "@detour_flaggable_find_by", :email
    visit "/detour/groups/#{group.to_param}"
    page.find(".add-fields").click
  end

  context "when successful" do
    before do
      name = page.find("##{page.all("label")[-2][:for]}")[:name]
      fill_in name, with: user.email
      click_button "Update Group"
    end

    it "displays a flash message" do
      page.should have_content "Your group has been successfully updated."
    end

    it "shows the newly added member" do
      page.find("input[type='text'][disabled]").value.should eq user.email
    end
  end

  context "when unsuccessful" do
    before do
      click_button "Update Group"
    end

    it "displays a correct error header" do
      within ".panel-danger .panel-heading" do
        page.should have_content "Whoops! There were some errors saving your group:"
      end
    end

    it "displays error messages" do
      page.should have_content "User \"\" could not be found"
    end
  end
end

describe "removing a member from a group" do
  let(:group) { create :group }
  let(:user) { create :user }
  let!(:membership) { create :membership, group: group, member: user }

  before do
    User.instance_variable_set "@detour_flaggable_find_by", :email
    visit "/detour/groups/#{group.to_param}"
    name = page.find("##{page.all("label").last[:for]}")[:name]
    check name
    click_button "Update Group"
  end

  it "does not show the removed member" do
    page.should_not have_selector "label[for='group_memberships_attributes_0_member_key']"
  end
end

describe "destroying a group", js: true do
  let!(:group) { create :group }

  before do
    visit "/detour/groups/#{group.to_param}"
    click_button "Delete Group"
    page.find(".modal a").click
  end

  it "shows a flash message" do
    page.should have_content "Group \"#{group.name}\" has been deleted"
  end

  it "shows the remaining groups" do
    page.should_not have_selector ".group"
  end
end


text:
a-) Crie um serviço de calculadora com operações de soma, subtração, multiplicação e divisão, utilize esse serviço em dois controllers diferentes

b-) Instale o node js em seu ambiente e execute o exemplo 7 em localhost

c-) Execute o exemplo 8 em localhost