text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.System.Threading;

namespace DvachBrowser3
{
    /// <summary>
    /// Канал слабо связанных событий.
    /// </summary>
    public sealed class WeakEventChannel : IWeakEventChannel
    {
        private readonly object _lock = new object();

        private const int MaxCount = 100;

        private readonly List<WeakEventContainer> _containers = new List<WeakEventContainer>();

        private static readonly List<WeakReference<WeakEventChannel>> Channels;

        private static readonly ThreadPoolTimer CleanupTask;

        private static DateTime? _lastRun;

        static WeakEventChannel()
        {
            Channels = new List<WeakReference<WeakEventChannel>>();
            CleanupTask = ThreadPoolTimer.CreatePeriodicTimer(CleanupHandler, TimeSpan.FromMinutes(2));
        }

        public static async Task<DateTime?> GetLastRun()
        {
            var task = Task.Factory.StartNew(() =>
            {
                lock (Channels)
                {
                    return _lastRun;
                }
            });
            return await task;
        }

        public static async Task TriggerCleanup()
        {
            var task = Task.Factory.StartNew(() =>
            {
                CleanupHandler(null);
            });
            await task;
        }

        public static async Task<int> GetDictionariesCount()
        {
            var task = Task.Factory.StartNew(() =>
            {
                var channels = GetChannels();
                var results = channels.Select(channel => channel.GetInfo()).ToList();
                return results.Select(r => r.Item1).DefaultIfEmpty(0).Sum();
            });
            return await task;
        }

        public static async Task<int> GetCallbacksCount()
        {
            var task = Task.Factory.StartNew(() =>
            {
                var channels = GetChannels();
                var results = channels.Select(channel => channel.GetInfo()).ToList();
                return results.Select(r => r.Item2).DefaultIfEmpty(0).Sum();
            });
            return await task;
        }

        private static WeakEventChannel[] GetChannels()
        {
            var channels = new List<WeakEventChannel>();
            lock (Channels)
            {
                foreach (var channel in Channels)
                {
                    WeakEventChannel c;
                    if (channel.TryGetTarget(out c))
                    {
                        channels.Add(c);
                    }
                }
            }
            return channels.ToArray();
        }

        private static void CleanupHandler(ThreadPoolTimer timer)
        {
            try
            {
                var channels = new List<WeakEventChannel>();
                var toDelete = new List<WeakReference<WeakEventChannel>>();
                lock (Channels)
                {
                    foreach (var channel in Channels)
                    {
                        WeakEventChannel c;
                        if (channel.TryGetTarget(out c))
                        {
                            channels.Add(c);
                        }
                        else
                        {
                            toDelete.Add(channel);
                        }
                    }
                    foreach (var channel in toDelete)
                    {
                        Channels.Remove(channel);
                    }
                }
                foreach (var channel in channels)
                {
                    channel.Cleanup();
                }
                lock (Channels)
                {
                    _lastRun = DateTime.Now;
                }
#if DEBUG
                AppHelpers.DispatchAction(async () =>
                {
                    Debug.WriteLine($"Weak event manager: dictionaries = {await GetDictionariesCount()}, callbacks = {await GetCallbacksCount()}");
                });
#endif
            }
            catch
            {
                // ignore
            }
        }

        /// <summary>
        /// Channel identifier.
        /// </summary>
        public Guid Id { get; }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="id">Channel identifier.</param>
        public WeakEventChannel(Guid id)
        {
            Id = id;
            lock (Channels)
            {
                Channels.Add(new WeakReference<WeakEventChannel>(this));
            }
        }

        private Tuple<int, int> GetInfo()
        {
            lock (_lock)
            {
                int counters = 0;
                int callbacks = 0;
                foreach (var c in _containers)
                {
                    counters++;
                    callbacks += c.Count;
                }
                return new Tuple<int, int>(counters, callbacks);
            }
        }

        private void Cleanup()
        {
            lock (_lock)
            {
                var toDelete = new List<WeakEventContainer>();
                for (int i = 0; i < _containers.Count; i++)
                {
                    var container = _containers[i];
                    container.TryCleanup();
                    if (container.Count == 0 && i > 0)
                    {
                        toDelete.Add(container);
                    }
                }
                foreach (var container in toDelete)
                {
                    _containers.Remove(container);
                }
            }
        }

        /// <summary>
        /// Register callback.
        /// </summary>
        /// <param name="callback">Weak event callback.</param>
        /// <returns>Callback registration token.</returns>
        public Guid AddCallback(IWeakEventCallback callback)
        {
            lock (_lock)
            {
                if (_containers.Count == 0)
                {
                    _containers.Insert(0, new WeakEventContainer());
                }
                if (_containers[0].Count > MaxCount)
                {
                    _containers.Insert(0, new WeakEventContainer());
                }
                return _containers[0].Register(callback);
            }
        }

        /// <summary>
        /// Remove callback.
        /// </summary>
        /// <param name="token">Weak event callback registration token.</param>
        public void RemoveCallback(Guid token)
        {
            lock (_lock)
            {
                var toDelete = new List<WeakEventContainer>();
                for (int i = 0; i < _containers.Count; i++)
                {
                    var container = _containers[i];
                    container.Unregister(token);
                    if (container.Count == 0 && i > 0)
                    {
                        toDelete.Add(container);
                    }
                }
                foreach (var container in toDelete)
                {
                    _containers.Remove(container);
                }
            }
        }

        /// <summary>
        /// Trigger weak event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">Event argument.</param>
        public void RaiseEvent(object sender, object e)
        {
            var toInvoke = new List<IWeakEventCallback>();
            lock (_lock)
            {
                foreach (var container in _containers)
                {
                    foreach (var cb in container.GetCallbacks())
                    {
                        toInvoke.Add(cb);
                    }
                }
            }
            foreach (var cb in toInvoke)
            {
                cb.ReceiveWeakEvent(sender, this, e);
            }
        }

        private class WeakEventContainer
        {
            private Dictionary<Guid, WeakReference<IWeakEventCallback>> _references = new Dictionary<Guid, WeakReference<IWeakEventCallback>>();

            public int Count => _references.Count;

            public void TryCleanup()
            {
                var toDelete = new List<Guid>();
                foreach (var kv in _references)
                {
                    IWeakEventCallback cb;
                    if (!kv.Value.TryGetTarget(out cb))
                    {
                        toDelete.Add(kv.Key);
                    }
                }
                foreach (var id in toDelete)
                {
                    _references.Remove(id);
                }
            }

            public Guid Register(IWeakEventCallback callback)
            {
                if (callback == null)
                {
                    return Guid.Empty;
                }
                var id = Guid.NewGuid();
                _references[id] = new WeakReference<IWeakEventCallback>(callback);
                return id;
            }

            public void Unregister(Guid id)
            {
                _references.Remove(id);
            }

            public ICollection<IWeakEventCallback> GetCallbacks()
            {
                var toInvoke = new List<IWeakEventCallback>();
                var toDelete = new List<Guid>();
                foreach (var kv in _references)
                {
                    IWeakEventCallback cb;
                    if (!kv.Value.TryGetTarget(out cb))
                    {
                        toDelete.Add(kv.Key);
                    }
                    else
                    {
                        toInvoke.Add(cb);
                    }
                }
                foreach (var id in toDelete)
                {
                    _references.Remove(id);
                }
                return toInvoke;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
.class Landroid/content/pm/AMSLogger$1;
.super Landroid/os/FileObserver;
.source "AMSLogger.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/content/pm/AMSLogger;->logStackTrace(ILjava/lang/String;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/content/pm/AMSLogger;

.field final synthetic val$traceFile:Ljava/lang/String;

# direct methods
.method constructor <init>(Landroid/content/pm/AMSLogger;Ljava/lang/String;ILjava/lang/String;)V
    .locals 0

    iput-object p1, p0, Landroid/content/pm/AMSLogger$1;->this$0:Landroid/content/pm/AMSLogger;

    iput-object p4, p0, Landroid/content/pm/AMSLogger$1;->val$traceFile:Ljava/lang/String;

    invoke-direct {p0, p2, p3}, Landroid/os/FileObserver;-><init>(Ljava/lang/String;I)V

    return-void
.end method

# virtual methods
.method public declared-synchronized onEvent(ILjava/lang/String;)V
    .locals 3

    monitor-enter p0

    :try_start_0
    invoke-static {}, Landroid/content/pm/AMSLogger;->-get0()Ljava/lang/String;

    move-result-object v0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    iget-object v2, p0, Landroid/content/pm/AMSLogger$1;->val$traceFile:Ljava/lang/String;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string/jumbo v2, " file closed after writing"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Slog;->i(Ljava/lang/String;Ljava/lang/String;)I

    invoke-virtual {p0}, Landroid/content/pm/AMSLogger$1;->notifyAll()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit p0

    return-void

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "UnrealEd.h"

/** Notification class for asynchronous shader compiling. */
class FNavigationBuildingNotificationImpl
	: public FTickableEditorObject
{

public:

	FNavigationBuildingNotificationImpl()
	{
		bPreviouslyDetectedBuild = false;
		LastEnableTime = 0;
	}

	/** Starts the notification. */
	void BuildStarted();

	/** Ends the notification. */
	void BuildFinished();

protected:
	/** FTickableEditorObject interface */
	virtual void Tick(float DeltaTime) override;
	virtual bool IsTickable() const override
	{
		return true;
	}
	virtual TStatId GetStatId() const override;

private:
	void ClearCompleteNotification();
	FText GetNotificationText() const;

	bool bPreviouslyDetectedBuild;
	double TimeOfStartedBuild;
	double TimeOfStoppedBuild;

	/** Tracks the last time the notification was started, used to avoid spamming. */
	double LastEnableTime;

	TWeakPtr<SNotificationItem> NavigationBuiltCompleteNotification;

	/** The source code symbol query in progress message */
	TWeakPtr<SNotificationItem> NavigationBuildNotificationPtr;
};


text:
package ro.helator.ie.camel.interfaces;

import org.osgi.framework.Bundle;

public interface TemplateScanerService {

	public void register(Bundle bundle, ClassLoader loader);

	public void unregister(Bundle bundle, ClassLoader loader);

}


text:
package superheroes.dao.impl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import superheroes.dao.UrlDao;
import superheroes.entity.Url;

import java.util.List;

/**
 * Created by catop on 4/4/15.
 */
@Component
public class UrlDaoHibernateImpl implements UrlDao {

    private static final Logger LOGGER = LogManager.getLogger(UrlDaoHibernateImpl.class.getName());

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveUrl(Url url) {
        LOGGER.trace("IN: url=" + url);
        Session session = sessionFactory.getCurrentSession();
        session.save(url);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateUrl(Url url) {
        LOGGER.trace("IN: url=" + url);
        Session session = sessionFactory.getCurrentSession();
        session.saveOrUpdate(url);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteUrl(Url url) {
        LOGGER.trace("IN: url=" + url);
        Session session = sessionFactory.getCurrentSession();
        session.delete(url);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Url getUrlById(Long id) {
        LOGGER.trace("IN: id=" + id);
        Session session = sessionFactory.getCurrentSession();
        Url url = (Url) session.get(Url.class, id);
        return url;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public List<Url> getAllUrls() {
        LOGGER.trace("IN");
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from superheroes.entity.Url");
        List<Url> urls = query.list();
        LOGGER.trace("OUT: urls.size=" + urls.size());
        return urls;
    }
}


text:
<?php

namespace TrackerBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="TrackerBundle\Entity\UserRepository")
 */
class User extends BaseUser
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="firstName", type="string", length=50)
     */
    protected $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="lastName", type="string", length=50)
     */
    protected $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=60)
     */
    protected $email;

    /**
     * @var integer
     *
     * @ORM\Column(name="status", type="integer")
     */
    protected $status;

    /**
     * @var string
     *
     * @ORM\Column(name="hash", type="string", length=255)
     */
    protected $hash;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime", nullable=true)
     */
    protected $created;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated", type="datetime", nullable=true)
     */
    protected $updated;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="passwordChangedAt", type="datetime", nullable=true)
     */
    protected $passwordChangedAt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     *
     * @return User
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     *
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set status
     *
     * @param integer $status
     *
     * @return User
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return integer
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set hash
     *
     * @param string $hash
     *
     * @return User
     */
    public function setHash($hash)
    {
        $this->hash = $hash;

        return $this;
    }

