text:
package org.apache.sling.validation.impl.resourcemodel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.threads.ThreadPool;
import org.apache.sling.commons.threads.ThreadPoolManager;
import org.apache.sling.validation.impl.model.ChildResourceImpl;
import org.apache.sling.validation.impl.model.ParameterizedValidatorImpl;
import org.apache.sling.validation.impl.model.ResourcePropertyImpl;
import org.apache.sling.validation.impl.model.ValidationModelImpl;
import org.apache.sling.validation.impl.util.Trie;
import org.apache.sling.validation.model.ChildResource;
import org.apache.sling.validation.model.ParameterizedValidator;
import org.apache.sling.validation.model.ResourceProperty;
import org.apache.sling.validation.model.ValidationModel;
import org.apache.sling.validation.model.spi.ValidationModelCache;
import org.apache.sling.validation.model.spi.ValidationModelProvider;
import org.apache.sling.validation.spi.Validator;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//the event handler is dynamic and registered in the activate method
@Service(value = ValidationModelProvider.class)
@Component
public class ResourceValidationModelProviderImpl implements ValidationModelProvider, EventHandler {

    static final String MODEL_XPATH_QUERY = "/jcr:root%s/*[@sling:resourceType=\""+ResourceValidationModelProviderImpl.VALIDATION_MODEL_RESOURCE_TYPE+"\" and @"+ResourceValidationModelProviderImpl.VALIDATED_RESOURCE_TYPE+"=\"%s\"]";
    static final String[] TOPICS = { SlingConstants.TOPIC_RESOURCE_REMOVED, SlingConstants.TOPIC_RESOURCE_CHANGED,
            SlingConstants.TOPIC_RESOURCE_ADDED };

    public static final String NAME_REGEX = "nameRegex";
    public static final String CHILDREN = "children";
    public static final String VALIDATOR_ARGUMENTS = "validatorArguments";
    public static final String VALIDATORS = "validators";
    public static final String OPTIONAL = "optional";
    public static final String PROPERTY_MULTIPLE = "propertyMultiple";
    public static final String PROPERTIES = "properties";
    public static final String VALIDATION_MODEL_RESOURCE_TYPE = "sling/validation/model";
    public static final String MODELS_HOME = "validation/";
    public static final String APPLICABLE_PATHS = "applicablePaths";
    public static final String VALIDATED_RESOURCE_TYPE = "validatedResourceType";
    public static final String SEVERITY = "severity";

    @Reference
    private ResourceResolverFactory rrf = null;

    @Reference
    private ValidationModelCache cache;

    private static final Logger LOG = LoggerFactory.getLogger(ResourceValidationModelProviderImpl.class);

    @Reference
    private ThreadPoolManager tpm = null;

    private ThreadPool threadPool;

    private ServiceRegistration eventHandlerRegistration;

    @Activate
    protected void activate(ComponentContext componentContext) throws LoginException {
        threadPool = tpm.get("Validation Service Thread Pool");
        ResourceResolver rr = null;
        try {
            rr = rrf.getAdministrativeResourceResolver(null);
            StringBuilder sb = new StringBuilder("(");
            String[] searchPaths = rr.getSearchPath();
            if (searchPaths.length > 1) {
                sb.append("|");
            }
            for (String searchPath : searchPaths) {
                if (searchPath.endsWith("/")) {
                    searchPath = searchPath.substring(0, searchPath.length() - 1);
                }
                String path = searchPath + "/*" + ResourceValidationModelProviderImpl.MODELS_HOME;
                sb.append("(path=").append(path).append("*)");
            }
            sb.append(")");
            Dictionary<String, Object> eventHandlerProperties = new Hashtable<String, Object>();
            eventHandlerProperties.put(EventConstants.EVENT_TOPIC, TOPICS);
            eventHandlerProperties.put(EventConstants.EVENT_FILTER, sb.toString());
            eventHandlerRegistration = componentContext.getBundleContext().registerService(
                    EventHandler.class.getName(), this, eventHandlerProperties);
            LOG.debug("Registered event handler for validation models in {}", sb.toString());
        } finally {
            if (rr != null) {
                rr.close();
            }
        }
    }

    @Deactivate
    protected void deactivate(ComponentContext componentContext) {
        if (threadPool != null) {
            tpm.release(threadPool);
        }
        if (eventHandlerRegistration != null) {
            eventHandlerRegistration.unregister();
            eventHandlerRegistration = null;
        }
    }