    /**
     * Get hash
     *
     * @return string
     */
    public function getHash()
    {
        return $this->hash;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     *
     * @return User
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     *
     * @return User
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set passwordChangedAt
     *
     * @param \DateTime $passwordChangedAt
     *
     * @return User
     */
    public function setPasswordChangedAt($passwordChangedAt)
    {
        $this->passwordChangedAt = $passwordChangedAt;

        return $this;
    }

    /**
     * Get passwordChangedAt
     *
     * @return \DateTime
     */
    public function getPasswordChangedAt()
    {
        return $this->passwordChangedAt;
    }

    /**
     * @return string
     */
    public function __toString(){
        return (string) $this->getEmail();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">RadioLink</string>
    <string name="action_share">Share</string>

    <string name="scheme">radiolink</string>
    <string name="scheme_host_share">share</string>
    <string name="scheme_host_test">test</string>

    <string name="scheme_title">Share</string>

    <string name="channel_code_dialog_title">Channel</string>

    <string name="join_channel_dialog_title">確認</string>
    <string name="join_channel_dialog_message">このチャンネルに参加しますか?</string>

    <string name="channel_code_is_null">ChannelCode欄をタップしてチャンネルコードを設定してください。</string>
    <string name="channel_is_not_owner">画像はChannel作成ユーザだけが設定できます。</string>

    <string name="media_type_headset">Headset</string>
    <string name="media_type_speaker">Speaker</string>
    <string name="media_type_normal">Normal</string>

    <string name="mic_normal">Mic</string>
    <string name="mic_mute">Mute</string>

    <string name="mic_mute_normal">マイクを有効にしました。</string>
    <string name="mic_mute_message">マイクをミュートにしました。</string>

    <string name="purchase_cancel">購入をキャンセルしました。</string>

    <!-- GCM title,message -->
    <string name="gcm_title_channel_update">チャンネル アップデート</string>
    <string name="gcm_message_channel_update">チャンネル が更新されました。</string>

    <string name="channel_not_found">指定されたチャンネルが見つかりませんでした。</string>
    <string name="channel_code_mini_length">チャンネルコードは{{LENGTH}}文字以上入力してください。</string>

    <string name="create_date_dummy">1970/01/01</string>
</resources>


text:
'use strict';

angular.module('users').factory('Roles', [
	function() {
		// Roles service logic
		// ...

		// Public API
		return {
			getRoles: function() {
				return ['user', 'assistant_forester', 'forest_manager', 'chief_officer', 'super'];
			}
		};
	}
]);


text:
var fs = require("fs");

// Reading Synchronously
//var contents = fs.readFileSync("./lib/sayings.md", "UTF-8");

// reads binary.
//var contents = fs.readFileSync("./lib/sayings.md");
/*
var contents = fs.readFile("./lib/sayings.md", "UTF-8", function(err, contents){
	if(err){
		throw err;
	}

	global.console.log(contents);
});
*/

global.console.log("Readling file async...");

var path = require("path");

fs.readdir("./lib", function(err, files){
	files.forEach(function(fileName){
		var file = path.join(__dirname, "lib", fileName);
		var stats = fs.statSync(file);
		if(stats.isFile() && fileName !== ".DS_Store"){
			fs.readFile(file, "UTF-8", function(err, contents){
				console.log(contents);
			})
		}
	})
})


text:
<?php namespace Neomerx\JsonApi\Contracts\Encoder\Parser;

use \Iterator;

/**
 * @package Neomerx\JsonApi
 */
interface DataAnalyzerInterface
{
    /**
     * Analyze input data.
     *
     * @param array|object|null|Iterator $data
     *
     * @return array [$isEmpty, $isCollection, $schema, $traversableData]
     */
    public function analyze($data);
}


text:
angular.module('ot.service.template', [
    'ot.service.core',
    'ot.service.form'
])
    .service('otTemplateService', function ($http, $modal, ot, otFormService, otAlertService) {
        var self = {};

        /**
         * Displays and manages the template definition for a branch.
         * @param templateDefinitionUri URL to get the template definition.
         */
        self.templateDefinition = function (templateDefinitionUri) {
            return otFormService.display({
                uri: templateDefinitionUri,
                title: "Template configuration",
                size: 'lg',
                submit: function (template) {
                    return ot.call($http.put(templateDefinitionUri, template));
                }
            });
        };

        /**
         * Synchronises the template definition with branches.
         * @param templateSyncUri URL to get the template definition.
         */
        self.templateSync = function (templateSyncUri) {
            otAlertService.displayProgressDialog({
                title: "Template synchronisation",
                promptMessage: "Synchronisation of this template is about to start. This might change the linked " +
                    "instances. Do you want to continue?",
                waitingMessage: "Synchronising the template...",
                endMessage: "Synchronisation has been done.",
                resultUri: 'app/service/service.template.syncResult.tpl.html',
                task: function () {
                    return ot.call($http.post(templateSyncUri));
                }
            });
        };

        /**
         * Gets a single branch name and creates a template instance from it.
         */
        self.createTemplateInstance = function (templateInstanceUri) {
            return otFormService.display({
                uri: templateInstanceUri,
                title: "Template instance creation",
                submit: function (data) {
                    var name = data.name;
                    var manual = data.manual;
                    delete data.name;
                    delete data.manual;
                    var request = {
                        name: name,
                        manual: manual,
                        parameters: data
                    };
                    return ot.call($http.put(templateInstanceUri, request));
                }
            });
        };

        /**
         * Disconnect a branch from its template
         */
        self.templateInstanceDisconnect = function (templateInstanceDisconnectUri) {
            return otAlertService.confirm({
                title: "Template disconnection",
                message: "Do you really want to disconnect this branch from its template? There will be no way " +
                    "to reattach it later on."
            }).then(function () {
                return ot.pageCall($http.delete(templateInstanceDisconnectUri));
            });
        };

        /**
         * Connect a branch to a template
         */
        self.templateInstanceConnect = function (templateInstanceConnectUri) {
            return otFormService.display({
                uri: templateInstanceConnectUri,
                title: "Connection to a template",
                submit: function (data) {
                    console.log('data=', data);
                    // Creation of the request
                    var request = {};
                    // Selected template
                    request.templateId = parseInt(data.connectionRequest.id, 10);
                    // Manual mode?
                    request.manual = data.connectionRequest.data.manual;
                    // Collections of parameters
                    request.parameters = {};
                    angular.forEach(data.connectionRequest.data, function (value, key) {
                        if (key != 'manual') {
                            request.parameters[key] = value;
                        }
                    });
                    // Call
                    return ot.pageCall($http.post(templateInstanceConnectUri, request));
                }
            });
        };

        /**
         * Syncs a branch against its template
         */
        self.templateInstanceSync = function (templateInstanceSyncUri) {
            return otAlertService.confirm({
                title: "Template synchronisation",
                message: "Do you really want to synchronise this branch from its template?"
            }).then(function () {
                return ot.pageCall($http.post(templateInstanceSyncUri));
            });
        };

        return self;
    })
;


text:
| Lang | Env | Arc | Topic |
|------|-----|-----|-------|
| | | | Introduction |
| JS | | | What is JS; browser vs node |
| Env | | | Starting a terminal; Installing node |
| Env | Node | | Using Node; Starting/stopping the REPL |
| JS | Node REPL | | Node REPL: math; variables |
| Env | | | Setting up a project dir; How to think about projects on disk |
| Env | | | Setting up an editor; Atom; Sublime |
| JS | Node REPL | node-rogue | Strings; Hello World by `console.log`; draw a static map |
| JS | Node REPL | node-rogue | Functions 1: simple functions; `double()`; global turn counter |
| JS | Node REPL | node-rogue | Randomness 1: dice |
| JS | Node REPL | node-rogue | Objects 1: objects as single objects; monsters |
| JS | Node REPL | node-rogue | Draw a stats panel |
| JS | Node REPL | node-rogue | Six completely random attributes |
| JS | Node REPL | node-rogue | Functions 2: state-parameterized functions; `double()`; health counters |
| JS | Node REPL | node-rogue | If/else; is-live on stats panel (currently always-yes) |
| JS | Node REPL | node-rogue | Objects 2: game items: simple weapons - daggers only |
| JS | Node REPL | node-rogue | Functions 3: functions as object members; weapons determining damage |
| JS | Node REPL | node-rogue | Arrays; simple monster list |
| JS | Node REPL | node-rogue | `Array.map()`; acting over the monsters |
| JS | Node REPL | node-rogue | Template strings; better `console.log`; screen log; game event messages |
| JS | Node REPL | node-rogue | updating the player's position with function calls; redrawing the map |
| JS | Node | node-rogue | Moving to using the code from a console environment |
| JS | Node TTY | node-rogue | Consuming keypresses; auto-updating the player's position; auto-redraw |
| JS | Node TTY | node-rogue | Preventing the player from making impossible moves |
| Env | | | Setting up a github account |
| Env | | | Setting up git locally |
| Env | | | Moving node-rogue into github |
| JS | Node TTY | node-rogue | Picking up treasure |
| JS | Node TTY | node-rogue | Basic conflict: you hit them, they die |
| JS | Node TTY | node-rogue | Objects 3: objects as containers; moving the game global state into an object |
| JS | Node TTY | node-rogue | Randomness 2: list selection - more than just daggers |
| JS | Node TTY | node-rogue | Monster movement 1: completely random synced movement |
| JS | Node TTY | node-rogue | Monster movement 2: preventing impossible monster moves |
| JS | Node TTY | node-rogue | Monster movement 3: bee-lining |
| JS | Node TTY | node-rogue | Monster movement 4: multiple movement brains: random, bee-line, sit-still |
| JS | Node TTY | node-rogue | Better conflict: hit points; they fight back; missing |
| JS | Node TTY | node-rogue | Colors; `colors` JS module; Installing modules with `npm`; color message line |
| JS | Node TTY | node-rogue | Color map |
| JS | Node TTY | node-rogue | Rudimentary static map generation |
| JS | Node TTY | node-rogue | `for loop`s; Much larger static map generation; scrolling |
| JS | Node TTY | node-rogue | Clearing the screen between game steps |
| JS | Node TTY | node-rogue | Fitting the console |
| JS | Node TTY | node-rogue | Healing |
| JS | Node TTY | node-rogue | Hunger |
| JS | Node TTY | node-rogue | Monster spawning |
| JS | Node TTY | node-rogue | Load and save game state |
| JS | Node TTY | node-rogue | Slightly randomized maps: hall generation |
| JS | Node TTY | node-rogue | Slightly randomized maps: door placement |
| JS | Node TTY | node-rogue | Slightly randomized maps: room placement |
| JS | Node TTY | node-rogue | Slightly randomized maps: room omission |
| JS | Node TTY | node-rogue | Slightly randomized maps: monsters |
| JS | Node TTY | node-rogue | Slightly randomized maps: items |
| JS | Node TTY | node-rogue | Slightly randomized maps: treasure |
| JS | Node TTY | node-rogue | Slightly randomized maps: stairs |
| JS | Node TTY | node-rogue | Slightly randomized maps: town level |
| JS | Node TTY | node-rogue | Slightly randomized maps: depth difficulty |
| JS | Node TTY | node-rogue | Randomized maps: better room placement |
| JS | Node TTY | node-rogue | Randomized maps: shaped rooms |
| JS | Node TTY | node-rogue | Randomized maps: themed rooms |
| JS | Node TTY | node-rogue | Randomized maps: fixed rooms |
| JS | Node TTY | node-rogue | Randomized maps: unique items |
| JS | Node TTY | node-rogue | Randomized maps: unique creatures |
| JS | Node TTY | node-rogue | Permadeath |
| JS | Node TTY | node-rogue | Graveyard |
| JS | Node | node-rogue | Local "global" install |
| JS | NPM | node-rogue | NPM registration and installation |
| JS | | node-rogue | Free form: add some content! |
| JS | NPM | node-rogue | NPM registering a new version |

| JS | Browser | TipCalc | Javascript 9 | First tiny app: a tip calculator in Node REPL |


text:
using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Caliburn.Micro.HelloUWP.Messages;
using Caliburn.Micro.HelloUWP.ViewModels;

namespace Caliburn.Micro.HelloUWP
{
    public sealed partial class App
    {
        private WinRTContainer _container;
        private IEventAggregator _eventAggregator;

        public App()
        {
            InitializeComponent();
        }

        protected override void Configure()
        {
            _container = new WinRTContainer();
            _container.RegisterWinRTServices();

            _container
                .PerRequest<ShellViewModel>()
                .PerRequest<DeviceViewModel>();

            _eventAggregator = _container.GetInstance<IEventAggregator>();
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            // Note we're using DisplayRootViewFor (which is view model first)
            // this means we're not creating a root frame and just directly
            // inserting ShellView as the Window.Content

            DisplayRootViewFor<ShellViewModel>();

            // It's kinda of weird having to use the event aggregator to pass
            // a value to ShellViewModel, could be an argument for allowing
            // parameters or launch arguments

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                _eventAggregator.PublishOnUIThread(new ResumeStateMessage());
            }
        }

        protected override void OnSuspending(object sender, SuspendingEventArgs e)
        {
            _eventAggregator.PublishOnUIThread(new SuspendStateMessage(e.SuspendingOperation));
        }

        protected override object GetInstance(Type service, string key)
        {
            return _container.GetInstance(service, key);
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return _container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            _container.BuildUp(instance);
        }
    }
}


text:
'use strict';

const assert = require('assert');
const { ImperativeTest } = require('../..');

const test = new ImperativeTest();
let onDoneCalled = false;

test.on('done', () => {
  onDoneCalled = true;
});

assert(!onDoneCalled, 'must not call on done');

test.end();

assert(onDoneCalled, 'onDone must be called');


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "ARGF.closed?" do
  before :each do
    @file1_name = fixture __FILE__, "file1.txt"
    @file2_name = fixture __FILE__, "file2.txt"
  end

  it "returns true if the current stream has been closed" do
    argf [@file1_name, @file2_name] do
      stream = @argf.to_io
      stream.close

      @argf.closed?.should be_true
      stream.reopen(@argf.filename, 'r')
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
	<title>{% block title %}{% endblock %}</title>

        {% block content %}
        {% endblock %}

                С уважением,

                команда интернет-магазина «Томат»

                {% block footer-phones %}
                Тел.: 8 (3952) 486-596

                {% endblock %}
                tomat-podarky.ru


text:
require_relative '../../../spec_helper'
require_relative 'shared/constants'

describe "Digest::MD5#digest_length" do

  it "returns the length of computed digests" do
    cur_digest = Digest::MD5.new
    cur_digest.digest_length.should == MD5Constants::DigestLength
  end

end


text:
layout:     post
title: "Comparing rental prices in the US market"
date:       2017-12-11
author:     "Thomas Vincent"
header-img: "img/galaxy.jpg"
---

<style>
.center-image
{
    margin: 0 auto;
    display: block;
}
</style>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

___

## Rental Prices in the US

As a fortunate resident of New York City, I get to enjoy the many activities offered by a city that never really turns off its lights. The price to pay for such entertainment, however, are the crazy rental fees. I have stopped counting the number of conversations I have had with friends about some of the exhorbitant living costs in NYC. I have also drooled over multi-million mansions with sprawling views of the city, and wondered how studios the size of a shoe box could claim such high prices. Fortunately for me, I have been living in the same spot for the last few years, but am now expecting to start looking again soon.

This means that I am starting to look for both a new neighborhood and a new apartment, and for that I have been primarily relying on the [Streeteasy](https://streeteasy.com/) and [Zillow](https://www.zillow.com/) wesbites. Eventually, keeping track of all this gets a little confusing, and I can only imagine  how much worse it gets for people just moving into NYC.

For these reasons, I decided to see if I could leverage some open-source data in order to extract and visualize some information out of it. In the following post, I will collect and analyze some of the [great data made available by Zillow](https://www.zillow.com/research/data/#rental-data), while also going through the steps that allowed me to create the [web application](https://statofmind.shinyapps.io/rental-predictor/) displayed below

[![Web application screenshot](/img/rental_predictor_app_screenshot.png)](https://statofmind.shinyapps.io/truth-o-meter/)

### Obtaining Zillow data & Forecasts

Obtaining the data for this project is very straightforward, and does not require any scraping or cleaning. All the data can be directly downloaded from the following [link](https://www.zillow.com/research/data/#rental-data), and contains monthly median rental prices in neigborhoods of various US cities between 2010 and now. In order to produce forecasts of the time series represented in the Zillow dataset, I leveraged the additive `HoltWinters` function, which comes as part of `R`'s core packages). Briefly, the additive Holt Winters model assumes that the value of a time series $$Y$$ at time $$t$$ can be represented as:

$$y_{t} = b_{1} + b_{2}t + S_{t} + \epsilon_{t}$$

where $$b_{1}$$ represents the base signal of the time series, $$_{2}$$ denotes the linear trend component, $$S_{t}$$ is the additive seasonal factor and $$\epsilon_{t}$$ is the random error component of the time series. The Holt Winters additive seasonal model assumes that the amplitude of the seasonal component of the time series is independent of the average level of the series itself. I thought that this assumption fit well with the Zillow data, so decided to work with that. I also assessed other methodologies for time series forecasting, but it eventually turned into a bigger project than I had intended. Instead, I have planned to write a comparative analysis for the various time series libraries available in both Python and R. In the meantime, let's show how the app was built!

### Building the Rental Predictor Shiny application

The next step was to build a Shiny app that allows anyone to look at forecasts and seasonality of different neighborhoods. For simplicity, I have hosted the app on [shinyapps.io](https://statofmind.shinyapps.io/rental-predictor/), but in order to ensure full reproducibility, I have containerized the full application using `Docker`. If you have not used or heard of `Docker`, their own website gives a very good description:

```
Docker containers wrap up a piece of software in a complete filesystem that contains everything it needs to run: code, runtime, system tools, system libraries – anything you can install on a server. This guarantees that it will always run the same, regardless of the environment it is running in.
```

With that in mind, the development workflow used to create this Shiny app was:

* Build the shiny app locally (i.e. on your local machine) and ensure that everything works just as expected.
* Create a file called `Dockerfile`, in which we specify all the required instructions and commands, environnment variables and configurations.
* Build and run the `Docker` container to check that the app behaves as expected. If not, iterate over the first step until you are satisfied.
* Reap the benefits of a fully reproducible app that can be ran on any OS platform!

The source code for the full web app can be found at the [following GitHub repository](https://github.com/tlfvincent/rental-predictor), and has the following directory structure:

{% highlight bash %}
.
├── Dockerfile
├── LICENSE
├── README.md
├── app
│   ├── data
│   │   ├── Neighborhood_MedianRentalPrice_1Bedroom.csv
│   │   ├── Neighborhood_MedianRentalPrice_2Bedroom.csv
│   │   ├── Neighborhood_MedianRentalPrice_3Bedroom.csv
│   │   ├── Neighborhood_MedianRentalPrice_4Bedroom.csv
│   │   └── Neighborhood_MedianRentalPrice_Studio.csv
│   ├── server.R
│   ├── static
│   │   └── dygraph.css
│   ├── ui.R
│   └── utils.R
├── download_data.sh
├── rental_predictor.R
└── shiny-server.sh

1 directory, 10 files
{% endhighlight %}

By cloning this [Github directory](https://github.com/tlfvincent/rental-predictor) and typing the commands below, you will be able to run the web app yourself. You should also make sure that Docker is installed on your machine, which can be achieved by following the instructions in this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-16-04).

{% highlight bash %}
# build Docker container with tag name rental-predictor
docker build -t rental-predictor .

# run Docker container and mirror port 4000
docker run -p 4000:4000 -t rental-predictor

# Note: the above was tested on a Ubuntu machine hosted on DigitalOcean.
# For convenience, I used their Docker One-Click Applications,
# which automatically installs Docker during the booting process.
{% endhighlight %}

Et voila, you are done! A snapshot of the app is displayed below, or you can visit the app at the following link. It allows to select a city and neighborhood, at which point the plot described in the previous section are surfaced to the user:

![Web application screenshot](/img/rental_predictor_app_screenshot.png)


text:
layout: post
title: "How to develop an Osirix Plugin - part 1: basics"
date:   2015-07-13
categories: osirix_plugin
tags: Tutorial
---

It's not easy to find documentation or examples on how to develop one's own Osirix plugin. I gathered here some materials and my experience.

* Update 2017-08-12: [Check the new version of this tutorial]({{ site.baseurl }}{% post_url 2017-08-12-Horos-Plugin %}).

# Useful websites

[OsiriX website](http://www.osirix-viewer.com/Documentation/Guides/Development/)
[OsiriX plugin basics website](https://osirixpluginbasics.wordpress.com)
[OsiriX plugin by osirixnewby](http://myfirstosirixplugin.blogspot.com/)
[OsiriX plugin development tutorial by Kyung Hyun Sung](http://kyungs.bol.ucla.edu/Site/Software.html)
[OsiriX ITK plugin development tutorial by Brian Jensen](http://campar.in.tum.de/Students/SepOsiriXSegmentation)

# My how-to

1. Get available plugins code from [github repository](https://github.com/pixmeo/osirixplugins) to your ``<osirx_plugins_dir>``
2. Use **Osirix Plugin Generator.app** from ``<osirx_plugins_dir>/_help``. Move it to ``<your_plugin_dir>``
3. Configure build settings -Change ``Base SDK`` to ``Latest OSX``
4. Build and ... Voila! - you should be able to install your plugin, restart osirix and run your plugin.

It works, but it would be nice to have debugger before we start messing with the code.

1. Click **Edit Scheme**. As executable choose Osirix (one installed in Application is OK).
2. Go to **Arguments**, **Arguments Passed on Launch** and add
  `--LoadPlugin $(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).$(WRAPPER_EXTENSION)`
3. Change architecture to one corresponding to your Osirix version.
4. Build and ... Voila! Osirix should open, your plugin should be in plugins menu and you should be able to play with breakpoints in the plugin code.


text:
from iptest.assert_util import skiptest
skiptest("win32", "silverlight", "cli64")
from iptest.cominterop_util import *
from clr import StrongBox
from System.Runtime.InteropServices import DispatchWrapper

if is_win7:
    import sys
    print "MSAgent is unavailable on Windows 7!"
    sys.exit(0)
#------------------------------------------------------------------------------
#--GLOBALS
com_obj = CreateAgentServer()

#------------------------------------------------------------------------------
#--TESTS
def test_merlin():
    from time import sleep

    Assert('Equals' in dir(com_obj))
    charID = StrongBox[int](0)
    reqID = StrongBox[int](0)
    com_obj.Load('Merlin.acs', charID, reqID)
    cid = charID.Value

    character = StrongBox[object](DispatchWrapper(None))
    com_obj.GetCharacter(cid, character)
    c = character.Value.WrappedObject
    sleep(1)

    if is_snap or testpath.basePyDir.lower()=='src':
        c.Show(0, reqID)
        sleep(1)
        visible = StrongBox[int](0)
        while visible.Value == 0:
            c.GetVisible(visible)
            sleep(1)

    c.Think('IronPython...', reqID)
    c.Play('Read', reqID)
    c.GestureAt(True, False, reqID)
    c.GestureAt(100, 200, reqID)
    AssertError(OverflowError, c.GestureAt, 65537.34, 32) # It should be an error to convert a float to Int16 since it will not fit

    c.Speak('hello world', None, reqID)

    c.StopAll(0)
    c.Hide(0, reqID)
    sleep(1)
    com_obj.Unload(cid)

    delete_files("AgentServerObjects.dll")

#------------------------------------------------------------------------------
run_com_test(__name__, __file__)


text:
using namespace uth;

Heli::Heli(pmath::Vec2f givenPos, Player* player)
{
	auto heliTex = uthRS.LoadTexture("Enemies/copteri.png");
	heliTex->SetSmooth(true);
	this->AddComponent(new AnimatedSprite(heliTex, 2, 2, 1, 12));
	m_hoverTime = 0;
	m_hoverSpeed = 2;
	m_hoverScale = pmath::Vec2f(100, 80);
	isMoving = 0;
	m_linearSpeedBase = 1;
	m_linearSpeed = 0.5;
	m_missileCD_max = 0.7;
	m_missileCD_min = 0.2;
	m_dt = 0;
	m_pathLenght = 0;
	m_shootDelay = 0.07;
	burstTimer = 3;
	m_missileClip = 8;
	m_missileCount = 0;
	m_shootingTarget = pmath::Vec2f(0,400);
	bonVoyageTimer = 0;
	m_missileRegenTimer = 0;
	m_missileRegenTime = 1;
	m_hoverMaxTime = 0; // randomized in pilot func.
	isCool = 0;
	m_player = player;
	m_health = 100;
	m_stabilizer = 6.5;
	m_angleMod = 18;
	m_currentAngle = 0;
	m_hoverMod = 1;
	m_curPos = givenPos - pmath::Vec2(1,0);
	Navigate(pmath::Vec2f(givenPos));
	isShooting = false;
	m_verticalScaler = 1;

	//m_heliSound = uthRS.LoadSound("Audio/Effects/helicopter.ogg");
	//m_heliSound->Play();
	//m_heliSound->SetVolume(70);
	//m_heliSound->Loop(true);
}

void Heli::slerpToAngle()
{
	float tempAngle = m_currentAngle - m_targetAngle;
	if (abs(tempAngle) > 1)
	{
		m_currentAngle -= tempAngle / m_stabilizer;
	}
	else
	{
		m_currentAngle = m_targetAngle;
	}
}
Heli::Heli()
{
}

Heli::~Heli()
{
}

void Heli::update(float dt)
{
	m_verticalScaler = 0.4 + (transform.GetPosition().y + 300) / 1000;
	m_dt = dt;
	if (GetComponent<Rigidbody>())
		Pilot();

	if (m_player->m_isJumping && transform.GetPosition().y > 175 && ((transform.GetPosition().x < 185 && transform.GetPosition().x > 80 && m_player->isGoingRight == true) || (transform.GetPosition().x > -185 && transform.GetPosition().x < -90 && m_player->isGoingRight == false)))
	{
		m_health = 0;
	}
		m_lastX = transform.GetPosition().x;

#ifdef UTH_SYSTEM_ANDROID
	if (uthInput.Touch.Motion() == TouchMotion::TAP)
	{
		SetNextPos(uthInput.Common.Position());
	}
#endif

}

bool Heli::isDestroyed()
{
	if (m_health < 1)
	{
		return 1;
	}
	else
	{
		return 0;
	}

}

void Heli::Hover()
{
		m_hoverMod = pow(cos(pmath::pi * (m_nextPos - m_curPos).length() / m_pathLenght),2); // acceleration and deacceleration. Use pows 2 * n only.
		m_hoverTime +=  m_hoverSpeed * m_dt;
		m_hoverDisplacement = m_hoverMod * pmath::Vec2f(m_hoverScale.x * sin(m_hoverTime), m_hoverScale.y * cos(m_hoverTime / 2));
}

void Heli::Navigate(pmath::Vec2f targ)
{
	if (m_nextPos != m_curPos)
	{
		m_prevPos = m_curPos;
		m_nextPos = targ;
		m_moveDir = (m_nextPos - m_prevPos);
		m_pathLenght = m_moveDir.length();
		m_moveDir = m_moveDir.normalize();
		isMoving = 1;
	}

}

void Heli::LinearMove()
{
	m_linearSpeedBoost = (1 - m_hoverMod) * (m_nextPos - m_curPos).length() / 100;  // boost kicks in on long distances. max dist is 1400 so max boost is 1400/200 = 7. (1 - m_hoverMod) gives smooth acceleration.
	m_curPos +=  (m_linearSpeed + m_linearSpeedBoost) * m_moveDir;

	if (std::abs((m_curPos - m_nextPos).length()) < 2 )
	{
		m_curPos = m_nextPos;
		isMoving = 0;
		m_hoverMaxTime = Randomizer::GetFloat(4, 8); // sets time until next transition.
	}

}

void Heli::Pilot()
{
	if (bonVoyageTimer > m_hoverMaxTime && !isShooting)
	{
		auto voyage = pmath::Vec2f(Randomizer::GetFloat(-700, 700), Randomizer::GetFloat(150, 275));
		if ((transform.GetPosition() - voyage).length() > 200 && abs(voyage.x) > 400)
		{
			SetNextPos(voyage);
			bonVoyageTimer = 0;
		}
	}

	bonVoyageTimer += m_dt;

	if (!isMoving)
	{
		Navigate(m_nextPos);
	}

	if (isMoving)
	{
		LinearMove();
	}

	Hover();
	Torque();

	// direction change
	transform.SetScale((-m_shootingTarget.x + transform.GetPosition().x) / std::abs(m_shootingTarget.x - transform.GetPosition().x) *m_verticalScaler, m_verticalScaler);
	GetComponent<Rigidbody>()->SetPosition(m_curPos + m_hoverDisplacement);
	slerpToAngle();
	GetComponent<Rigidbody>()->SetAngle(m_currentAngle);
	GetComponent<Rigidbody>()->SetPhysicsGroup(3);
	//transform.SetPosition(m_curPos + m_hoverDisplacement); // sums up hover origin and hover displacement. Puts the object into the point.

	// SHOOTING:
	m_reload();
	m_shooter();

}

void Heli::Torque()
{
	m_targetAngle = -m_angleMod * sin(0.5*(m_lastX - transform.GetPosition().x));
}

void Heli::SetNextPos(pmath::Vec2f targ)
{
	m_nextPos = targ;
	isMoving = 0;
}

void Heli::SetShootTarget(pmath::Vec2f targ)
{
	m_shootingTarget = targ;
}

void Heli::SetMisCD_min(float min)
{
	m_missileCD_max = min;
}

void Heli::SetMisCD_max(float max)
{
	m_missileCD_max = max;
}

void Heli::SetLinearSpeed(float linear)
{
	m_linearSpeed = linear;
}

void Heli::SetHoverSpeed(float hover)
{
	m_hoverSpeed = hover;
}

void Heli::m_shooter()
{
	m_reload();
	burst();

}

void Heli::m_reload()
{
	if (!isShooting)
	{
		if (m_missileRegenTimer >= m_missileRegenTime)
		{
			++m_missileCount;
			m_missileRegenTimer = 0;
		}
		m_missileRegenTimer += m_dt;

		if (m_missileCount >= m_missileClip)
		{
			isShooting = 1;
		}
	}
}

void Heli::m_launch()
{
	if ((transform.GetPosition() - m_shootingTarget).length() < 1000)
	{
		Parent()->AddChild(new Missile(transform.GetPosition(), m_player));
	}
}

void Heli::burst()
{
	if (burstTimer <= 0)
	{
		isCool = 1;
		burstTimer = m_shootDelay;
	}

	burstTimer -= m_dt;

	if (isCool && isShooting && !isMoving)
	{
		m_launch();
		--m_missileCount;
		isCool = 0;

		if (m_missileCount <= 0)
		{
			isShooting = 0;
		}
	}

}

void Heli::takeDamage(int amount)
{
	m_health -= amount;
}


text:
.dj_gecko .mblToolBarButtonArrow {
  -moz-transform: scale(0.77, 1.05) rotate(45deg);
}
.dj_ff3 .mblToolBarButtonArrow {
  -moz-border-radius: 1px;
}
.dj_ff3 .mblToolBarButtonBody {
  -moz-border-radius: 5px;
}
.dj_ff3 .mblToolBarButtonHasLeftArrow .mblToolBarButtonBody {
  -moz-border-radius-topleft: 0;
  -moz-border-radius-bottomleft: 0;
}
.dj_ff3 .mblToolBarButtonHasRightArrow .mblToolBarButtonBody {
  -moz-border-radius-topright: 0;
  -moz-border-radius-bottomright: 0;
}
.dj_ie .mblToolBarButtonLeftArrow {
  top: 0;
  left: -2px;
  width: 13px;
  height: 31px;
  border-style: none;
  border-radius: 0;
  background-image: url(compat/arrow-button-head.png);
}
.dj_ie .mblToolBarButtonSelected .mblToolBarButtonLeftArrow {
  background-image: url(compat/arrow-button-head-sel.png);
}
.dj_ie .mblToolBarButtonRightArrow {
  top: 0;
  right: -3px;
  width: 13px;
  height: 31px;
  border-style: none;
  border-radius: 0;
  background-image: url(compat/arrow-button-right-head.png);
}
.dj_ie .mblToolBarButtonSelected .mblToolBarButtonRightArrow {
  background-image: url(compat/arrow-button-right-head-sel.png);
}
.dj_ie .mblToolBarButtonBody {
  background-image: url(compat/arrow-button-bg.png);
  background-position: left bottom;
}
.dj_ie .mblToolBarButtonBodySelected {
  background-image: url(compat/arrow-button-bg-sel.png);
}
.dj_ie .mblToolBarButtonBody table {
  margin: 0;
}
.dj_ie .mblToolBarButtonHasLeftArrow .mblToolBarButtonBody {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
.dj_ie .mblToolBarButtonHasRightArrow .mblToolBarButtonBody {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.dj_ie6 .mblToolBarButton .mblToolBarButtonBody {
  background-position: left top;
}


text:
/**
 * Integrates Redactor with Elefant's file browser dialog.
 * Requires Elefant's filemanager/util/browser handler.
 */

$.Redactor.prototype.filebrowser = function () {
	return {
		// Initialize the plugin
		init: function () {
			var button = this.button.addAfter ('imagebrowser', 'filebrowser', $.i18n ('Insert File'));
			this.button.setIcon (button, '');
			this.button.addCallback (button, this.filebrowser.open_dialog);
		},

		open_dialog: function (button, el, self, evt) {
			this.filebrowser.text = this.selection.text ();
			this.selection.save ();
			$.filebrowser ({
				callback: $.proxy (this.filebrowser.insert_file, this)
			});
		},

		insert_file: function (file) {
			this.selection.restore ();
			this.buffer.set ();

			if (file.match (/\.(jpg|png|gif)$/i)) {
				this.insert.html ('');
			} else if (file.match (/\.swf$/i)) {
				this.insert.raw ('');
			} else if (file.match (/\.(mp4|m4v|flv|f4v)$/i)) {
				this.insert.raw ('');
			} else if (file.match (/\.mp3$/i)) {
				this.insert.raw ('');
			} else {
				if (this.filebrowser.text !== undefined && this.filebrowser.text !== '') {
					var basename = this.filebrowser.text;
				} else {
					var basename = file.match (/([^\/]+)$/)[1];
				}
				this.insert.html ('' + basename + '');
			}
		}
	};
};


text:
#ifndef UnconnectedStateMachineCONSTRAINT_H_
#define UnconnectedStateMachine_H_
#include "engine/BasicConstraint.h"
#include <memory>

using namespace std;
using namespace alica;

namespace alica
{
    class ProblemDescriptor;
    class RunningPlan;
}

namespace alicaAutogenerated
{

} /* namespace alica */

#endif /* UnconnectedStateMachineCONSTRAINT_H_ */


text:
---
uid: SolidEdgeAssembly.Occurrence.ClearCapturedRelationships
summary: This method clears the relationships that have already been captured for the occurrence.
remarks:
---


text:
// The MIT License (MIT)

// Copyright (c) 2013-2021 Rapptz, ThePhD and contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "sol_test.hpp"

#include "common_classes.hpp"

#include <catch2/catch.hpp>

#include <iostream>
#include <list>
#include <memory>

inline namespace sol2_tests_usertypes_auxiliary_keys {
	struct aux { };

	struct aux_index {
		int index(sol::stack_reference) const noexcept {
			return 500;
		}
	};

} // namespace sol2_tests_usertypes_auxiliary_keys

TEST_CASE("usertype/auxiliary keys", "Make sure set and set_function on metatable / usertype<T> have feature parity and do the right thing") {
	sol::state lua;
	lua.open_libraries(sol::lib::base);

	// the index only works when set in the constructor?
	auto aux_ut = lua.new_usertype<aux>("aux");
	auto aux_index_ut = lua.new_usertype<aux_index>("aux_index");
	sol::metatable aux_mt = lua["aux"];
	sol::metatable aux_index_mt = lua["aux_index"];

	aux_ut[1] = "value-1";
	aux_mt[2] = 2;

	aux_index_ut.set_function(sol::meta_function::index, &aux_index::index);
	aux_index_ut[1] = "value-1";
	aux_index_mt[2] = 2;

	sol::optional<sol::error> maybe_error = lua.safe_script(
	     "a = aux.new()\n"
	     "ai = aux_index.new()\n"
	     "aux[3] = function () return 321 end\n"
	     "aux_index[3] = function () return 123 end\n"
	     "assert(a[1] == \"value-1\")\n"
	     "assert(a[2] == 2)\n"
	     "assert(a[3]() == 321)\n"
	     "assert(a[4] == nil)\n"
	     "assert(ai[1] == \"value-1\")\n"
	     "assert(ai[2] == 2)\n"
	     "assert(ai[3]() == 123)\n"
	     "assert(ai[4] == 500)\n",
	     &sol::script_pass_on_error);
	REQUIRE_FALSE(maybe_error.has_value());
}


text:
local Class = YokiRaidCursor.Class
local Test = YokiRaidCursor.Testing.Test
local GridTest = Class('GridTest', Test)

function GridTest:Initialize()
    self:Register(self.GetNeighbor_WithAdjacentHorizontalFrames_ReturnsNeighbor)
    self:Register(self.GetNeighbor_WithAdjacentVerticalFrames_ReturnsNeighbor)
    self:Register(self.GetNeighbor_OnVerticalEdge_ReturnsFrameAtOppositeEnd)
    self:Register(self.GetNeighbor_OnHorizontalEdge_ReturnsFrameAtOppositeEnd)

    self:SetUp()
end

function GridTest:SetUp()

    --[[
    --      f4
    --
    -- f3   f1   f2
    --
    --      f5
    --]]

    self.f1 = self:CreateMockFrame(0, 0, 100, 100)
    self.f2 = self:CreateMockFrame(200, 0, 100, 100)
    self.f3 = self:CreateMockFrame(-200, 0, 100, 100)
    self.f4 = self:CreateMockFrame(0, 200, 100, 100)
    self.f5 = self:CreateMockFrame(0, -200, 100, 100)

    local frames = { self.f1, self.f2, self.f3, self.f4, self.f5 }

    self.grid = YokiRaidCursor.Core.Grid(frames)
end

function GridTest:GetNeighbor_WithAdjacentHorizontalFrames_ReturnsNeighbor()
    local neighbor

    neighbor = self.grid:GetNeighbor(self.f1, 'Right')
    self:AssertEquals(self.f2, neighbor)

    neighbor = self.grid:GetNeighbor(self.f2, 'Left')
    self:AssertEquals(self.f1, neighbor)

    neighbor = self.grid:GetNeighbor(self.f1, 'Left')
    self:AssertEquals(self.f3, neighbor)
end

function GridTest:GetNeighbor_WithAdjacentVerticalFrames_ReturnsNeighbor()
    local neighbor

    neighbor = self.grid:GetNeighbor(self.f1, 'Up')
    self:AssertEquals(self.f4, neighbor)

    neighbor = self.grid:GetNeighbor(self.f4, 'Down')
    self:AssertEquals(self.f1, neighbor)

    neighbor = self.grid:GetNeighbor(self.f1, 'Down')
    self:AssertEquals(self.f5, neighbor)
end

function GridTest:GetNeighbor_OnVerticalEdge_ReturnsFrameAtOppositeEnd()
    local neighbor

    neighbor = self.grid:GetNeighbor(self.f4, 'Up')
    self:AssertEquals(self.f5, neighbor)
end

function GridTest:GetNeighbor_OnHorizontalEdge_ReturnsFrameAtOppositeEnd()
    local neighbor

    neighbor = self.grid:GetNeighbor(self.f3, 'Left')
    self:AssertEquals(self.f2, neighbor)
end

local test = GridTest()


text:
namespace CarDealer.Services.Models.Cars
{
   public class CarModel
    {
        public int Id { get; set; }

        public string Make { get; set; }

        public string Model { get; set; }

        public long TravelledDistance { get; set; }
    }
}


text:
/*
 * Camunda BPM REST API
 * OpenApi Spec for Camunda BPM REST API.
 *
 * The version of the OpenAPI document: 7.13.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.camunda.consulting.openapi.client.model;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.threeten.bp.OffsetDateTime;

/**
 * EventSubscriptionDto
 */
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-14T01:59:23.608853+02:00[Europe/Berlin]")
public class EventSubscriptionDto {
  public static final String SERIALIZED_NAME_ID = "id";
  @SerializedName(SERIALIZED_NAME_ID)
  private String id;

  public static final String SERIALIZED_NAME_EVENT_TYPE = "eventType";
  @SerializedName(SERIALIZED_NAME_EVENT_TYPE)
  private String eventType;

  public static final String SERIALIZED_NAME_EVENT_NAME = "eventName";
  @SerializedName(SERIALIZED_NAME_EVENT_NAME)
  private String eventName;

  public static final String SERIALIZED_NAME_EXECUTION_ID = "executionId";
  @SerializedName(SERIALIZED_NAME_EXECUTION_ID)
  private String executionId;

  public static final String SERIALIZED_NAME_PROCESS_INSTANCE_ID = "processInstanceId";
  @SerializedName(SERIALIZED_NAME_PROCESS_INSTANCE_ID)
  private String processInstanceId;

  public static final String SERIALIZED_NAME_ACTIVITY_ID = "activityId";
  @SerializedName(SERIALIZED_NAME_ACTIVITY_ID)
  private String activityId;

  public static final String SERIALIZED_NAME_CREATED_DATE = "createdDate";
  @SerializedName(SERIALIZED_NAME_CREATED_DATE)
  private OffsetDateTime createdDate;

  public static final String SERIALIZED_NAME_TENANT_ID = "tenantId";
  @SerializedName(SERIALIZED_NAME_TENANT_ID)
  private String tenantId;

  public EventSubscriptionDto id(String id) {

    this.id = id;
    return this;
  }

   /**
   * The id of the event subscription.
   * @return id
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The id of the event subscription.")

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public EventSubscriptionDto eventType(String eventType) {

    this.eventType = eventType;
    return this;
  }

   /**
   * The type of the event subscription.
   * @return eventType
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The type of the event subscription.")

  public String getEventType() {
    return eventType;
  }

  public void setEventType(String eventType) {
    this.eventType = eventType;
  }

  public EventSubscriptionDto eventName(String eventName) {

    this.eventName = eventName;
    return this;
  }

   /**
   * The name of the event this subscription belongs to as defined in the process model.
   * @return eventName
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The name of the event this subscription belongs to as defined in the process model.")

  public String getEventName() {
    return eventName;
  }

  public void setEventName(String eventName) {
    this.eventName = eventName;
  }

  public EventSubscriptionDto executionId(String executionId) {

    this.executionId = executionId;
    return this;
  }

   /**
   * The execution that is subscribed on the referenced event.
   * @return executionId
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The execution that is subscribed on the referenced event.")

  public String getExecutionId() {
    return executionId;
  }

  public void setExecutionId(String executionId) {
    this.executionId = executionId;
  }

  public EventSubscriptionDto processInstanceId(String processInstanceId) {

    this.processInstanceId = processInstanceId;
    return this;
  }

   /**
   * The process instance this subscription belongs to.
   * @return processInstanceId
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The process instance this subscription belongs to.")

  public String getProcessInstanceId() {
    return processInstanceId;
  }

  public void setProcessInstanceId(String processInstanceId) {
    this.processInstanceId = processInstanceId;
  }

  public EventSubscriptionDto activityId(String activityId) {

    this.activityId = activityId;
    return this;
  }

   /**
   * The identifier of the activity that this event subscription belongs to. This could for example be the id of a receive task.
   * @return activityId
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The identifier of the activity that this event subscription belongs to. This could for example be the id of a receive task.")

  public String getActivityId() {
    return activityId;
  }

  public void setActivityId(String activityId) {
    this.activityId = activityId;
  }

  public EventSubscriptionDto createdDate(OffsetDateTime createdDate) {

    this.createdDate = createdDate;
    return this;
  }

   /**
   * The time this event subscription was created.
   * @return createdDate
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The time this event subscription was created.")

  public OffsetDateTime getCreatedDate() {
    return createdDate;
  }

  public void setCreatedDate(OffsetDateTime createdDate) {
    this.createdDate = createdDate;
  }

  public EventSubscriptionDto tenantId(String tenantId) {

    this.tenantId = tenantId;
    return this;
  }

   /**
   * The id of the tenant this event subscription belongs to. Can be `null` if the subscription belongs to no single tenant.
   * @return tenantId
  **/
  @javax.annotation.Nullable
  @ApiModelProperty(value = "The id of the tenant this event subscription belongs to. Can be `null` if the subscription belongs to no single tenant.")

  public String getTenantId() {
    return tenantId;
  }

  public void setTenantId(String tenantId) {
    this.tenantId = tenantId;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    EventSubscriptionDto eventSubscriptionDto = (EventSubscriptionDto) o;
    return Objects.equals(this.id, eventSubscriptionDto.id) &&
        Objects.equals(this.eventType, eventSubscriptionDto.eventType) &&
        Objects.equals(this.eventName, eventSubscriptionDto.eventName) &&
        Objects.equals(this.executionId, eventSubscriptionDto.executionId) &&
        Objects.equals(this.processInstanceId, eventSubscriptionDto.processInstanceId) &&
        Objects.equals(this.activityId, eventSubscriptionDto.activityId) &&
        Objects.equals(this.createdDate, eventSubscriptionDto.createdDate) &&
        Objects.equals(this.tenantId, eventSubscriptionDto.tenantId);
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, eventType, eventName, executionId, processInstanceId, activityId, createdDate, tenantId);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class EventSubscriptionDto {\n");
    sb.append("    id: ").append(toIndentedString(id)).append("\n");
    sb.append("    eventType: ").append(toIndentedString(eventType)).append("\n");
    sb.append("    eventName: ").append(toIndentedString(eventName)).append("\n");
    sb.append("    executionId: ").append(toIndentedString(executionId)).append("\n");
    sb.append("    processInstanceId: ").append(toIndentedString(processInstanceId)).append("\n");
    sb.append("    activityId: ").append(toIndentedString(activityId)).append("\n");
    sb.append("    createdDate: ").append(toIndentedString(createdDate)).append("\n");
    sb.append("    tenantId: ").append(toIndentedString(tenantId)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Plot the Best-fit Model — uvmcmcfit 0.1 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="uvmcmcfit 0.1 documentation" href="index.html" />
    <link rel="up" title="Inspecting the Model Results for XMM101" href="xmm101-inspect.html" />
    <link rel="next" title="Plot Several Acceptable Model Fits" href="xmm101-goodfits.html" />
    <link rel="prev" title="Testing Convergence" href="xmm101-convergence.html" />

Navigation

          index

          next |

          previous |

uvmcmcfit 0.1 documentation »

Examples »

XMM101: a single, unlensed galaxy »

Inspecting the Model Results for XMM101 »

Plot the Best-fit Model¶

The second step is to plot the best-fit model and make sure that the model
accurately reproduces the data.  You can do this using
<tt class="xref py py-func docutils literal">visualize.bestFit()</tt>.

Some Preliminaries¶

Caution

You must run <tt class="xref py py-func docutils literal">visualize.bestFit()</tt> from inside a CASA terminal OR you
must install MIRIAD and add the following line to config.yaml:

UseMiriad: True

Note

To run <tt class="xref py py-func docutils literal">visualize.bestFit()</tt> from inside CASA, follow these steps

Install casa-python.  This
makes it easy to install custom python packages in CASA
using pip.

Install <tt class="docutils literal">pyyaml</tt> and <tt class="docutils literal">astropy</tt> into your CASA python environment.

<tt class="docutils literal">casa-pip install pyyaml</tt>

<tt class="docutils literal">casa-pip install astropy</tt>

Inspect $HOME/.casa/init.py and ensure that it contains a link to
the directory where <tt class="docutils literal">pyyaml</tt> and <tt class="docutils literal">astropy</tt> were installed.  In
my case, the file already had the following:

import site
site.addsitedir(“/Users/rbussman/.casa/lib/python2.7/site-packages”)

So, I had to add the following lines:

site.addsitedir(“/Users/rbussman/.casa/lib/python/site-packages”)
site.addsitedir(“/Users/rbussman/python/uvmcmcfit”)

This allowed CASA to recognize that <tt class="docutils literal">pyyaml</tt> and <tt class="docutils literal">uvmcmcfit</tt>
were installed.  You may have placed <tt class="docutils literal">uvmcmcfit</tt> in a different
directory, so modify these instructions accordingly.

Note

To install MIRIAD on Mac, try the MIRIAD MacPorts page

Caution

If you use MIRIAD to make images of the best-fit model, you must create a
special cshell script called image.csh.  This file should contain the
instructions needed for MIRIAD to invert and deconvolve the simulated
visibilities from the best-fit model.

The Simplest Best-fit Plot¶

Generating a simple plot of the best-fit model should be straightforward:

import visualize
visualize.bestFit()

If you run this routine in CASA, you will enter an interactive cleaning
session.

Note

See this ALMA tutorial
for help on interactive cleaning.

After the cleaning session finishes, two plots will be produced like
the ones shown below.

Left panel: ALMA 870um imaging of XMM101 (red contours, starting at
+/-3-sigma and increasing by factors of sqrt(2)) overlaid on the best-fit model
from <tt class="docutils literal">uvmcmcfit</tt> (grayscale).  The half-power shape of the source <tt class="docutils literal">Source0</tt>
in this case, is shown by a magenta ellipse.  The shape of the synthesized beam
is represented by the hatched black ellipse.

Right panel: Same as left panel, but showing the residual image after
subtracting the best-fit model simulated visibilities from the observed
visibilities.  White and black contours trace positive and negative contours,
respectively.

In this case, the model provides a good fit.  There is evidence that the source
is elongated in a direction perpendicular to the semi-major axis of the
synthesized beam.

Comparison to Alternative Imaging¶

You can also compare the best-fit model to an image at an alternative
wavelength (e.g., to compare lens properties with an optical or near-IR image
of the lens).  Do this by adding the following keyword:

visualize.bestFit(showOptical=True)

You should get the same results as above, but with an additional plot showing
the comparison with the alternative image.  Below is an example comparing the
ALMA 870um imaging and best-fit model with HST F110W imaging.

Additional Options¶

You can turn off interactive cleaning in CASA:

visualize.bestFit(interactive=False)

<tt class="xref py py-func docutils literal">visualize.bestFit()</tt> produces a large number of intermediate stage files
that are automatically deleted as the last step in the program.  These can
sometimes be useful for debugging.  To stop the program from automatically
deleting all intermediate files, use the following option:

visualize.bestFit(cleanup=False)

Table Of Contents

Plot the Best-fit Model

Some Preliminaries

The Simplest Best-fit Plot

Comparison to Alternative Imaging

Additional Options

Previous topic

Testing Convergence

Next topic

Plot Several Acceptable Model Fits

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

uvmcmcfit 0.1 documentation »

Examples »

XMM101: a single, unlensed galaxy »

Inspecting the Model Results for XMM101 »

        © Copyright 2014, Shane Bussmann.
      Created using Sphinx 1.2.2.


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize">

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ListView
            android:id="@+id/left_drawer"
            android:layout_width="280dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp"
            android:background="#111"/>
    </android.support.v4.widget.DrawerLayout>
</FrameLayout>


text:
pymatgen.io.qchem package
=========================

Subpackages
-----------

.. toctree::

Submodules
----------

.. toctree::

   pymatgen.io.qchem.inputs
   pymatgen.io.qchem.outputs
   pymatgen.io.qchem.sets
   pymatgen.io.qchem.utils

Module contents
---------------

.. automodule:: pymatgen.io.qchem
    :members:
    :undoc-members:
    :show-inheritance:


text:
namespace Toggl.Core.UI.Helper
{
    public enum UpcomingEventsOption
    {
        Disabled,
        WhenEventStarts,
        FiveMinutes,
        TenMinutes,
        FifteenMinutes,
        ThirtyMinutes,
        OneHour
    }
}


text:
<?php

namespace Magento\ProductAlert\Controller\Unsubscribe;

use Magento\ProductAlert\Controller\Unsubscribe as UnsubscribeController;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\NoSuchEntityException;

class Stock extends UnsubscribeController
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     */
    public function __construct(
        Context $context,
        CustomerSession $customerSession,
        ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $customerSession);
    }

    /**
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        $productId = (int)$this->getRequest()->getParam('product');
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$productId) {
            $resultRedirect->setPath('/');
            return $resultRedirect;
        }

        try {
            $product = $this->productRepository->getById($productId);
            if (!$product->isVisibleInCatalog()) {
                throw new NoSuchEntityException();
            }

            $model = $this->_objectManager->create('Magento\ProductAlert\Model\Stock')
                ->setCustomerId($this->customerSession->getCustomerId())
                ->setProductId($product->getId())
                ->setWebsiteId(
                    $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')
                        ->getStore()
                        ->getWebsiteId()
                )
                ->loadByParam();
            if ($model->getId()) {
                $model->delete();
            }
            $this->messageManager->addSuccess(__('You will no longer receive stock alerts for this product.'));
        } catch (NoSuchEntityException $noEntityException) {
            $this->messageManager->addError(__('The product was not found.'));
            $resultRedirect->setPath('customer/account/');
            return $resultRedirect;
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('We can\'t update the alert subscription right now.'));
        }
        $resultRedirect->setUrl($product->getProductUrl());
        return $resultRedirect;
    }
}


text:
var util = require('util');
var twitter = require('ntwitter');

var twit = new twitter({
  consumer_key: 'hXTkQoAx9NUlW2DfMUOCQ',
  consumer_secret: 'gmIXIkWMc6oycGI9wBrGNXCmWFiixAU952ZDyNigQ',
  access_token_key: '15810455-kUvb1xMD3yIfzxfJQFTuOdPCk6xv8jfsFK9gY84wJ',
  access_token_secret: 'CY6y3z9bEAqHXQVP3AL6rIMWylCXYqlVELtNWWhknk'
});

twit.stream('user', {track:'nodejs'}, function(stream) {
      stream.on('data', function (data) {
        console.log(data);
      });
      stream.on('end', function (response) {
        // Handle a disconnection
      });
      stream.on('destroy', function (response) {
        // Handle a 'silent' disconnection from Twitter, no end/error event fired
      });
      // Disconnect stream after five seconds
      setTimeout(stream.destroy, 5000);
    });


text:
require "chef/provisioning/azure_driver/driver"

Chef::Provisioning.register_driver_class("azure", Chef::Provisioning::AzureDriver::Driver)


text:
# test.validate.js

> Create `test.validate.js` contents.

## Usage

```javascript
var create = require( '@stdlib/_tools/scaffold/test-validate-js' );
```

#### create( code )

Returns `test.validate.js` contents based on a code `string` or [`Buffer`][@stdlib/buffer/ctor] with options annotations.

```javascript
var code = [
    '/**',
    '* Validates function options.',
    '*',
    '* @private',
    '* @param {Object} opts - destination object',
    '* @param {Options} options - function options',
    '* @param {string} [options.sep] - separator',
    '* @returns {(Error|null)} null or an error object',
    '*/'
];
code = code.join( '\n' );

var tests = create( code );
/* returns
    'use strict';

    // MODULES //

    var tape = require( 'tape' );
    var validate = require( './../lib/validate.js' );

    // TESTS //

    tape( 'main export is a function', function test( t ) {
        t.ok( true, __filename );
        t.equal( typeof validate, 'function', 'main export is a function' );
        t.end();
    });

    tape( 'the function returns an error if not provided an object', function test( t ) {
        var values;
        var err;
        var i;

        values = [
            '5',
            5,
            NaN,
            true,
            false,
            null,
            void 0,
            [],
            function noop() {}
        ];

        for ( i = 0; i < values.length; i++ ) {
            err = validate( {}, values[i] );
            t.equal( err instanceof TypeError, true, 'returns a type error when provided '+values[i] );
        }
        t.end();
    });

    tape( 'the function returns an error if provided a `sep` option which is not a string', function test( t ) {
        var values;
        var err;
        var i;

        values = [
            5,
            true,
            false,
            void 0,
            null,
            NaN,
            [],
            {},
            function noop() {}
        ];

        for ( i = 0; i < values.length; i++ ) {
            err = validate( {}, {
                'sep': values[i]
            });
            t.equal( err instanceof TypeError, true, 'returns a type error when provided '+values[i] );
        }
        t.end();
    });

    tape( 'the function returns `null` if all options are valid', function test( t ) {
        var options;
        var opts;
        var err;

        options = {};
        opts = {
            'sep': 'beep'
        };

        err = validate( options, opts );
        t.equal( err, null, 'returns null' );

        t.deepEqual( options, opts, 'sets options' );
        t.end();
    });

    tape( 'the function ignores unrecognized/unsupported options', function test( t ) {
        var options;
        var opts;
        var err;

        options = {};
        opts = {
            'beep': true,
            'boop': 3.14,
            'foo': 'bar'
        };

        err = validate( options, opts );
        t.equal( err, null, 'returns null' );

        t.deepEqual( options, {}, 'does not set unrecognized options' );
        t.end();
    });
*/
```

## Examples

```javascript
var join = require( 'path' ).join;
var readFile = require( '@stdlib/fs/read-file' ).sync;
var create = require( '@stdlib/_tools/scaffold/test-validate-js' );

var file = readFile( join( __dirname, 'fixtures', 'validate.js.txt' ) );

console.log( create( file ) );
```

* * *

## CLI

### Usage

```bash
Usage: test-validate-js [options] [<code>]

Options:

  -h,    --help                Print this message.
  -V,    --version             Print the package version.
```

### Examples

```bash
$ test-validate-js <code>
<tests>
```

To use as a standard stream,

```bash
$ echo <code> | test-validate-js
<tests>
```

[@stdlib/buffer/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/buffer/ctor


text:
         Save Failed:
        {{ error.status }}
        /
        {{ error.statusText }}

        {{error.data.id}}
        /
        {{ error.data.message }}

        Retry


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.github.endoscope</groupId>
        <artifactId>endoscope</artifactId>
        <version>3.1.3-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>endoscope-storage-jdbc</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>endoscope-core</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>endoscope-storage-aggr</artifactId>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>endoscope-storage-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['base_url'] = 'https://evening-sierra-26626.herokuapp.com/index.php';

$config['index_page'] = '';


text:
namespace strings
{
class UniStringDFA
{
public:
  class Iterator
  {
  public:
    Iterator & Move(UniChar c);

    inline bool Accepts() const { return !Rejects() && m_pos == m_s.size(); }
    inline bool Rejects() const { return m_rejected; }

  private:
    friend class UniStringDFA;

    Iterator(UniString const & s);

    UniString const & m_s;
    size_t m_pos;
    bool m_rejected;
  };

  explicit UniStringDFA(UniString const & s);
  explicit UniStringDFA(std::string const & s);

  Iterator Begin() const;

private:
  UniString const m_s;
};
}  // namespace strings


text:
@interface MomentPhotosView ()
@property (strong,nonatomic) NSArray *photos;
@end

@implementation MomentPhotosView
-(CGFloat)configWithAVFilePhotos:(NSArray*)photos width:(CGFloat)width{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    self.photos=photos;

    CGFloat viewHeight=0;
    CGFloat photoSize=width/3.0;
    if(photos==nil || photos.count==0){
        return viewHeight;
    }

    for (NSUInteger i=0; i<self.photos.count; i++) {
        AVFile *photoFile=self.photos[i];
        UIImageView *photoImageView=[UIImageView new]; //每次滑动 TabelView都要创建很多 UIImageView  ~
        photoImageView.userInteractionEnabled=YES;

        //这里引用循环 ~
        @weakify(self)
        [photoImageView bk_whenTapped:^{
            @strongify(self)
            if([self.delegate respondsToSelector:@selector(momentPhotosView:didPhotoClickAtIndex:)]){
                [self.delegate momentPhotosView:self didPhotoClickAtIndex:i];
            }
        }];
        photoImageView.layer.borderWidth=1;
        photoImageView.layer.borderColor = [UIColor lightGrayDividerColor].CGColor;

        CGPoint origin= CGPointMake((i%3) *photoSize, (i/3) *photoSize);
        CGRect frame= CGRectMake(origin.x, origin.y, photoSize, photoSize);
        photoImageView.frame=frame;
        [self addSubview:photoImageView];

        [[ImageCacheManager sharedImageCacheManager]retrieveImageForEntity:photoFile withFormatName:kMomentThumbnailFormatName completionBlock:^(id<FICEntity> entity, NSString *formatName, UIImage *image) {

            //防止图片错位
            NSArray *cuoweiPhotos=photos;

            if(cuoweiPhotos==self.photos){
                photoImageView.image=image;
            }

        }];
    }

    NSInteger numberOfLine= photos.count/3 + (photos.count %3 >0 ? 1 : 0);
    viewHeight=numberOfLine * photoSize;
    return viewHeight;

}

@end


text:
    {% if claimStatus === 'active'%}

To be processed (54)

Actioned (26)

    {% elseif claimStatus === 'actioned' %}

To be processed (54)

Actioned (26)

    {% endif %}

{{status}}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context>

	<Resource name="jdbc/osmgress_mapnik" auth="Container"
		type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000"
		username="osmgress" password="osmgress" driverClassName="org.postgresql.Driver"
		url="jdbc:postgresql://localhost/osmgress_mapnik" />

	<Realm className="org.apache.catalina.realm.JDBCRealm"
		driverName="org.postgresql.Driver" digest="SHA-256" connectionName="osmgress"
		connectionPassword="osmgress" connectionURL="jdbc:postgresql://localhost/osmgress_mapnik"
		userTable="osmg_user" userNameCol="name" userCredCol="password"
		userRoleTable="osmg_userroles" roleNameCol="role" />

</Context>


text:
"""
============================
Sample selection in NearMiss
============================

This example illustrates the different way of selecting example in
:class:`~imblearn.under_sampling.NearMiss`.
"""

# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# License: MIT

# %%
print(__doc__)

import seaborn as sns

sns.set_context("poster")

# %% [markdown]
# We define a function allowing to make some nice decoration on the plot.

# %%

def make_plot_despine(ax):
    sns.despine(ax=ax, offset=10)
    ax.set_xlim([0, 3.5])
    ax.set_ylim([0, 3.5])
    ax.set_xticks(np.arange(0, 3.6, 0.5))
    ax.set_yticks(np.arange(0, 3.6, 0.5))
    ax.set_xlabel(r"$X_1$")
    ax.set_ylabel(r"$X_2$")
    ax.legend(loc="upper left")

# %% [markdown]
# We can start by generating some data to later illustrate the principle of
# each :class:`~imblearn.under_sampling.NearMiss` heuristic rules.

# %%
import numpy as np

rng = np.random.RandomState(18)

X_minority = np.transpose(
    [[1.1, 1.3, 1.15, 0.8, 0.8, 0.6, 0.55], [1.0, 1.5, 1.7, 2.5, 2.0, 1.2, 0.55]]
)
X_majority = np.transpose(
    [
        [2.1, 2.12, 2.13, 2.14, 2.2, 2.3, 2.5, 2.45],
        [1.5, 2.1, 2.7, 0.9, 1.0, 1.4, 2.4, 2.9],
    ]
)

# %% [mardown]
# NearMiss-1
# ----------
#
# NearMiss-1 selects samples from the majority class for which the average
# distance to some nearest neighbours is the smallest. In the following
# example, we use a 3-NN to compute the average distance on 2 specific samples
# of the majority class. Therefore, in this case the point linked by the
# green-dashed line will be selected since the average distance is smaller.

# %%
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors

fig, ax = plt.subplots(figsize=(8, 8))
ax.scatter(
    X_minority[:, 0],
    X_minority[:, 1],
    label="Minority class",
    s=200,
    marker="_",
)
ax.scatter(
    X_majority[:, 0],
    X_majority[:, 1],
    label="Majority class",
    s=200,
    marker="+",
)

nearest_neighbors = NearestNeighbors(n_neighbors=3)
nearest_neighbors.fit(X_minority)
dist, ind = nearest_neighbors.kneighbors(X_majority[:2, :])
dist_avg = dist.sum(axis=1) / 3

for positive_idx, (neighbors, distance, color) in enumerate(
    zip(ind, dist_avg, ["g", "r"])
):
    for make_plot, sample_idx in enumerate(neighbors):
        ax.plot(
            [X_majority[positive_idx, 0], X_minority[sample_idx, 0]],
            [X_majority[positive_idx, 1], X_minority[sample_idx, 1]],
            "--" + color,
            alpha=0.3,
            label=f"Avg. dist.={distance:.2f}" if make_plot == 0 else "",
        )
ax.set_title("NearMiss-1")
make_plot_despine(ax)

# %% [mardown]
# NearMiss-2
# ----------
#
# NearMiss-2 selects samples from the majority class for which the average
# distance to the farthest neighbors is the smallest. With the same
# configuration as previously presented, the sample linked to the green-dashed
# line will be selected since its distance the 3 farthest neighbors is the
# smallest.

# %%
fig, ax = plt.subplots(figsize=(8, 8))
ax.scatter(
    X_minority[:, 0],
    X_minority[:, 1],
    label="Minority class",
    s=200,
    marker="_",
)
ax.scatter(
    X_majority[:, 0],
    X_majority[:, 1],
    label="Majority class",
    s=200,
    marker="+",
)

nearest_neighbors = NearestNeighbors(n_neighbors=X_minority.shape[0])
nearest_neighbors.fit(X_minority)
dist, ind = nearest_neighbors.kneighbors(X_majority[:2, :])
dist = dist[:, -3::]
ind = ind[:, -3::]
dist_avg = dist.sum(axis=1) / 3

for positive_idx, (neighbors, distance, color) in enumerate(
    zip(ind, dist_avg, ["g", "r"])
):
    for make_plot, sample_idx in enumerate(neighbors):
        ax.plot(
            [X_majority[positive_idx, 0], X_minority[sample_idx, 0]],
            [X_majority[positive_idx, 1], X_minority[sample_idx, 1]],
            "--" + color,
            alpha=0.3,
            label=f"Avg. dist.={distance:.2f}" if make_plot == 0 else "",
        )
ax.set_title("NearMiss-2")
make_plot_despine(ax)

# %% [mardown]
# NearMiss-3
# ----------
#
# NearMiss-3 can be divided into 2 steps. First, a nearest-neighbors is used to
# short-list samples from the majority class (i.e. correspond to the
# highlighted samples in the following plot). Then, the sample with the largest
# average distance to the *k* nearest-neighbors are selected.

# %%
fig, ax = plt.subplots(figsize=(8.5, 8.5))
ax.scatter(
    X_minority[:, 0],
    X_minority[:, 1],
    label="Minority class",
    s=200,
    marker="_",
)
ax.scatter(
    X_majority[:, 0],
    X_majority[:, 1],
    label="Majority class",
    s=200,
    marker="+",
)

nearest_neighbors = NearestNeighbors(n_neighbors=3)
nearest_neighbors.fit(X_majority)

# select only the majority point of interest
selected_idx = nearest_neighbors.kneighbors(X_minority, return_distance=False)
X_majority = X_majority[np.unique(selected_idx), :]
ax.scatter(
    X_majority[:, 0],
    X_majority[:, 1],
    label="Short-listed samples",
    s=200,
    alpha=0.3,
    color="g",
)
nearest_neighbors = NearestNeighbors(n_neighbors=3)
nearest_neighbors.fit(X_minority)
dist, ind = nearest_neighbors.kneighbors(X_majority[:2, :])
dist_avg = dist.sum(axis=1) / 3

for positive_idx, (neighbors, distance, color) in enumerate(
    zip(ind, dist_avg, ["r", "g"])
):
    for make_plot, sample_idx in enumerate(neighbors):
        ax.plot(
            [X_majority[positive_idx, 0], X_minority[sample_idx, 0]],
            [X_majority[positive_idx, 1], X_minority[sample_idx, 1]],
            "--" + color,
            alpha=0.3,
            label=f"Avg. dist.={distance:.2f}" if make_plot == 0 else "",
        )
ax.set_title("NearMiss-3")
make_plot_despine(ax)

fig.tight_layout()
plt.show()


text:
#ifndef YAVE_GRAPHICS_SWAPCHAIN_SWAPCHAIN_H
#define YAVE_GRAPHICS_SWAPCHAIN_SWAPCHAIN_H

#include <yave/yave.h>

#include <yave/graphics/images/Image.h>
#include <yave/graphics/graphics.h>

#include "FrameToken.h"

#include <y/core/Vector.h>

namespace yave {

static constexpr ImageUsage SwapchainImageUsage = ImageUsage::SwapchainBit | ImageUsage::ColorBit;
using SwapchainImageView = ImageView<SwapchainImageUsage>;

class Swapchain : NonMovable {

    class SwapchainImage : public Image<SwapchainImageUsage> {
        public:
            SwapchainImage(SwapchainImage&&) = default;
            SwapchainImage& operator=(SwapchainImage&&) = default;

            ~SwapchainImage() {
                // prevents images to delete their VkImage, this is already done by the swapchain
                _image = {};
            }

        private:
            friend class Swapchain;

            SwapchainImage() = default;
    };

    struct Semaphores {
        VkSemaphore image_aquired = vk_null();
        VkSemaphore render_complete = vk_null();
        VkFence fence = vk_null();
    };

    public:
        Swapchain(VkSurfaceKHR surface);
        Swapchain(Window* window);
        ~Swapchain();

        VkSwapchainKHR vk_swapchain() const;

        const math::Vec2ui& size() const;
        usize image_count() const;

        ImageFormat color_format() const;

        const auto& images() const {
            return _images;
        }

        core::Result<FrameToken> next_frame();
        void present(const FrameToken& token, CmdBufferRecorder&& recorder, const CmdQueue& queue);

    private:
        bool is_valid() const;
        [[nodiscard]] bool reset();

        bool build_swapchain();
        void build_semaphores();
        void destroy_semaphores();

        u64 _frame_id = 0;

        math::Vec2ui _size;
        ImageFormat _color_format;

        core::Vector<SwapchainImage> _images;
        core::Vector<Semaphores> _semaphores;

        VkHandle<VkSurfaceKHR> _surface;
        VkHandle<VkSwapchainKHR> _swapchain;
};

}

#endif // YAVE_GRAPHICS_SWAPCHAIN_SWAPCHAIN_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MTHRUtility
{
    public class DbInfo:IUtility
    {
        private KeyAndValues keyAndValues;

        public DbInfo(KeyAndValues keyAndValues)
        {
            this.keyAndValues = keyAndValues;
        }
        public void Execute()
        {
            Console.WriteLine("Not impliment");
          //  Console.WriteLine("The utility {0} is executed with parameters {1}", keyAndValues.Key, keyAndValues.Values.Aggregate((current, next) => current + ", " + next));
        }
    }
}