    @Override
    public void handleEvent(Event event) {
        LOG.debug("Asynchronously invalidating models cache due to event {}", event);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                cache.invalidate();
            }
        };
        threadPool.execute(task);
    }

    /**
     * Searches for validation models bound to a specific resource type in the repository. All validation models
     * will be returned in a {@link Trie} data structure for easy retrieval of the models using their
     * {@code applicable paths} as trie keys.
     *
     * @param relativeResourceType
     *            {@inheritDoc}
     * @param validatorsMap
     *            {@inheritDoc}
     * @return {@inheritDoc}
     * @throws {@inheritDoc}
     */
    @Override
    @Nonnull
    public Collection<ValidationModel> getModels(@Nonnull String relativeResourceType, @Nonnull Map<String, Validator<?>> validatorsMap, @Nonnull ResourceResolver resourceResolver) {
        ValidationModelImpl vm;
        Collection<ValidationModel> validationModels = new ArrayList<ValidationModel>();
        String[] searchPaths = resourceResolver.getSearchPath();
        for (String searchPath : searchPaths) {
            final String queryString = String.format(MODEL_XPATH_QUERY, searchPath, relativeResourceType);
            Iterator<Resource> models = resourceResolver.findResources(queryString, "xpath");
            while (models.hasNext()) {
                Resource model = models.next();
                LOG.debug("Found validation model resource {}.", model.getPath());
                String jcrPath = model.getPath();
                try {
                    ValueMap validationModelProperties = model.adaptTo(ValueMap.class);
                    String[] applicablePaths = PropertiesUtil.toStringArray(validationModelProperties.get(ResourceValidationModelProviderImpl.APPLICABLE_PATHS, String[].class));
                    Resource r = model.getChild(ResourceValidationModelProviderImpl.PROPERTIES);
                    List<ResourceProperty> resourceProperties = buildProperties(validatorsMap,r);
                    List<ChildResource> children = buildChildren(model, model, validatorsMap);
                    if (resourceProperties.isEmpty() && children.isEmpty()) {
                        throw new IllegalArgumentException("Neither children nor properties set.");
                    } else {
                        vm = new ValidationModelImpl(resourceProperties, relativeResourceType,
                                applicablePaths, children);
                        validationModels.add(vm);
                    }
                } catch (IllegalArgumentException e) {
                    throw new IllegalStateException("Found invalid validation model in '" + jcrPath + "': "
                            + e.getMessage(), e);
                }
            }
            if (!validationModels.isEmpty()) {
                // do not continue to search in other search paths if some results were already found!
                // earlier search paths overlay lower search paths (/apps wins over /libs)
                // the applicable content paths do not matter here!
                break;
            }
        }
        return validationModels;
    }

    /**
     * Creates a set of the properties that a resource is expected to have, together with the associated validators.
     *
     * @param validatorsMap      a map containing {@link Validator}s as values and their class names as keys
     * @param propertiesResource the resource identifying the properties node from a validation model's structure (might be {@code null})
     * @return a set of properties or an empty set if no properties are defined
     * @see ResourceProperty
     */
    private @Nonnull List<ResourceProperty> buildProperties(@Nonnull Map<String, Validator<?>> validatorsMap, Resource propertiesResource) {
        List<ResourceProperty> properties = new ArrayList<ResourceProperty>();
        if (propertiesResource != null) {
            for (Resource property : propertiesResource.getChildren()) {
                String fieldName = property.getName();
                ValueMap propertyValueMap = property.adaptTo(ValueMap.class);
                Boolean propertyMultiple = PropertiesUtil.toBoolean(propertyValueMap.get(ResourceValidationModelProviderImpl.PROPERTY_MULTIPLE), false);
                Boolean propertyRequired = !PropertiesUtil.toBoolean(propertyValueMap.get(ResourceValidationModelProviderImpl.OPTIONAL), false);
                String nameRegex = PropertiesUtil.toString(propertyValueMap.get(ResourceValidationModelProviderImpl.NAME_REGEX), null);
                Resource validators = property.getChild(ResourceValidationModelProviderImpl.VALIDATORS);
                List<ParameterizedValidator> parameterizedValidators = new ArrayList<ParameterizedValidator>();
                if (validators != null) {
                    Iterator<Resource> validatorsIterator = validators.listChildren();
                    while (validatorsIterator.hasNext()) {
                        Resource validator = validatorsIterator.next();
                        ValueMap validatorProperties = validator.adaptTo(ValueMap.class);
                        if (validatorProperties == null) {
                            throw new IllegalStateException("Could not adapt resource " + validator.getPath() + " to ValueMap");
                        }
                        String validatorName = validator.getName();
                        Validator<?> v = validatorsMap.get(validatorName);
                        if (v == null) {
                            throw new IllegalArgumentException("Could not find validator with name '" + validatorName + "'");
                        }
                        // get arguments for validator
                        String[] validatorArguments = validatorProperties.get(ResourceValidationModelProviderImpl.VALIDATOR_ARGUMENTS, String[].class);
                        Map<String, Object> validatorArgumentsMap = new HashMap<String, Object>();
                        if (validatorArguments != null) {
                            for (String arg : validatorArguments) {
                                String[] keyValuePair = arg.split("=");
                                if (keyValuePair.length != 2) {
                                    continue;
                                }
                                validatorArgumentsMap.put(keyValuePair[0], keyValuePair[1]);
                            }
                        }
                        // get severity
                        Integer severity = validatorProperties.get(SEVERITY, Integer.class);
                        parameterizedValidators.add(new ParameterizedValidatorImpl(v, validatorArgumentsMap, severity));
                    }
                }
                ResourceProperty f = new ResourcePropertyImpl(fieldName, nameRegex, propertyMultiple, propertyRequired, parameterizedValidators);
                properties.add(f);
            }
        }
        return properties;
    }

    /**
     * Searches children resources from a {@code modelResource}, starting from the {@code rootResource}. If one needs all the children
     * resources of a model, then the {@code modelResource} and the {@code rootResource} should be identical.
     *
     * @param modelResource          the resource describing a {@link org.apache.sling.validation.api.ValidationModel}
     * @param rootResource           the model's resource from which to search for children (this resource has to have a {@link
     *                               ResourceValidationModelProviderImpl#CHILDREN} node directly underneath it)
     * @param validatorsMap          a map containing {@link Validator}s as values and their class names as values
     * @return a list of all the children resources; the list will be empty if there are no children resources
     */
    private @Nonnull List<ChildResource> buildChildren(@Nonnull Resource modelResource, @Nonnull Resource rootResource,
                                                    @Nonnull Map<String, Validator<?>> validatorsMap) {
        List<ChildResource> children = new ArrayList<ChildResource>();
        Resource childrenResource = rootResource.getChild(ResourceValidationModelProviderImpl.CHILDREN);
        if (childrenResource != null) {
            for (Resource child : childrenResource.getChildren()) {
                // if pattern is set, always use that
                ValueMap childrenProperties = child.adaptTo(ValueMap.class);
                if (childrenProperties == null) {
                    throw new IllegalStateException("Could not adapt resource " + child.getPath() + " to ValueMap");
                }
                final String name = child.getName();
                final String nameRegex;
                if (childrenProperties.containsKey(ResourceValidationModelProviderImpl.NAME_REGEX)) {
                    nameRegex = childrenProperties.get(ResourceValidationModelProviderImpl.NAME_REGEX, String.class);
                } else {
                    // otherwise fall back to the name
                    nameRegex = null;
                }
                boolean isRequired = !PropertiesUtil.toBoolean(childrenProperties.get(ResourceValidationModelProviderImpl.OPTIONAL), false);
                ChildResource childResource = new ChildResourceImpl(name, nameRegex, isRequired, buildProperties(validatorsMap, child.getChild(ResourceValidationModelProviderImpl.PROPERTIES)), buildChildren(modelResource, child, validatorsMap));
                children.add(childResource);
            }
        }
        return children;
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Neat.StreamManager.Factory.ReaderFactory.Interface;
using Neat.StreamManager.Factory.ReaderFactory.Parameters.Abstract;
using Neat.StreamManager.Factory.StreamFactory.Interface;
using Neat.StreamManager.Factory.StreamFactory.Parameters.Abstract;
using Neat.StreamManager.Factory.WriterFactory.Interface;
using Neat.StreamManager.Factory.WriterFactory.Parameters.Abstract;
using Neat.StreamManager.Interface;

namespace Neat.StreamManager
{
    public class StreamManager : IStreamManager
    {
        private readonly IEnumerable<IStreamFactory> _streamFactories;
        private readonly IEnumerable<ITextReaderFactory> _textReaderFactories;
        private readonly IEnumerable<ITextWriterFactory> _textWriterFactories;
        private Dictionary<StreamType, IStreamFactory> _streamFactoriesHash;
        private Dictionary<TextReaderType, ITextReaderFactory> _textReaderFactoriesHash;
        private Dictionary<TextWriterType, ITextWriterFactory> _textWriterFactoriesHash;
        private bool _streamFactoriesHashLoaded;
        private bool _textReaderFactoriesHashLoaded;
        private bool _textWriterFactoriesHashLoaded;
        private readonly object _streamFactoriesHashLock;
        private readonly object _textReaderFactoriesHashLock;
        private readonly object _textWriterFactoriesHashLock;

        public StreamManager(IEnumerable<IStreamFactory> streamFactories, IEnumerable<ITextReaderFactory> textReaderFactories, IEnumerable<ITextWriterFactory> textWriterFactories)
        {
            _streamFactories = streamFactories;
            _textReaderFactories = textReaderFactories;
            _textWriterFactories = textWriterFactories;
            _streamFactoriesHashLoaded = false;
            _textReaderFactoriesHashLoaded = false;
            _textWriterFactoriesHashLoaded = false;
            _streamFactoriesHashLock = new object();
            _textReaderFactoriesHashLock = new object();
            _textWriterFactoriesHashLock = new object();
        }

        public Stream GetStream(StreamType streamType, StreamParameters streamParameters)
        {
            LoadStreamFactories();

            if (_streamFactoriesHash.ContainsKey(streamType))
            {
                return _streamFactoriesHash[streamType].Create(streamParameters);
            }

            throw new ArgumentException(string.Format("No Factory defined for type {0}", streamType));
        }

        public TextReader GetTextReader(TextReaderType textReaderType, TextReaderParameters textReaderParameters)
        {
            LoadTextReaderFactories();

            if (_textReaderFactoriesHash.ContainsKey(textReaderType))
            {
                return _textReaderFactoriesHash[textReaderType].Create(textReaderParameters);
            }

            throw new ArgumentException(string.Format("No Factory defined for type {0}", textReaderType));
        }

        public TextWriter GetTextWriter(TextWriterType textWriterType, TextWriterParameters textReaderParameters)
        {
            LoadTextWriterFactories();

            if (_textWriterFactoriesHash.ContainsKey(textWriterType))
            {
                return _textWriterFactoriesHash[textWriterType].Create(textReaderParameters);
            }

            throw new ArgumentException(string.Format("No Factory defined for type {0}", textWriterType));
        }

        private void LoadStreamFactories()
        {
            if(!_streamFactoriesHashLoaded)
            {
                lock(_streamFactoriesHashLock)
                {
                    if(!_streamFactoriesHashLoaded)
                    {
                        var streamFactoriesHash = new Dictionary<StreamType, IStreamFactory>();
                        foreach (var streamFactory in _streamFactories)
                        {
                            if(!streamFactoriesHash.ContainsKey(streamFactory.StreamType))
                            {
                                streamFactoriesHash.Add(streamFactory.StreamType, streamFactory);
                            }
                        }
                        _streamFactoriesHash = streamFactoriesHash;
                        Thread.MemoryBarrier();
                        _streamFactoriesHashLoaded = true;
                    }
                }
            }
        }

        private void LoadTextReaderFactories()
        {
            if (!_textReaderFactoriesHashLoaded)
            {
                lock (_textReaderFactoriesHashLock)
                {
                    if (!_textReaderFactoriesHashLoaded)
                    {
                        var textReaderFactoriesHash = new Dictionary<TextReaderType, ITextReaderFactory>();
                        foreach (var textReaderFactory in _textReaderFactories)
                        {
                            if (!textReaderFactoriesHash.ContainsKey(textReaderFactory.TextReaderType))
                            {
                                textReaderFactoriesHash.Add(textReaderFactory.TextReaderType, textReaderFactory);
                            }
                        }
                        _textReaderFactoriesHash = textReaderFactoriesHash;
                        Thread.MemoryBarrier();
                        _textReaderFactoriesHashLoaded = true;
                    }
                }
            }
        }

        private void LoadTextWriterFactories()
        {
            if (!_textWriterFactoriesHashLoaded)
            {
                lock (_textWriterFactoriesHashLock)
                {
                    if (!_textWriterFactoriesHashLoaded)
                    {
                        var textWriterFactoriesHash = new Dictionary<TextWriterType, ITextWriterFactory>();
                        foreach (var textWriterFactory in _textWriterFactories)
                        {
                            if (!textWriterFactoriesHash.ContainsKey(textWriterFactory.TextWriterType))
                            {
                                textWriterFactoriesHash.Add(textWriterFactory.TextWriterType, textWriterFactory);
                            }
                        }
                        _textWriterFactoriesHash = textWriterFactoriesHash;
                        Thread.MemoryBarrier();
                        _textWriterFactoriesHashLoaded = true;
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: pd -send "hostname symbol $HOSTNAME" ${0%/*}/Pd/laser-driver.pd


text:
@interface ARFollowArtistFeedItem : ARFeedItem <UIActivityItemSource>

@property (nonatomic, copy, readonly) NSArray *artworks;
@property (nonatomic, readonly) Artist *artist;
@property (nonatomic, readonly) Profile *profile;

@end


text:
package kawa.standard;

import gnu.text.Char;
import gnu.lists.*;
import gnu.mapping.Procedure0or1;
import gnu.mapping.WrongType;
import gnu.mapping.InPort;
import gnu.text.LineBufferedReader;
import java.io.Reader;
import java.io.InputStream;

public class readchar extends Procedure0or1
{
    public static final readchar readChar = new readchar(false);
    public static final readchar peekChar = new readchar(true);

    boolean peeking;

    public readchar(boolean peeking) {
        super(peeking ? "peek-char" : "read-char");
        this.peeking = peeking;
    }

    final Object readChar(Reader port) {
        try {
            int ch;
            if (peeking)
                ch = LineBufferedReader.peekCodePoint(port);
            else
                ch = LineBufferedReader.readCodePoint(port);
            return ch < 0 ? Sequence.eofValue : Char.make(ch);
        } catch (java.io.IOException e) {
            throw new RuntimeException ("IO Exception caught");
        }
    }

    public static int readByte(InputStream port, boolean peeking) {
        try {
            int ch;
            if (peeking) {
                port.mark(1);
                ch = port.read();
                port.reset();
            } else
                ch = port.read();
            return ch;
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }

    final Object readChar(InputStream port) {
        int ch = readByte(port, peeking);
        if (ch < 0)
            return Sequence.eofValue;
	return Char.make(ch);
    }

    public final Object apply0() {
        return readChar (InPort.inDefault());
    }

    public final Object apply1(Object arg1) {
        if (arg1 instanceof Reader)
            return readChar((Reader) arg1);
        if (arg1 instanceof InputStream)
            return readChar ((InputStream) arg1);
        throw new WrongType (this, 1, arg1, "input-port");
    }
}


text:
use std::path::Path;
use std::fs::{remove_dir_all, remove_file, symlink_metadata};
use std::collections::HashMap;

use crate::build_step::BuildStep;
use crate::builder::context::Context;
use crate::builder::distrib::{Unknown,Distribution};
use crate::builder::error::{Error};
use crate::builder::commands::{composer, gem, npm, pip, dirs};
use crate::builder::packages;
use crate::container::mount::{
    unmount, mount_system_dirs, mount_proc, mount_run, unmount_system_dirs,
};
use crate::container::util::{clean_dir, write_container_signature};
use crate::file_util::{Dir, copy, truncate_file};
use crate::path_util::IterSelfAndParents;

pub struct Guard<'a> {
    pub ctx: Context<'a>,
    pub distro: Box<dyn Distribution>,
}

impl<'a> Guard<'a> {
    pub fn build(ctx: Context) -> Result<(), Error> {
        Guard {
            ctx: ctx,
            distro: Box::new(Unknown),
        }.run_process()
    }

    fn run_process(&mut self) -> Result<(), Error> {
        self.start()?;

        for b in self.ctx.container_config.setup.iter() {
            debug!("Building step: {:?}", b);
            self.ctx.timelog.mark(format_args!("Step: {:?}", b))
                .map_err(|e| format!("Can't write timelog: {}", e))?;
            b.build(self, true)
                .map_err(|e| Error::Step(b.0.clone(), e))?;
        }

        self.finish()?;
        Ok(())
    }

    pub fn start(&mut self) -> Result<(), String> {
        mount_system_dirs()?;
        mount_run(&Path::new("/vagga/root/run"))?;
        mount_proc(&Path::new("/proc"))?;
        copy("/proc/self/uid_map", "/vagga/container/uid_map")
            .map_err(|e| format!("Error copying uid_map: {}", e))?;
        copy("/proc/self/gid_map", "/vagga/container/gid_map")
            .map_err(|e| format!("Error copying gid_map: {}", e))?;
        try_msg!(Dir::new("/vagga/root/etc").create(),
             "Error creating /etc dir: {err}");
        copy("/etc/resolv.conf", "/vagga/root/etc/resolv.conf")
            .map_err(|e| format!("Error copying /etc/resolv.conf: {}", e))?;
        copy("/etc/hosts", "/vagga/root/etc/hosts")
            .map_err(|e| format!("Error copying /etc/hosts: {}", e))?;
        self.ctx.timelog.mark(format_args!("Prepare"))
            .map_err(|e| format!("Can't write timelog: {}", e))?;
        Ok(())
    }

    pub fn finish(&mut self) -> Result<(), String> {
        // Pip
        if self.ctx.featured_packages.contains(&packages::PipPy2) ||
           self.ctx.featured_packages.contains(&packages::PipPy3)
        {
            pip::freeze(&mut self.ctx)?;
        }
        // Npm
        if self.ctx.featured_packages.contains(&packages::Npm) {
            npm::list(&mut self.ctx)?;
        }
        // Composer
        if self.ctx.featured_packages.contains(&packages::Composer) {
            composer::finish(&mut self.ctx)?;
        }
        // Gem
        if self.ctx.featured_packages.contains(&packages::Bundler) {
            gem::list(&mut self.ctx)?;
        }

        self.distro.finish(&mut self.ctx)?;

        let base = Path::new("/vagga/root");

        for path in self.ctx.mounted.iter().rev() {
            unmount(path)?;
        }
        unmount(&Path::new("/vagga/root/run"))?;
        unmount_system_dirs()?;

        if Path::new("/vagga/container/cache").exists() {
            try_msg!(
                remove_dir_all("/vagga/container/cache"),
                "Error when removing containers cache directory: {err}"
            );
        }

        // Truncate resolv.conf and hosts files
        truncate_file("/vagga/root/etc/resolv.conf")?;
        if let Some(ref resolv_path) =
            self.ctx.container_config.resolv_conf_path
        {
            if resolv_path != Path::new("/etc/resolv.conf") {
                truncate_file(
                    &base.join(resolv_path.strip_prefix("/").unwrap()))?;
            }
        }
        truncate_file("/vagga/root/etc/hosts")?;
        if let Some(ref hosts_path) =
            self.ctx.container_config.hosts_file_path
        {
            if hosts_path != Path::new("/etc/hosts") {
                truncate_file(
                    &base.join(hosts_path.strip_prefix("/").unwrap()))?;
            }
        }

        for path in self.ctx.remove_paths.iter() {
            try_msg!(dirs::remove(&Path::new("/").join(path)),
                "Error removing path: {err}");
        }

        for dir in self.ctx.empty_dirs.iter() {
            clean_dir(&base.join(dir), false)?;
        }

        for dir in self.ctx.ensure_dirs.iter() {
            try_msg!(dirs::ensure(&Path::new("/").join(dir)),
                "Error creating dir: {err}");
        }

        if self.ctx.container_config.is_data_container() {
            let root = Path::new("/vagga/root");
            let exclude_paths = self.ctx.container_config.data_dirs.iter()
                // We validate exclude paths as absolute
                .map(|p| p.strip_prefix("/").unwrap())
                .collect::<Vec<_>>();
            let mut keep_rel_paths = HashMap::new();
            for exclude_path in &exclude_paths {
                for p in exclude_path
                    .iter_self_and_parents().skip(1)
                {
                    if let Some(&true) = keep_rel_paths.get(p) {
                        warn_duplicate_data_dir(p, true);
                    }
                    if !keep_rel_paths.contains_key(p) {
                        keep_rel_paths.insert(p, false);
                    }
                }
                if let Some(&is_final) = keep_rel_paths.get(exclude_path) {
                    warn_duplicate_data_dir(exclude_path, is_final);
                }
                // true means final path
                // so we merely keep this directory
                // and do not process its subdirs
                keep_rel_paths.insert(exclude_path, true);
            }
            try_msg!(remove_all_except(root, &keep_rel_paths),
                "Error removing dirs: {err}");
        }

        if self.ctx.settings.index_all_images {
            self.ctx.timelog.mark(format_args!("Indexing"))
                .map_err(|e| format!("Can't write timelog: {}", e))?;
            warn!("Indexing container...");
            write_container_signature(Path::new("/vagga/container"))?;
        }

        self.ctx.timelog.mark(format_args!("Finish"))
            .map_err(|e| format!("Can't write timelog: {}", e))?;

        return Ok(());
    }
}

fn remove_all_except(root: &Path, keep_rel_paths: &HashMap<&Path, bool>)
    -> Result<(), String>
{
    let entries = try_msg!(root.read_dir(),
        "Can't read dir {dir:?}: {err}", dir=root);
    for entry in entries {
        let ref path = try_msg!(entry,
                "Can't iterate over dir entries {dir:?}: {err}",
                dir=root)
            .path();
        let ref rel_path = path.strip_prefix("/vagga/root").unwrap();
        match keep_rel_paths.get(rel_path) {
            Some(&is_final) if is_final => {
                continue;
            },
            Some(_) => {
                remove_all_except(path, keep_rel_paths)?;
            },
            None => {
                let file_type = try_msg!(
                    symlink_metadata(path),
                    "Error querying file metadata: {path:?}: {err}", path=path
                ).file_type();
                if file_type.is_dir() {
                    try_msg!(clean_dir(path, true),
                        "Error cleaning dir {path:?}: {err}",
                        path=path);
                } else {
                    try_msg!(remove_file(path),
                        "Error removing file {path:?}: {err}",
                        path=path);
                }
            },
        }
    }
    Ok(())
}

fn warn_duplicate_data_dir(rel_path: &Path, is_final: bool) {
    let path = Path::new("/").join(rel_path);
    if is_final {
        warn!("{:?} is already contained as data directory", path);
    } else {
        warn!("{:?} is a prefix of other directory", path);
    }
}


text:
from setuptools import setup

setup(name='pdownload',
      version='0.3.0',
      description='Parallel file downloader',
      author='Ben Harris',
      author_email='benharris247@gmail.com',
      license='Apache',
      packages=['pdownload'],
      entry_points={
          'console_scripts': [
              'pdownload = pdownload.pdownload:main'
          ]
      },
      zip_safe=False,
      install_requires=[
          'requests',
          'tqdm'
      ])


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="robots" content="index, follow, all" />
    <title>Devise\Support\DeviseException | Devise</title>

            <link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="../../css/sami.css">

                <form id="search-form" action="../../search.html" method="GET">

            <input name="search"
                   class="typeahead form-control"
                   type="search"
                   placeholder="Search">
        </form>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements">
                    Toggle navigation

                </button>
                Devise

Classes

Namespaces

Interfaces

Traits

Index

Search

class

Devise

Support

DeviseException

DeviseException

    class
    DeviseException        extends Exception

Class DeviseException should be the base class exception
for any exception thrown inside of Devise. This way we can
catch those specifically if we want and know that they are
different from just regular exceptions.

Methods

                    static DeviseException

                    getFacadeRoot()

Pretends to be a Facade for Exception

Details

at line 18

                static            DeviseException
    getFacadeRoot()

Pretends to be a Facade for Exception

Return Value

            DeviseException

        Generated by Sami, the API Documentation Generator.


text:
"""Miscellaneous utility functions."""
import os
import sys
import re
import shutil
import fnmatch
from collections import defaultdict

MAX_FILENAME_LENGTH = 200

def normpath(path):
    """Provide the canonical form of the path suitable for storing in
    the database.
    """
    return os.path.normpath(os.path.abspath(os.path.expanduser(path)))

def ancestry(path, pathmod=None):
    """Return a list consisting of path's parent directory, its
    grandparent, and so on. For instance:
       >>> ancestry('/a/b/c')
       ['/', '/a', '/a/b']
    """
    pathmod = pathmod or os.path
    out = []
    last_path = None
    while path:
        path = pathmod.dirname(path)

        if path == last_path:
            break
        last_path = path

        if path: # don't yield ''
            out.insert(0, path)
    return out

def sorted_walk(path, ignore=()):
    """Like ``os.walk``, but yields things in sorted, breadth-first
    order.  Directory and file names matching any glob pattern in
    ``ignore`` are skipped.
    """
    # Make sure the path isn't a Unicode string.
    path = bytestring_path(path)

    # Get all the directories and files at this level.
    dirs = []
    files = []
    for base in os.listdir(path):
        # Skip ignored filenames.
        skip = False
        for pat in ignore:
            if fnmatch.fnmatch(base, pat):
                skip = True
                break
        if skip:
            continue

        # Add to output as either a file or a directory.
        cur = os.path.join(path, base)
        if os.path.isdir(syspath(cur)):
            dirs.append(base)
        else:
            files.append(base)

    # Sort lists and yield the current level.
    dirs.sort()
    files.sort()
    yield (path, dirs, files)

    # Recurse into directories.
    for base in dirs:
        cur = os.path.join(path, base)
        # yield from _sorted_walk(cur)
        for res in sorted_walk(cur, ignore):
            yield res

def mkdirall(path):
    """Make all the enclosing directories of path (like mkdir -p on the
    parent).
    """
    for ancestor in ancestry(path):
        if not os.path.isdir(syspath(ancestor)):
            os.mkdir(syspath(ancestor))

def prune_dirs(path, root, clutter=('.DS_Store', 'Thumbs.db')):
    """If path is an empty directory, then remove it. Recursively
    remove path's ancestry up to root (which is never removed) where
    there are empty directories. If path is not contained in root, then
    nothing is removed. Filenames in clutter are ignored when
    determining emptiness.
    """
    path = normpath(path)
    root = normpath(root)

    ancestors = ancestry(path)
    if root in ancestors:
        # Only remove directories below the root.
        ancestors = ancestors[ancestors.index(root)+1:]

        # Traverse upward from path.
        ancestors.append(path)
        ancestors.reverse()
        for directory in ancestors:
            directory = syspath(directory)
            if not os.path.exists(directory):
                # Directory gone already.
                continue

            if all(fn in clutter for fn in os.listdir(directory)):
                # Directory contains only clutter (or nothing).
                try:
                    shutil.rmtree(directory)
                except OSError:
                    break
            else:
                break

def components(path, pathmod=None):
    """Return a list of the path components in path. For instance:
       >>> components('/a/b/c')
       ['a', 'b', 'c']
    """
    pathmod = pathmod or os.path
    comps = []
    ances = ancestry(path, pathmod)
    for anc in ances:
        comp = pathmod.basename(anc)
        if comp:
            comps.append(comp)
        else: # root
            comps.append(anc)

    last = pathmod.basename(path)
    if last:
        comps.append(last)

    return comps

def bytestring_path(path):
    """Given a path, which is either a str or a unicode, returns a str
    path (ensuring that we never deal with Unicode pathnames).
    """
    # Pass through bytestrings.
    if isinstance(path, str):
        return path

    # Try to encode with default encodings, but fall back to UTF8.
    encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    try:
        return path.encode(encoding)
    except (UnicodeError, LookupError):
        return path.encode('utf8')

def displayable_path(path):
    """Attempts to decode a bytestring path to a unicode object for the
    purpose of displaying it to the user.
    """
    if isinstance(path, unicode):
        return path

    encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    try:
        return path.decode(encoding, 'ignore')
    except (UnicodeError, LookupError):
        return path.decode('utf8', 'ignore')

def syspath(path, pathmod=None):
    """Convert a path for use by the operating system. In particular,
    paths on Windows must receive a magic prefix and must be converted
    to unicode before they are sent to the OS.
    """
    pathmod = pathmod or os.path
    windows = pathmod.__name__ == 'ntpath'

    # Don't do anything if we're not on windows
    if not windows:
        return path

    if not isinstance(path, unicode):
        # Try to decode with default encodings, but fall back to UTF8.
        encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
        try:
            path = path.decode(encoding, 'replace')
        except UnicodeError:
            path = path.decode('utf8', 'replace')

    # Add the magic prefix if it isn't already there
    if not path.startswith(u'\\\\?\\'):
        path = u'\\\\?\\' + path

    return path

def samefile(p1, p2):
    """Safer equality for paths."""
    return shutil._samefile(syspath(p1), syspath(p2))

def soft_remove(path):
    """Remove the file if it exists."""
    path = syspath(path)
    if os.path.exists(path):
        os.remove(path)

def _assert_not_exists(path, pathmod=None):
    """Raises an OSError if the path exists."""
    pathmod = pathmod or os.path
    if pathmod.exists(path):
        pass
        #raise OSError('file exists: %s' % path)

def copy(path, dest, replace=False, pathmod=None):
    """Copy a plain file. Permissions are not copied. If dest already
    exists, raises an OSError unless replace is True. Has no effect if
    path is the same as dest. Paths are translated to system paths
    before the syscall.
    """
    if samefile(path, dest):
        return
    path = syspath(path)
    dest = syspath(dest)
    _assert_not_exists(dest, pathmod)
    return shutil.copyfile(path, dest)

def move(path, dest, replace=False, pathmod=None):
    """Rename a file. dest may not be a directory. If dest already
    exists, raises an OSError unless replace is True. Hos no effect if
    path is the same as dest. Paths are translated to system paths.
    """
    if samefile(path, dest):
        return
    path = syspath(path)
    dest = syspath(dest)
    _assert_not_exists(dest, pathmod)
    return shutil.move(path, dest)

def unique_path(path):
    """Returns a version of ``path`` that does not exist on the
    filesystem. Specifically, if ``path` itself already exists, then
    something unique is appended to the path.
    """
    if not os.path.exists(syspath(path)):
        return path

    base, ext = os.path.splitext(path)
    match = re.search(r'\.(\d)+$', base)
    if match:
        num = int(match.group(1))
        base = base[:match.start()]
    else:
        num = 0
    while True:
        num += 1
        new_path = '%s.%i%s' % (base, num, ext)
        if not os.path.exists(new_path):
            return new_path

# Note: POSIX actually supports \ and : -- I just think they're
# a pain. And ? has caused problems for some.
CHAR_REPLACE = [
    (re.compile(r'[\\/\?"]|^\.'), '_'),
    (re.compile(r':'), '-'),
]
CHAR_REPLACE_WINDOWS = [
    (re.compile(r'["\*<>\|]|^\.|\.$|\s+$'), '_'),
]
def sanitize_path(path, pathmod=None, replacements=None):
    """Takes a path and makes sure that it is legal. Returns a new path.
    Only works with fragments; won't work reliably on Windows when a
    path begins with a drive letter. Path separators (including altsep!)
    should already be cleaned from the path components. If replacements
    is specified, it is used *instead* of the default set of
    replacements for the platform; it must be a list of (compiled regex,
    replacement string) pairs.
    """
    pathmod = pathmod or os.path
    windows = pathmod.__name__ == 'ntpath'

    # Choose the appropriate replacements.
    if not replacements:
        replacements = list(CHAR_REPLACE)
        if windows:
            replacements += CHAR_REPLACE_WINDOWS

    comps = components(path, pathmod)
    if not comps:
        return ''
    for i, comp in enumerate(comps):
        # Replace special characters.
        for regex, repl in replacements:
            comp = regex.sub(repl, comp)

        # Truncate each component.
        comp = comp[:MAX_FILENAME_LENGTH]

        comps[i] = comp
    return pathmod.join(*comps)

def sanitize_for_path(value, pathmod, key=None):
    """Sanitize the value for inclusion in a path: replace separators
    with _, etc. Doesn't guarantee that the whole path will be valid;
    you should still call sanitize_path on the complete path.
    """
    if isinstance(value, basestring):
        for sep in (pathmod.sep, pathmod.altsep):
            if sep:
                value = value.replace(sep, u'_')
    elif key in ('track', 'tracktotal', 'disc', 'disctotal'):
        # Pad indices with zeros.
        value = u'%02i' % value
    elif key == 'year':
        value = u'%04i' % value
    elif key in ('month', 'day'):
        value = u'%02i' % value
    elif key == 'bitrate':
        # Bitrate gets formatted as kbps.
        value = u'%ikbps' % (value / 1000)
    else:
        value = unicode(value)
    return value

def str2bool(value):
    """Returns a boolean reflecting a human-entered string."""
    if value.lower() in ('yes', '1', 'true', 't', 'y'):
        return True
    else:
        return False

def levenshtein(s1, s2):
    """A nice DP edit distance implementation from Wikibooks:
    http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/
    Levenshtein_distance#Python
    """
    if len(s1) < len(s2):
        return levenshtein(s2, s1)
    if not s1:
        return len(s2)

    previous_row = xrange(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1
            deletions = current_row[j] + 1
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row

    return previous_row[-1]

def plurality(objs):
    """Given a sequence of comparable objects, returns the object that
    is most common in the set and the frequency of that object. The
    sequence must contain at least one object.
    """
    # Calculate frequencies.
    freqs = defaultdict(int)
    for obj in objs:
        freqs[obj] += 1

    if not freqs:
        raise ValueError('sequence must be non-empty')

    # Find object with maximum frequency.
    max_freq = 0
    res = None
    for obj, freq in freqs.items():
        if freq > max_freq:
            max_freq = freq
            res = obj

    return res, max_freq


text:
<?php

namespace BearFramework\App;

use BearFramework\App;

/**
 * Provides information about the current request
 * @property string $scheme The request scheme
 * @property string $host The request hostname
 */
class Request
{

    /**
     * The request method
     * @var string
     */
    public $method = '';

    /**
     * The base URL of the request
     * @var string
     */
    public $base = '';

    /**
     * The path of the request. The path parts can be accessed by their indexes.
     * @var \BearFramework\App\Request\Path
     */
    public $path = null;

    /**
     * The query string of the request. The query parts can be accessed by their names.
     * @var \BearFramework\App\Request\Query
     */
    public $query = null;

    /**
     * The constructor
     */
    public function __construct()
    {
        $this->path = new App\Request\Path();
        $this->query = new App\Request\Query();
    }

    /**
     * Returns the full URL of the request
     * @return string The full URL of the request
     */
    public function __toString()
    {
        return $this->base . (string) $this->path;
    }

    /**
     * Magic method
     * @param string $name
     * @return mixed
     * @throws \Exception
     */
    public function __get($name)
    {
        if ($name === 'scheme' || $name === 'host') {
            $data = parse_url($this->base);
            return isset($data[$name]) ? $data[$name] : null;
        }
        throw new \Exception('Undefined property: ' . $name);
    }

    /**
     * Magic method
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value)
    {
        if ($name === 'scheme' || $name === 'host') {
            $data = parse_url($this->base);
            $this->base = ($name === 'scheme' ? $value : (isset($data['scheme']) ? $data['scheme'] : '')) . '://' . ($name === 'host' ? $value : (isset($data['host']) ? $data['host'] : '')) . (isset($data['path']) ? $data['path'] : '');
        }
    }

    /**
     * Magic method
     * @param string $name
     * @return boolean
     */
    public function __isset($name)
    {
        return $name === 'scheme' || $name === 'host';
    }

}


text:
"""
Petrophysically guided inversion: Joint linear example with nonlinear relationships
===================================================================================

We do a comparison between the classic least-squares inversion
and our formulation of a petrophysically guided inversion.
We explore it through coupling two linear problems whose respective physical
properties are linked by polynomial relationships that change between rock units.

"""

import discretize as Mesh
import matplotlib.pyplot as plt
import numpy as np
from SimPEG import (
    data_misfit,
    directives,
    inverse_problem,
    inversion,
    maps,
    optimization,
    regularization,
    simulation,
    utils,
)

# Random seed for reproductibility
np.random.seed(1)
# Mesh
N = 100
mesh = Mesh.TensorMesh([N])

# Survey design parameters
nk = 30
jk = np.linspace(1.0, 59.0, nk)
p = -0.25
q = 0.25

# Physics
def g(k):
    return np.exp(p * jk[k] * mesh.cell_centers_x) * np.cos(
        np.pi * q * jk[k] * mesh.cell_centers_x
    )

G = np.empty((nk, mesh.nC))

for i in range(nk):
    G[i, :] = g(i)

m0 = np.zeros(mesh.nC)
m0[20:41] = np.linspace(0.0, 1.0, 21)
m0[41:57] = np.linspace(-1, 0.0, 16)

poly0 = maps.PolynomialPetroClusterMap(coeffyx=np.r_[0.0, -4.0, 4.0])
poly1 = maps.PolynomialPetroClusterMap(coeffyx=np.r_[-0.0, 3.0, 6.0, 6.0])
poly0_inverse = maps.PolynomialPetroClusterMap(coeffyx=-np.r_[0.0, -4.0, 4.0])
poly1_inverse = maps.PolynomialPetroClusterMap(coeffyx=-np.r_[0.0, 3.0, 6.0, 6.0])
cluster_mapping = [maps.IdentityMap(), poly0_inverse, poly1_inverse]

m1 = np.zeros(100)
m1[20:41] = 1.0 + (poly0 * np.vstack([m0[20:41], m1[20:41]]).T)[:, 1]
m1[41:57] = -1.0 + (poly1 * np.vstack([m0[41:57], m1[41:57]]).T)[:, 1]

model2d = np.vstack([m0, m1]).T
m = utils.mkvc(model2d)

clfmapping = utils.GaussianMixtureWithNonlinearRelationships(
    mesh=mesh,
    n_components=3,
    covariance_type="full",
    tol=1e-8,
    reg_covar=1e-3,
    max_iter=1000,
    n_init=100,
    init_params="kmeans",
    random_state=None,
    warm_start=False,
    means_init=np.array(
        [
            [0, 0],
            [m0[20:41].mean(), m1[20:41].mean()],
            [m0[41:57].mean(), m1[41:57].mean()],
        ]
    ),
    verbose=0,
    verbose_interval=10,
    cluster_mapping=cluster_mapping,
)
clfmapping = clfmapping.fit(model2d)

clfnomapping = utils.WeightedGaussianMixture(
    mesh=mesh,
    n_components=3,
    covariance_type="full",
    tol=1e-8,
    reg_covar=1e-3,
    max_iter=1000,
    n_init=100,
    init_params="kmeans",
    random_state=None,
    warm_start=False,
    verbose=0,
    verbose_interval=10,
)
clfnomapping = clfnomapping.fit(model2d)

wires = maps.Wires(("m1", mesh.nC), ("m2", mesh.nC))

relatrive_error = 0.01
noise_floor = 0.0

prob1 = simulation.LinearSimulation(mesh, G=G, model_map=wires.m1)
survey1 = prob1.make_synthetic_data(
    m, relative_error=relatrive_error, noise_floor=noise_floor, add_noise=True
)

prob2 = simulation.LinearSimulation(mesh, G=G, model_map=wires.m2)
survey2 = prob2.make_synthetic_data(
    m, relative_error=relatrive_error, noise_floor=noise_floor, add_noise=True
)

dmis1 = data_misfit.L2DataMisfit(simulation=prob1, data=survey1)
dmis2 = data_misfit.L2DataMisfit(simulation=prob2, data=survey2)
dmis = dmis1 + dmis2
minit = np.zeros_like(m)

# Distance weighting
wr1 = np.sum(prob1.G ** 2.0, axis=0) ** 0.5 / mesh.cell_volumes
wr1 = wr1 / np.max(wr1)
wr2 = np.sum(prob2.G ** 2.0, axis=0) ** 0.5 / mesh.cell_volumes
wr2 = wr2 / np.max(wr2)

reg_simple = regularization.PGI(
    mesh=mesh,
    gmmref=clfmapping,
    gmm=clfmapping,
    approx_gradient=True,
    wiresmap=wires,
    non_linear_relationships=True,
    weights_list=[wr1, wr2],
)

opt = optimization.ProjectedGNCG(
    maxIter=50,
    tolX=1e-6,
    maxIterCG=100,
    tolCG=1e-3,
    lower=-10,
    upper=10,
)

invProb = inverse_problem.BaseInvProblem(dmis, reg_simple, opt)

# directives
scales = directives.ScalingMultipleDataMisfits_ByEig(
    chi0_ratio=np.r_[1.0, 1.0], verbose=True, n_pw_iter=10
)
scaling_schedule = directives.JointScalingSchedule(verbose=True)
alpha0_ratio = np.r_[1e6, 1e4, 1, 1]
alphas = directives.AlphasSmoothEstimate_ByEig(
    alpha0_ratio=alpha0_ratio, n_pw_iter=10, verbose=True
)
beta = directives.BetaEstimate_ByEig(beta0_ratio=1e-5, n_pw_iter=10)
betaIt = directives.PGI_BetaAlphaSchedule(
    verbose=True,
    coolingFactor=2.0,
    progress=0.2,
)
targets = directives.MultiTargetMisfits(verbose=True)
petrodir = directives.PGI_UpdateParameters(update_gmm=False)

# Setup Inversion
inv = inversion.BaseInversion(
    invProb,
    directiveList=[alphas, scales, beta, petrodir, targets, betaIt, scaling_schedule],
)

mcluster_map = inv.run(minit)

# Inversion with no nonlinear mapping
reg_simple_no_map = regularization.PGI(
    mesh=mesh,
    gmmref=clfnomapping,
    gmm=clfnomapping,
    approx_gradient=True,
    wiresmap=wires,
    non_linear_relationships=False,
    weights_list=[wr1, wr2],
)

opt = optimization.ProjectedGNCG(
    maxIter=50,
    tolX=1e-6,
    maxIterCG=100,
    tolCG=1e-3,
    lower=-10,
    upper=10,
)

invProb = inverse_problem.BaseInvProblem(dmis, reg_simple_no_map, opt)

# directives
scales = directives.ScalingMultipleDataMisfits_ByEig(
    chi0_ratio=np.r_[1.0, 1.0], verbose=True, n_pw_iter=10
)
scaling_schedule = directives.JointScalingSchedule(verbose=True)
alpha0_ratio = np.r_[100.0 * np.ones(2), 1, 1]
alphas = directives.AlphasSmoothEstimate_ByEig(
    alpha0_ratio=alpha0_ratio, n_pw_iter=10, verbose=True
)
beta = directives.BetaEstimate_ByEig(beta0_ratio=1e-5, n_pw_iter=10)
betaIt = directives.PGI_BetaAlphaSchedule(
    verbose=True,
    coolingFactor=2.0,
    progress=0.2,
)
targets = directives.MultiTargetMisfits(
    chiSmall=1.0, TriggerSmall=True, TriggerTheta=False, verbose=True
)
petrodir = directives.PGI_UpdateParameters(update_gmm=False)

# Setup Inversion
inv = inversion.BaseInversion(
    invProb,
    directiveList=[alphas, scales, beta, petrodir, targets, betaIt, scaling_schedule],
)

mcluster_no_map = inv.run(minit)

# WeightedLeastSquares Inversion

reg1 = regularization.WeightedLeastSquares(
    mesh, alpha_s=1.0, alpha_x=1.0, mapping=wires.m1
)
reg1.cell_weights = wr1
reg2 = regularization.WeightedLeastSquares(
    mesh, alpha_s=1.0, alpha_x=1.0, mapping=wires.m2
)
reg2.cell_weights = wr2
reg = reg1 + reg2

opt = optimization.ProjectedGNCG(
    maxIter=50,
    tolX=1e-6,
    maxIterCG=100,
    tolCG=1e-3,
    lower=-10,
    upper=10,
)

invProb = inverse_problem.BaseInvProblem(dmis, reg, opt)

# directives
alpha0_ratio = np.r_[1, 1, 1, 1]
alphas = directives.AlphasSmoothEstimate_ByEig(
    alpha0_ratio=alpha0_ratio, n_pw_iter=10, verbose=True
)
scales = directives.ScalingMultipleDataMisfits_ByEig(
    chi0_ratio=np.r_[1.0, 1.0], verbose=True, n_pw_iter=10
)
scaling_schedule = directives.JointScalingSchedule(verbose=True)
beta = directives.BetaEstimate_ByEig(beta0_ratio=1e-5, n_pw_iter=10)
beta_schedule = directives.BetaSchedule(coolingFactor=5.0, coolingRate=1)
targets = directives.MultiTargetMisfits(
    TriggerSmall=False,
    verbose=True,
)

# Setup Inversion
inv = inversion.BaseInversion(
    invProb,
    directiveList=[alphas, scales, beta, targets, beta_schedule, scaling_schedule],
)

mtik = inv.run(minit)

# Final Plot
fig, axes = plt.subplots(3, 4, figsize=(25, 15))
axes = axes.reshape(12)
left, width = 0.25, 0.5
bottom, height = 0.25, 0.5
right = left + width
top = bottom + height

axes[0].set_axis_off()
axes[0].text(
    0.5 * (left + right),
    0.5 * (bottom + top),
    ("Using true nonlinear\npetrophysical relationships"),
    horizontalalignment="center",
    verticalalignment="center",
    fontsize=20,
    color="black",
    transform=axes[0].transAxes,
)

axes[1].plot(mesh.cell_centers_x, wires.m1 * mcluster_map, "b.-", ms=5, marker="v")
axes[1].plot(mesh.cell_centers_x, wires.m1 * m, "k--")
axes[1].set_title("Problem 1")
axes[1].legend(["Recovered Model", "True Model"], loc=1)
axes[1].set_xlabel("X")
axes[1].set_ylabel("Property 1")

axes[2].plot(mesh.cell_centers_x, wires.m2 * mcluster_map, "r.-", ms=5, marker="v")
axes[2].plot(mesh.cell_centers_x, wires.m2 * m, "k--")
axes[2].set_title("Problem 2")
axes[2].legend(["Recovered Model", "True Model"], loc=1)
axes[2].set_xlabel("X")
axes[2].set_ylabel("Property 2")

x, y = np.mgrid[-1:1:0.01, -4:2:0.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x
pos[:, :, 1] = y
CS = axes[3].contour(
    x,
    y,
    np.exp(clfmapping.score_samples(pos.reshape(-1, 2)).reshape(x.shape)),
    100,
    alpha=0.25,
    cmap="viridis",
)
axes[3].scatter(wires.m1 * mcluster_map, wires.m2 * mcluster_map, marker="v")
axes[3].set_title("Petrophysical Distribution")
CS.collections[0].set_label("")
axes[3].legend(["True Petrophysical Distribution", "Recovered model crossplot"])
axes[3].set_xlabel("Property 1")
axes[3].set_ylabel("Property 2")

axes[4].set_axis_off()
axes[4].text(
    0.5 * (left + right),
    0.5 * (bottom + top),
    ("Using a pure\nGaussian distribution"),
    horizontalalignment="center",
    verticalalignment="center",
    fontsize=20,
    color="black",
    transform=axes[4].transAxes,
)

axes[5].plot(mesh.cell_centers_x, wires.m1 * mcluster_no_map, "b.-", ms=5, marker="v")
axes[5].plot(mesh.cell_centers_x, wires.m1 * m, "k--")
axes[5].set_title("Problem 1")
axes[5].legend(["Recovered Model", "True Model"], loc=1)
axes[5].set_xlabel("X")
axes[5].set_ylabel("Property 1")

axes[6].plot(mesh.cell_centers_x, wires.m2 * mcluster_no_map, "r.-", ms=5, marker="v")
axes[6].plot(mesh.cell_centers_x, wires.m2 * m, "k--")
axes[6].set_title("Problem 2")
axes[6].legend(["Recovered Model", "True Model"], loc=1)
axes[6].set_xlabel("X")
axes[6].set_ylabel("Property 2")

CSF = axes[7].contour(
    x,
    y,
    np.exp(clfmapping.score_samples(pos.reshape(-1, 2)).reshape(x.shape)),
    100,
    alpha=0.5,
    label="True Petro. Distribution",
)
CS = axes[7].contour(
    x,
    y,
    np.exp(clfnomapping.score_samples(pos.reshape(-1, 2)).reshape(x.shape)),
    500,
    cmap="viridis",
    linestyles="--",
    label="Modeled Petro. Distribution",
)
axes[7].scatter(
    wires.m1 * mcluster_no_map,
    wires.m2 * mcluster_no_map,
    marker="v",
    label="Recovered model crossplot",
)
axes[7].set_title("Petrophysical Distribution")
axes[7].legend()
axes[7].set_xlabel("Property 1")
axes[7].set_ylabel("Property 2")

# Tikonov

axes[8].set_axis_off()
axes[8].text(
    0.5 * (left + right),
    0.5 * (bottom + top),
    ("Least-Squares\n~Using a single cluster"),
    horizontalalignment="center",
    verticalalignment="center",
    fontsize=20,
    color="black",
    transform=axes[8].transAxes,
)

axes[9].plot(mesh.cell_centers_x, wires.m1 * mtik, "b.-", ms=5, marker="v")
axes[9].plot(mesh.cell_centers_x, wires.m1 * m, "k--")
axes[9].set_title("Problem 1")
axes[9].legend(["Recovered Model", "True Model"], loc=1)
axes[9].set_xlabel("X")
axes[9].set_ylabel("Property 1")

axes[10].plot(mesh.cell_centers_x, wires.m2 * mtik, "r.-", ms=5, marker="v")
axes[10].plot(mesh.cell_centers_x, wires.m2 * m, "k--")
axes[10].set_title("Problem 2")
axes[10].legend(["Recovered Model", "True Model"], loc=1)
axes[10].set_xlabel("X")
axes[10].set_ylabel("Property 2")

CS = axes[11].contour(
    x,
    y,
    np.exp(clfmapping.score_samples(pos.reshape(-1, 2)).reshape(x.shape)),
    100,
    alpha=0.25,
    cmap="viridis",
)
axes[11].scatter(wires.m1 * mtik, wires.m2 * mtik, marker="v")
axes[11].set_title("Petro Distribution")
CS.collections[0].set_label("")
axes[11].legend(["True Petro Distribution", "Recovered model crossplot"])
axes[11].set_xlabel("Property 1")
axes[11].set_ylabel("Property 2")
plt.subplots_adjust(wspace=0.3, hspace=0.3, top=0.85)
plt.show()


text:
title: Affinity Photo (now) & Designer (soon) for iPad
date: 2017-06-07 16:05:00 +03:00
categories:
- design
- workflows
tags:
- design
- photo editing
- affinity photo
layout: post
---

![my studio apps](/images/studio-apps.png)
It didn't took me long, after I installed the Affinity Photo (by Serif Labs)  to realize that I can delete plenty of photo editing apps without regrets. This app puts (back) the Pro in my iPad Pro.

![my design apps, resources  and workflows. ](/images/designtag.png)
In the image bellow are my design resources (apps, software, workflows, etc), organized in 1password. On the left side are listed in the 'design' folder and on the right side, are listed by 'design' tag. As you can see, I tried many apps, but I must say that I am amazed by the power of this Affinity Photo.

 I can't wait to install Affinity Designer so I can free some precious space on my 128gb iPad Pro, removing many vectorial apps. Luckily,  Matt confirms on [twitter](https://twitter.com/mattp4478/status/872355604240764928) and  [Procreate Forums](https://forums.procreate.art/index.php?topic=5842.120) that Designer is "going to happen - and it's not far away from now".

Affinity Photo can be found [here](https://affinity.serif.com/en-gb/photo/ipad/). And I strongly recommend their [vimeo account](https://vimeo.com/macaffinity) for in depth video tutorials for the iPad version or [this resources](https://affinity.serif.com/forum/index.php?/topic/10119-official-affinity-photo-desktop-video-tutorials-200/) for the desktop version.

I expect that this fall my design workflow is about to be changed a lot. [Procreacte](http://procreate.art/) is preparing a 'very special release' (as they wrote in today's mini update), [Omnigraffle 3](https://www.omnigroup.com/omnigraffle/preview) is in beta (I am testing it) and Autodesk's '[Graphic](https://graphic.com/ipad/)' is also preparing a new serious update (I know from my sources). [Concepts](https://concepts.tophatch.com/) is constantly coming with new features but unfortunately,  one app I like very much for UX/UI and prototyping - [Protosketch](http://protosketch.io/) - is moving very slow... maybe too slow. I would probably say the same thing about [Grafio3](https://itunes.apple.com/us/app/grafio-3-diagrams-ideas/id382418196?mt=8).

![my iPad second screen](/images/designtab.png)


text: MEAN stack learning demonstration for better understanding


text:
angular.module('authService', [])
    // factory to login and get information
    .factory('Auth', function($http, $q, $location, $window, AuthToken) {
        var authFactory = {};

        authFactory.login = function(username, password) {
            return $http.post('/user/authenticate', {
                username: username,
                password: password
            }).success(function(data) {
                AuthToken.setToken(data.token);
                $window.location.reload();
                return data;
            });
        };

        authFactory.logout = function() {
            AuthToken.setToken();
            $window.location.reload();
        };

        authFactory.isLoggedIn = function() {
            if (AuthToken.getToken()) return true;
            else return false;
        };

        authFactory.getUser = function() {
            if (AuthToken.getToken()) {
                return $http.get('/user/me', {
                    cache: true
                });
            } else {
                return $q.reject({
                    message: 'User has no token.'
                });
            }
        };

        return authFactory;

    })
    //inject the token into the client
    .factory('AuthToken', function($window) {
        var authTokenFactory = {};

        authTokenFactory.getToken = function() {
            return $window.localStorage.getItem('token');
        };

        authTokenFactory.setToken = function(token) {
            if (token) $window.localStorage.setItem('token', token);
            else $window.localStorage.removeItem('token');
        };

        return authTokenFactory;
    })
    // integrate token into all requests
    .factory('AuthInterceptor', function($q, $location, AuthToken) {
        var interceptorFactory = {};

        interceptorFactory.request = function(config) {
            var token = AuthToken.getToken();
            if (token) config.headers['x-access-token'] = token;
            return config;
        };

        interceptorFactory.responseError = function(response) {
            if (response.status == 403) {
                AuthToken.setToken();
                $location.path('/login');
            }

            return $q.reject(response);
        };

        return interceptorFactory;
    });


text:
#define ___VERSION 407002
#include "gambit.h"

/*
 * Define SCHEME_LIBRARY_LINKER as the name of the Scheme library
 * prefixed with "____20_" and suffixed with "__".  This is the
 * function that initializes the Scheme library.
 */

#define SCHEME_LIBRARY_LINKER ____20_mylib__

___BEGIN_C_LINKAGE
extern ___mod_or_lnk SCHEME_LIBRARY_LINKER (___global_state);
___END_C_LINKAGE

void setup_gambit()
{
  /*
   * Setup the Scheme library by calling "___setup" with appropriate
   * parameters.  The call to "___setup_params_reset" sets all parameters
   * to their default setting.
   */

  ___setup_params_struct setup_params;

  ___setup_params_reset (&setup_params);

  setup_params.version = ___VERSION;
  setup_params.linker  = SCHEME_LIBRARY_LINKER;

  ___setup (&setup_params);
}

void cleanup_gambit()
{
	___cleanup();
}


text:
<?php
namespace CDGNG\Statistics;

class All extends Statistic
{
    protected function getData($calendar)
    {
        return $calendar->getData();
    }

    protected function getSlotName()
    {
        return('All');
    }

    public function exportAsCsv()
    {
        // Supprime la colonne Slot (inutile dans ce cas)
        $csv = parent::exportAsCsv();
        $csv->removeColumn(1);
        return $csv;
    }
}


text:
This is a simple Cordova app with an Intercom integration.

## Installing the Cordova CLI

To install Cordova, run the following from your command line:

```
npm install -g cordova
npm install -g ios-sim
```

## Configuration

Before you run your app, you'll need to add your Intercom **AppID** and **API Key** to `config.xml` for both Android and/or iOS.
```xml
<preference name="intercom-app-id" value="YOUR_APP_ID"/>
<preference name="intercom-ios-api-key" value="YOU_IOS_API_KEY"/>
<preference name="intercom-android-api-key" value="YOUR_ANDROID_API_KEY"/>
```

If you want to enable Android FCM push notifications copy your `google-services.json` file into the `Example/` folder add this line to `config.xml`:
```xml
<preference name="intercom-android-push-type" value="FCM"/>
```

## Running the app

To get started, add your platform(s) of choice:

```
cordova platform add ios
cordova platform add android
```

Now you can install the Intercom plugin:

```
cordova plugin add cordova-plugin-intercom
```
You can now run your app with the following command:
#### iOS
```
cordova run ios
```
### Android
```
cordova run android
```


text:
import { paths } from './function';

// cannot use import because @isomorphic
const _ = require('lodash');

const Tyr = require('../tyr').default;

/**
 * NOTE: This cannot be a ES6 class because it is isomorphic
 *
 * @isomorphic
 */
function Path(base, pathName, opts) {
  this.base = base;
  this.name = pathName;

  const skipArray = opts && opts.skipArray;

  if (base instanceof Path) base = base.tail;

  const path = (this.path = []);

  if (!pathName) pathName = '';
  let starti = 0,
    si = 0;
  let collectionName = undefined;
  for (; si < pathName.length; si++) {
    const ch = pathName[si];

    switch (ch) {
      case ':':
        if (path.length)
          throw new Error(
            `Collection name cannot have a "." in "${pathName}".`
          );

        if (collectionName)
          throw new Error(
            `Two collections being specified in "${pathName}", only one is allowed.`
          );

        collectionName = pathName.substring(starti, si);
        starti = si + 1;
        break;

      case '|':
        if (!this._groups) this._groups = [];
        this._groups.push(path.length + 1);
      // fall through

      case '.':
        path.push(pathName.substring(starti, si));
        starti = si + 1;
        break;
    }
  }

  if (starti < si) path.push(pathName.substring(starti));

  if (collectionName) {
    this.base = base = Tyr.byName[collectionName];
    this.collectionSpecified = true;

    if (!base)
      throw new Error(
        `Unknown collection "${collectionName}" in "${pathName}".`
      );

    if (base.isDb())
      throw new Error(
        `Collection "${collectionName}" in "${pathName}" is not an auxiliary or static collection.`
      );

    if (!base.def.singleton)
      throw new Error(
        `Collection "${collectionName}" in "${pathName}" is not a singleton.`
      );
  }

  const plen = path.length,
    pathFields = (this.fields = new Array(plen));

  let at = base;

  if (opts && opts.method) {
    at = base.def.service;
  }

  let pi = 0;
  //denormal;

  nextPath: while (pi < plen) {
    const name = path[pi];
    // DYNAMIC-FIELD-ROOT: if at is a custom field root, then def won't be defined
    let def = at.def ?? at;

    if (name === '_') {
      if (!at.of)
        throw new Error(`"${name}" in "${pathName}" is not an array or map.`);

      at = at.of;
      pathFields[pi++] = at;
      continue nextPath;
    }

    if (
      name.match(Path._numberRegex) &&
      pi &&
      pathFields[pi - 1].type.name === 'array'
    ) {
      at = at.of;
      pathFields[pi++] = at;
      continue nextPath;
    }

    if (!at.fields) {
      const aAt = Path._skipArray(at);

      const aAtFields = aAt?.fields;
      if (
        aAtFields &&
        (aAtFields[name] ||
          (/.+[$_]$/.test(name) &&
            aAtFields[name.substring(0, name.length - 1)]))
      ) {
        at = aAt;
        def = at.def;
      } else if (at.link) {
        at = at.link;
        def = at.def;
      } else {
        if (!def.keys) {
          throw new Error(
            `"${name}" in "${pathName}" is not valid` +
              (at.link ? '" (maybe need advanced population syntax)' : '')
          );
        }
      }
    }

    const f = at.fields;
    if ((!f || !f[name]) && def.keys) {
      at = at.of;
      pathFields[pi++] = at;
      continue nextPath;
    }

    const parentAt = at;
    at = f[name];
    if (!at && /.+[$_]$/.test(name)) {
      const _name = name.substring(0, name.length - 1);

      while (/* if */ _name) {
        const _at = parentAt.fields[_name];
        if (!_at) {
          throw new Error(`"${_name}" in "${pathName}" is not a valid field.`);
        }

        /*
        const denormalization = name.endsWith('_');

        // TODO:  this denormalization code does not deal with denormal entries like "a.b"
        //        so commenting it out for now, does more harm than good
        if (denormalization) {
          if (!denormal) {
            denormal = _at.def.denormal;
            if (!denormal) {
              break;
            }
          } else {
            //if (!denormal[_name]) {
            //break;
            //}
            //denormal = denormal[_name];
          }
        } else {
          denormal = null;
        }
        */

        at = _at;
        pathFields[pi++] = at;
        at = at.link;
        continue nextPath;
      }
    }

    if (skipArray && (pi + 1 >= plen || path[pi + 1] !== '_')) {
      at = Path._skipArray(at);
    }

    if (!at) {
      throw new Error(
        `Cannot find field "${this.pathName(pi)}" in path "${base.toString()}:${
          this.name
        }"`
      );
    }

    pathFields[pi++] = at;
  }
}

Path._numberRegex = /^[0-9]+$/;

Path._skipArray = function (field) {
  if (field && !field.type) {
    throw new Error('field missing type');
  }

  while (field && field.type.def.name === 'array') {
    field = field.of;
  }

  return field;
};

Path.prototype.metaType = 'path';

Path.prototype.parsePath = function (path, skipArray) {
  return new Path(this, path, { skipArray });
};

Path.decode = function (path) {
  return path.replace(/\|/g, '.');
};

Path.encode = function (path) {
  return path.replace(/\./g, '|');
};

/**
 * TODO:  make this a configurable Tyranid option as to how populated entries should be named
 *
 *    1. organizationId -> organization
 *    2. organization   -> organization$
 *    3. organization   -> organization
 *
 */
Path.populateNameFor = function (name, denormal) {
  if (name.endsWith('Id')) {
    name = name.substring(0, name.length - 2);
    return denormal ? name + '_' : name;
  }

  return denormal ? name + '_' : name + '$';
};

Path.prototype.walk = function (path /*: string | number*/) {
  /*
      TODO NAMEPATH-1:

        change Path to be immutable (it already is for the most part) and to
        support a parent Path then avoid having to pse the entire path here and
        just use the existing Path object embedded in a new Path object that
        just processes the child path
   */
  return this.base.parsePath(this.name + '.' + path);
};

Path.resolve = function (
  collection, // Tyr.CollectionInstance,
  parentPath, //?: Tyr.PathInstance,
  path //?: Tyr.PathInstance | string
) {
  if (parentPath) {
    if (typeof path === 'string') {
      return parentPath.walk(path);
    } else if (path) {
      return path;
    } else {
      return parentPath;
    }
  }

  if (typeof path === 'string') {
    return collection.parsePath(path);
  }

  return path;
};

Path.prototype.pathName = function (pi) {
  return pi <= 1
    ? this.name
    : this.path.slice(0, pi + 1).join('.') + ' in ' + this.name;
};

Path.prototype.toString = function () {
  return (
    (this.base instanceof Tyr.Collection
      ? this.base.def.name + ':'
      : this.base.toString() + '/') + this.name
  );
};

Path.prototype.isHistorical = function () {
  const fields = this.fields;

  // only the top-most field can be marked "historical"
  return fields.length && fields[0].def.historical;
};

Path.prototype.resolveObj = function (obj) {
  if (this.collectionSpecified) {
    // singleton behavior
    let values = this.base.values;
    if (!values) values = this.base.values = [];
    if (!values.length) values.push(new this.base({}));
    return values[0];
  }

  return obj;
};

Path.prototype.get = function (obj) {
  obj = this.resolveObj(obj);

  const np = this,
    path = np.path,
    fields = np.fields,
    plen = path.length;
  let arrayOrMapInPath = false;

  const values = [];

  function getInner(pi, obj) {
    if (Array.isArray(obj)) {
      const name = path[pi];
      if (name === '_') {
        pi++;
      } else if (name && name.match(Path._numberRegex)) {
        getInner(pi + 1, obj[name]);
        return;
      }

      if (pi === plen) {
        values.push(obj);
      } else {
        arrayOrMapInPath = true; // array
        for (let ai = 0, alen = obj.length; ai < alen; ai++) {
          getInner(pi, obj[ai]);
        }
      }
    } else if (pi === plen) {
      values.push(obj);
    } else if (obj === undefined || obj === null) {
      return;
    } else if (!_.isObject(obj)) {
      throw new Error(
        'Expected an object or array at ' + np.pathName(pi) + ', but got ' + obj
      );
    } else if (
      pi &&
      fields[pi - 1].type.name === 'object' &&
      path[pi] === '_'
    ) {
      arrayOrMapInPath = true; // map
      pi++;
      _.each(obj, v => getInner(pi, v));
    } else {
      let v,
        name = path[pi];

      if (
        pi < plen - 1 &&
        // link
        (fields[pi].link ||
          // array of link
          (pi < plen - 2 &&
            fields[pi].type.name === 'array' &&
            fields[pi + 1].link))
      ) {
        // if they are dereferencing a link, first check to see if an object exists by the current name
        // (the current name could be a denormalized or populated reference already)
        v = obj[name];
        if (!Tyr.isObject(v) || Array.isArray(v)) {
          // ... look for a populated or denormalized value
          let popName = Path.populateNameFor(name, false);
          v = obj[popName];
          if (v === undefined) {
            popName = Path.populateNameFor(name, true);
            v = obj[popName];

            if (v === undefined) {
              // they are dereferencing a link but there is no populated or denormalized value, return undefined
              // rather than throw an error
              return undefined;
            }
          }
        }
      } else {
        v = obj[name];
      }

      getInner(pi + 1, v);
    }
  }

  getInner(0, obj);

  if (!arrayOrMapInPath) {
    switch (values.length) {
      case 0:
        return undefined;
      case 1:
        return values[0];
      // fall through
    }
  }

  return values;
};

Path.prototype.set = function (obj, value, opts) {
  obj = this.resolveObj(obj);

  const np = this,
    path = np.path,
    fields = np.fields,
    plen = path.length;

  function walk(pi, obj) {
    if (!obj && opts && opts.ignore) return;

    const leaf = pi === plen - 1;

    if (Array.isArray(obj)) {
      const name = path[pi];
      if (leaf) {
        if (name && name.match(Path._numberRegex)) {
          obj[name] = value;
        } else {
          for (let i = 0; i < obj.length; i++) {
            obj[i] = value;
          }
        }
      } else {
        if (name === '_') {
          pi++;
        } else if (name && name.match(Path._numberRegex)) {
          let v = obj[name];
          if (!v && opts && opts.create) {
            obj[name] = fields[pi].type.name === 'array' ? [] : {};
            // Re-read value because mobx proxies
            v = obj[name];
          }

          walk(pi + 1, v);
          return;
        }

        for (const v of obj) {
          walk(pi, v);
        }
      }
    } else if (_.isObject(obj)) {
      if (leaf) {
        obj[path[pi]] = value;
      } else {
        if (pi && fields[pi - 1].type.name === 'object' && path[pi] === '_') {
          pi++;
          for (const v of obj) {
            walk(pi, v);
          }
        } else {
          const key = path[pi];
          let v = obj[key];
          if (!v && opts && opts.create) {
            obj[key] = fields[pi].type.name === 'array' ? [] : {};
            // Re-read value because mobx proxies
            v = obj[key];
          }
          walk(pi + 1, v);
        }
      }
    } else {
      throw new Error(
        'Expected an object or array at ' + np.pathName(pi) + ', but got ' + obj
      );
    }
  }

  walk(0, obj);
};

Path.prototype.uniq = function (obj) {
  const val = this.get(obj);
  return _.isArray(val) ? _.uniq(val) : [val];
};

Path.prototype.groupRange = function (groupNum) {
  const { _groups } = this;

  return groupNum
    ? [_groups[groupNum - 1], _groups[groupNum]]
    : [0, _groups[0]];
};

Path.prototype.groupLabel = function (groupNum) {
  return this._pathLabel(...this.groupRange(groupNum));
};

Path.prototype._pathLabel = function (startIdx, endIdx) {
  const { fields } = this;
  let i = startIdx,
    label = '',
    len = endIdx - startIdx,
    idxLabel = '',
    pf = i ? fields[i - 1] : undefined,
    f;

  // change "Organization Name" to just "Organization"
  // TODO:  might not want to always do this ... i.e. maybe only if it is a labelField?
  if (len > 1 && fields[endIdx - 1].label === 'Name') {
    endIdx--;
    len--;
  }

  for (; i < endIdx; pf = f, i++) {
    const last = i === endIdx - 1;
    f = fields[i];

    let l = '';

    const typeName = pf?.type.name;
    if ((typeName === 'object' && pf.keys) || typeName === 'array') {
      const path = this.path[i];

      if (path?.match(Path._numberRegex)) {
        const numbering = pf.keys?.numbering || pf.numbering;
        const code = Tyr.numberize(numbering, Number.parseInt(path, 10));

        if (label || numbering === 'ordinal') l = code;
        else idxLabel = code;
      } else {
        // handle the case where we have a map and the keys are strings, not numbers
        l = last ? f.label : f.pathLabel ?? f.label;
      }
    } else {
      l = last ? f.label : f.pathLabel ?? f.label;
    }

    if (l) {
      if (label) label += ' ';
      label += l;
    }

    if (idxLabel && (label || last)) {
      label += ' ' + idxLabel;
      idxLabel = '';
    }
  }

  return label;
};

Path.prototype._buildSpath = function (arr) {
  const key = arr ? '_spathArr' : '_spath';

  let sp = this[key];
  if (!sp) {
    sp = '';

    const { fields, path } = this;
    let parentField;

    for (let fi = 0, flen = fields.length; fi < flen; fi++) {
      const field = fields[fi];
      let { name } = field;

      if (name === '_') {
        name = path[fi];

        if (name === '_') continue;

        // otherwise name is a specific array index like 0,1,2,3,4
        if (!arr) continue;
      }

      if (fi) {
        // this is a denormalized path (but could be a populated path, so might need to add a '$' instead?)
        if (parentField.link) sp += '_';
        sp += '.';
      }
      sp += name;
      parentField = field;
    }

    this[key] = sp;
  }
  return sp;
};

Object.defineProperties(Path.prototype, {
  tail: {
    get() {
      return this.fields[this.fields.length - 1];
    },
  },

  detail: {
    get() {
      return Path._skipArray(this.fields[this.fields.length - 1]);
    },
  },

  collection: {
    get() {
      return this.base.collection;
    },
  },

  groupCount: {
    get() {
      return this._groups?.length || 0;
    },
  },

  label: {
    get() {
      const flen = this.fields.length;
      if (!flen) return this.base.label;
      const wlFn = Tyr.options.whiteLabel;
      if (wlFn) {
        const l = wlFn(this);
        if (l) return l;
      }

      return this._pathLabel(0, flen);
    },
  },

  pathLabel: {
    get() {
      const flen = this.fields.length;
      if (!flen) return this.base.label;
      const wlFn = Tyr.options.whiteLabel;
      if (wlFn) {
        const l = wlFn(this);
        if (l) return l;
      }

      const { _groups } = this;
      return this._pathLabel(_groups?.[_groups.length - 1] ?? 0, flen);
    },
  },

  spath: {
    get() {
      return this._buildSpath();
    },
  },

  spathArr: {
    get() {
      return this._buildSpath(true);
    },
  },

  identifier: {
    get() {
      let id = this._identifier;
      if (!id) {
        id = this._identifier = this.name.replace(/\./g, '_');
      }
      return id;
    },
  },

  denormal: {
    get() {
      const { fields } = this;
      const plen = fields.length;

      let pi = 0,
        denormal;
      while (pi < plen) {
        const field = fields[pi++];
        denormal = field.def.denormal;
        if (denormal) break;
      }

      while (pi < plen) {
        const field = fields[pi++];
        let denormalPath = field.name;
        let newDenormal = denormal[denormalPath];
        if (!newDenormal) {
          // look for a compound denormal
          for (; pi < plen; ) {
            const field = fields[pi++];
            const fname = field.name;
            if (fname === '_') continue;
            denormalPath += '.' + fname;
            newDenormal = denormal[denormalPath];
            if (newDenormal) break;
          }

          if (!newDenormal) return undefined;
        }

        denormal = newDenormal;
      }

      return denormal;
    },
  },
});

Path.prototype.projectify = function (projection) {
  const { detail, spath } = this;
  const { def } = detail;

  if (detail.db) projection[spath] = 1;

  // note:  we query a computed values dependents even if the computation is stored in the database
  //        in case we might want to dynamically recalculate the value.  there might be some cases
  //        where we don't want to do this
  //if (!this.db) {
  const getFn = def.get || def.getServer || def.getClient;
  if (getFn) {
    let proj = detail._projection;
    if (!proj) {
      proj = detail._projection = {};

      const paths = Tyr.functions.paths(getFn);
      for (const path of paths) {
        proj[path] = 1;
      }
    }

    Object.assign(projection, proj);
  }
  //}
};

Path.taggedTemplateLiteral = function (strings, ...keys) {
  if (keys.length) {
    let s = '',
      i = 0;

    for (const klen = keys.length; i < klen; i++) {
      s += strings[i];
      s += keys[i];
    }

    if (i < strings.length) {
      s += strings[i];
    }

    return this.$get(s);
  } else {
    return this.$get(strings[0]);
  }
};

Tyr.Path = Path;
export default Path;


text:
package org.minimalj.frontend.impl.swing.component;

import java.io.IOException;
import java.net.URL;

import javax.swing.JTextPane;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTMLEditorKit.HTMLFactory;
import javax.swing.text.html.ImageView;

import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.IContent;
import org.minimalj.frontend.impl.swing.toolkit.SwingFrontend;
import org.minimalj.frontend.impl.web.ResourcesHttpHandler;
import org.minimalj.frontend.page.Page;
import org.minimalj.frontend.page.Routing;

public class SwingHtmlContent extends JTextPane implements IContent {
	private static final long serialVersionUID = 1L;
	public static final String EVENT_TYPE_CLICK = "click";

	public SwingHtmlContent(URL url) {
		setEditorKit(new MjHtmlEditorKit());
		setContentType("text/html");
		setEditable(false);

		try {
			setPage(url);
		} catch (IOException e) {
			e.printStackTrace();
		}

		addLinkListener();
	}

	public SwingHtmlContent(String html) {
		setEditorKit(new MjHtmlEditorKit());
		setContentType("text/html");
		setEditable(false);

		setText(html);

		addLinkListener();
	}

	private void addLinkListener() {
		HyperlinkListener listener = e -> {
			if (e.getEventType() == EventType.ACTIVATED) {
				String href = e.getDescription();
				Page page = Routing.createPageSafe(href);
				SwingFrontend.run(SwingHtmlContent.this, () -> Frontend.show(page));
			}
		};
		addHyperlinkListener(listener);
	}

	private static class MjHtmlEditorKit extends HTMLEditorKit {
		private static final long serialVersionUID = 1L;

		private static ViewFactory mjFactory = new MjHTMLFactory();

		@Override
		public ViewFactory getViewFactory() {
			return mjFactory;
		}
	}

	private static class MjHTMLFactory extends HTMLFactory {
		@Override
		public View create(Element elem) {
			Object tag = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
			if (tag instanceof HTML.Tag) {
				HTML.Tag kind = (HTML.Tag) tag;
				if (kind == HTML.Tag.IMG) {
					return new MjImageView(elem);
				}
			}
			return super.create(elem);
		}
	}

	private static class MjImageView extends ImageView {
		private static ResourcesHttpHandler resourceHandler = new ResourcesHttpHandler();

		public MjImageView(Element elem) {
			super(elem);
		}

		@Override
		public URL getImageURL() {
			String src = (String) getElement().getAttributes().getAttribute(HTML.Attribute.SRC);
			if (src == null) {
				return null;
			}

			URL reference = ((HTMLDocument) getDocument()).getBase();
			try {
				if (reference != null) {
					return new URL(reference, src);
				} else {
					return resourceHandler.getUrl(src);
				}
			} catch (IOException e) {
				return null;
			}
		}
	}

}


text:
//    #[license]
//    SmartsheetClient SDK for C#
//    %%
//    Copyright (C) 2014 SmartsheetClient
//    %%
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//            http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//    %[license]

using System.Collections.Generic;

namespace Smartsheet.Api
{
    using Smartsheet.Api.Models;

    /// <summary>
    /// <para>This interface provides methods to access Attachment resources that are associated to Discussion resources.</para>
    ///
    /// <para>Thread Safety: Implementation of this interface must be thread safe.</para>
    /// </summary>
    public interface DiscussionAttachmentResources
    {
        /// <summary>
        /// <para>Gets a list of all Attachments that are in the Discussion</para>
        /// <para>It mirrors to the following Smartsheet REST API method: <br />
        /// GET /sheets/{sheetId}/discussions/{discussionId}/attachments</para>
        /// </summary>
        /// <param name="sheetId"> the sheetId </param>
        /// <param name="discussionId"> the discussion Id </param>
        /// <param name="paging"> the paging </param>
        /// <returns> list of all Attachments that are in the Discussion. </returns>
        /// <exception cref="System.InvalidOperationException"> if any argument is null or empty string </exception>
        /// <exception cref="InvalidRequestException"> if there is any problem with the REST API request </exception>
        /// <exception cref="AuthorizationException"> if there is any problem with  the REST API authorization (access token) </exception>
        /// <exception cref="ResourceNotFoundException"> if the resource cannot be found </exception>
        /// <exception cref="ServiceUnavailableException"> if the REST API service is not available (possibly due to rate limiting) </exception>
        /// <exception cref="SmartsheetException"> if there is any other error during the operation </exception>
        PaginatedResult<Attachment> ListAttachments(long sheetId, long discussionId, PaginationParameters paging);
    }
}


text:
package std.other.entity;

// Generated 2017-6-17 15:00:02 by Hibernate Tools 3.4.0.CR1

import static javax.persistence.GenerationType.IDENTITY;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.validator.NotNull;

/**
 * ArticleInfoUpdateLog generated by hbm2java
 */
@Entity
@Table(name = "article_info_update_log")
public class ArticleInfoUpdateLog implements java.io.Serializable {

	private static final long serialVersionUID = 1L;
	private Integer theId;
	private int articleInfoId;
	private Date occurrenceTime;

	public ArticleInfoUpdateLog() {
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "the_id", unique = true, nullable = false)
	public Integer getTheId() {
		return this.theId;
	}

	public void setTheId(Integer theId) {
		this.theId = theId;
	}

	@Column(name = "article_info_id", nullable = false)
	public int getArticleInfoId() {
		return this.articleInfoId;
	}

	public void setArticleInfoId(int articleInfoId) {
		this.articleInfoId = articleInfoId;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "occurrence_time", nullable = false, length = 19)
	@NotNull
	public Date getOccurrenceTime() {
		return this.occurrenceTime;
	}

	public void setOccurrenceTime(Date occurrenceTime) {
		this.occurrenceTime = occurrenceTime;
	}

}


text:
title: Fate Masters 6 - Criando um novo cenário - La Vaporeta
teaser: O Podcast dos Algozes dos Jogadores!
subheadline: Steampunk en Latinoamerica en Fate
date: 2015-07-28 09:38:00 -0300
layout: post
categories:
  - Podcast
tags:
 - Fate
 - Fate-Core
 - fate-masters
 - fate-masters-podcast
 - Podcast
 - La Vaporeta
 - Steampunk
header: no
podcast_comments: true
podcast_time: 50min
itunes:
  duration: 50:11
hosts:
 - Fábio Emilio Costa
 - Rafael Sant'Anna Meyer
 - Paulo Guerche
audios:
 - OGG:  https://archive.org/download/FateMasters6LaVaporeta/FateMasters6LaVaporeta.ogg
 - MP3:  https://archive.org/download/FateMasters6LaVaporeta/FateMasters6LaVaporeta.mp3
iaplayer: FateMasters6LaVaporeta
related_links:
  - text: O rascunho de _La Vaporeta_ (aberto para comentários), para vocês se deliciarem
    link: https://docs.google.com/document/d/102fgUuMCQZEPr1ZmSZS20CnV6x75Ors6WkAYdGWnUbg/edit?usp=docslist_api
events:
  - time: "00:04"
    text: Apresentação
  - time: "01:30"
    text: Recapitulação da Série de Criação de Mundos
  - time: "03:35"
    text: Apresentando _La Vaporeta_
  - time: "06:48"
    text: Sobre os limites a serem estabelecidos
  - time: "21:45"
    text: Sobre pontos de corte, mudanças históricas, e como isso permitiu gerar _La Vaporeta_
  - time: "24:03"
    text: O Limite do _"Legal"_
  - time: "26:46"
    text: Sobre o processo de decisão no _La Vaporeta_
  - time: "28:08"
    text: Sobre como o _fluff_ influencia o _crunch_ e vice versa
  - time: "39:00"
    text: É uma boa idéia criar regras novas?
  - time: "39:00"
    text: É uma boa idéia criar regras novas?
  - time: "46:30"
    text: Sobre a disponibilização do _La Vaporeta_ e sobre o próximo episódio
  - time: "48:16"
    text: Considerações Finais
---

Bem vindos a mais um  episódio de _Fate Masters_!  Hoje apresentaremos
o primeiro cenário feito por nós: La Vaporeta, um mundo de _steampunk_
latino  americano  com  direito  a  líderes  controversos,  engenhocas
insanas e muitas Unarondas. Além  disso, te ajudaremos a decidir sobre
quando criar  novas regras  é útil, como  fractalizar pode  ajudar seu
jogo e  responderemos até a  grande pergunta da humanidade:  quem veio
primeiro, o _fluff_ ou o _crunch_?


text:
 require 'spec_helper'
# require 'pry'
describe Mastermind::Game_Engine do
   let(:game) { Mastermind::Game_Engine.new }

  before :each do
    allow_message_expectations_on_nil
    allow(game).to receive(:puts).and_return(nil)
  end

  describe "#exact_match" do
    it 'returns exact matches'  do
      expect(game.exact_match(["r","r","r","r"], ["r","r","r","r"])).to eql([[0, 0, 0, 0], 4])
    end
  end

  describe "#partial_match" do
    it 'returns partial matches'  do
      expect(game.partial_match(["g", "y", "r", "b"], ["r", "g", "b", "y"])).to eql(4)
    end
  end

  describe "#game" do
    it 'plays the game' do
      allow(game.computer_code).to receive(:computer_choice).with(0).and_return(["r","r","r","r"])
      allow(game.player).to receive(:player_entry).and_return(nil)
      allow(game).to receive(:exact_match).and_return([[nil, nil,nil, nil], 4])
      allow(game).to receive(:partial_match).and_return(0)
      allow(game).to receive(:analysis).and_return(nil)
      allow(game).to receive(:winner).and_return("win")
      allow(game).to receive(:difficulty).and_return(0)
      expect(game.game).to eql("win")
    end
  end

   describe "#analysis" do
    it 'analyses the game' do
      game.instance_variable_set("@counter", 13)
      allow(game).to receive(:try_again).and_return("done")
      expect(game.analysis(["r", "g", "b", "y"], 2, 0)).to eql("done")
    end
   end

   describe "#winner" do
    it 'checks for winners' do
      allow(game).to receive(:start_time).and_return(1)
      allow(game).to receive(:final_time).and_return(2)
      allow(game).to receive(:namer).and_return("name")
      allow(game).to receive(:save_file).and_return("Saved")
      allow(game).to receive(:leaderboard).and_return("lead")
      allow(game).to receive(:ask).and_return("Asked")
      expect(game.winner).to eql("Asked")

    end
   end

   describe "#try_again" do
    it 'tells player to try again' do
      allow(game).to receive(:final_time).and_return(20)
      allow(game).to receive(:counter).and_return(0)
      allow(game).to receive(:ask).and_return("tried")
      expect(game.try_again(2,2)).to eql("tried")
    end
   end

   describe "#namer" do
    it 'asks for user name' do
      allow(game).to receive(:user_input).and_return("p")
      expect(game.namer).to eql("p")
    end
   end

  describe "#save_file" do
    it "should create 'filename' and put 'text' in it" do
    allow(game).to receive(:leaderboard).and_return("Done")
    expect(game.save_file("./bin/testgameresults.txt")).to be nil
    end
  end

  describe "#leaderboard" do
    it "should read the result file and print out top ten" do
    allow(game).to receive(:ask).and_return("Asked Again")
    expect(game.leaderboard("./bin/testgameresults.txt")).to eql("Asked Again")
    end
  end
end


text:
/*
	CommandTarget.cpp

	This pure base class is used to define a class as a receipient of the message heirarchy,
	which includes messages received from windows and internal messages passed by game objects

	(c)2005 PaleStar Development, Richard Lyle
*/

#define SYSTEM_DLL

#include "Debug/Trace.h"
#include "System/CommandTarget.h"
#include "Standard/StringHash.h"
#include "Standard/Limits.h"
#include "Debug/Assert.h"

//-------------------------------------------------------------------------------

Array< CommandTarget * >	CommandTarget::s_Targets;			// array of all existing command targets

//-------------------------------------------------------------------------------

CommandTarget::CommandTarget()
{
	// add the targets array
	s_Targets.push( this );
}

CommandTarget::~CommandTarget()
{
	// remove from target array
	s_Targets.removeSearch( this );
}

//-------------------------------------------------------------------------------

int CommandTarget::targetCount()
{
	return( s_Targets.size() );
}

CommandTarget *	CommandTarget::target( int n )
{
	return( s_Targets[ n ] );
}

//----------------------------------------------------------------------------

bool CommandTarget::postWindowMessage( void * hWnd, dword message, dword wparam, dword lparam )
{
	// send other messages directly
	Message msg;
	msg.message = message;
	msg.wparam = wparam;
	msg.lparam = lparam;
	msg.origin = 0;

	return( postMessage( msg ) );
}

bool CommandTarget::postMessage( const Message & msg )
{
	// pass message from newest to oldest command targets
	for(int i=CommandTarget::targetCount()-1;i>=0;i--)
		if ( CommandTarget::target( i )->onMessage( msg ) )
			return true;

	return false;
}

//-------------------------------------------------------------------------------
// EOF