text:
* * *

titel: Voorbeeld Resolutie die de Informatica Onderwijs Week en Uur Code ondersteunt indeling: breed nav:resources_nav

* * *

### Hieronder vindt u een voorbeeld resolutie die de informatica onderwijs week ondersteunt en de doelstellingen die door de staat en lokale wetgevers kunnen worden gebruikt.

[Huis, SENAAT, STATE, COUNTY of stad resolutie of PROCLAMATIE ###]- Aangezien de Informatica Onderwijs Week de cruciale rol belicht die informatica speelt in onze veranderende maatschappij en hoe informatica innovatie mogelijk maakt en economische kansen creëert;

[HUIS OF SENAAT RESOLUTIE ###]

[DATE]

Whereas computing technology is an integral part of culture and is transforming how people interact with each other and the world around them;

Whereas computer science is transforming industry, creating new fields of commerce, driving innovation in all fields of science, and bolstering productivity in established economic sectors;

Whereas the field of computer science underpins the information technology sector of our economy, which is a significant contributor to United States economic output;

Whereas the field of computer science is a foundational science for the digital age;

Whereas the information technology sector is uniquely positioned to help with economic recovery through the research and development of new innovations;

Whereas the outlook for computer science jobs is bright with one in every two STEM jobs in the country in computing occupations;

Whereas providing students the chance to participate in high-quality computer science activities exposes them to the rich opportunities the field offers and provides critical thinking skills that will serve them throughout their lives;

Whereas all students deserve a thorough preparation in computer science education, including access to the qualified teachers, technology, and age-appropriate curriculum needed to learn computer science at the elementary and secondary levels of education;

Whereas computer science education has challenges to address, including counting computer science classes towards high school graduation requirements, and providing professional development for computer science teachers;

Whereas participating in an Hour of Code during Computer Science Education Week can serve to demystify the field of computer science and encourage more students to take up further studies of computer science;

Whereas the field of computer science has significant equity barriers to address, including attracting more participation by females and underrepresented minorities to all levels and branches;

Whereas Grace Murray Hopper, one of the first females in the field of computer science, engineered new programming languages and pioneered standards for computer systems which laid the foundation for many advancements in computer science; and

Whereas the week of December 8, in honor of Grace Hopper's birthday, is designated as 'Computer Science Education Week': Now, therefore, be it

Resolved, That the [HOUSE OR SENATE, STATE, COUNTY, CITY OR SCHOOL BOARD] --

(1) supports the designation of Computer Science Education Week (December 8-14, 2014);

(2) encourages schools, educators, parents and policymakers to participate in Computer Science Education Week by enabling their students to participate in the Hour of Code;

(3) encourages schools, teachers, researchers, universities, business leaders and policymakers to identify mechanisms for teachers to receive cutting edge professional development to provide sustainable learning experiences in computer science at all educational levels and encourage students to be exposed to computer science concepts;

(4) encourages policymakers to remove barriers that prevent computer science classes from being counted as math or science credits toward graduation requirements;

(5) encourages opportunities, including through existing programs, for females and underrepresented minorities in computer science.


text:
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/forms';
import '@angular/http';
import '@angular/router';

// Other
import 'ng2-resource-rest';
import '@ng-bootstrap/ng-bootstrap';
import 'ng2-fullpage';
import 'ng2-slim-loading-bar';
import 'ng2-validation';
import 'ng2-webstorage';
import 'ng2-http-interceptor';
import 'ng2-rating';
import 'ag-grid/main';
import 'ag-grid-angular/main';
import 'angular2-tinymce';
import 'ng2-facebook-sdk';
import 'angular2-image-upload';
// import 'ng2-froala-editor/ng2-froala-editor';
// import 'angular2-color-picker';
// import 'ng2-highcharts';
// import 'angular2-moment';

// AngularClass
import '@angularclass/hmr';

// RxJS
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

// jQuery
import 'jquery';

// Owl Carousel 2
import 'owl.carousel';

// jQuery Color
// import 'jquery-color'; // unused

// Bootstrap
import 'bootstrap-loader';

// Bootstrap Material Design
import 'bootstrap-material-design';

// Fullpage
import 'fullpage.js';

// Autosize
import 'autosize';

// Sweet Alert 2
import 'sweetalert2';

// Froala WYSIWYG HTML Editor
// import 'froala-editor/js/froala_editor.pkgd.min';

// Highcharts
// import * as Highcharts from 'highcharts';
// (<any>window).Highcharts = Highcharts;
// // tslint:disable-next-line:no-var-requires
// require('highcharts/highcharts-more')(Highcharts);
// // tslint:disable-next-line:no-var-requires
// require('highcharts/modules/drilldown')(Highcharts);
// // tslint:disable-next-line:no-var-requires
// require('highcharts/modules/exporting')(Highcharts);
// // tslint:disable-next-line:no-var-requires
// require('highcharts/modules/funnel')(Highcharts);

// MomentJS
import 'moment';

if ('production' === ENV) {
  // Production
} else {
  // Development
}

redpajama_set_name: RedPajamaGithub


text:
namespace llvm {
  class BasicBlock;
  class Function;
  class Instruction;
  class TargetData;
  class Value;

  /// \brief Check whether an instruction is likely to be "free" when lowered.
  bool isInstructionFree(const Instruction *I, const TargetData *TD = 0);

  /// \brief Check whether a call will lower to something small.
  ///
  /// This tests checks whether calls to this function will lower to something
  /// significantly cheaper than a traditional call, often a single
  /// instruction.
  bool callIsSmall(const Function *F);

  /// \brief Utility to calculate the size and a few similar metrics for a set
  /// of basic blocks.
  struct CodeMetrics {
    /// \brief True if this function contains a call to setjmp or other functions
    /// with attribute "returns twice" without having the attribute itself.
    bool exposesReturnsTwice;

    /// \brief True if this function calls itself.
    bool isRecursive;

    /// \brief True if this function contains one or more indirect branches.
    bool containsIndirectBr;

    /// \brief True if this function calls alloca (in the C sense).
    bool usesDynamicAlloca;

    /// \brief Number of instructions in the analyzed blocks.
    unsigned NumInsts;

    /// \brief Number of analyzed blocks.
    unsigned NumBlocks;

    /// \brief Keeps track of basic block code size estimates.
    DenseMap<const BasicBlock *, unsigned> NumBBInsts;

    /// \brief Keep track of the number of calls to 'big' functions.
    unsigned NumCalls;

    /// \brief The number of calls to internal functions with a single caller.
    ///
    /// These are likely targets for future inlining, likely exposed by
    /// interleaved devirtualization.
    unsigned NumInlineCandidates;

    /// \brief How many instructions produce vector values.
    ///
    /// The inliner is more aggressive with inlining vector kernels.
    unsigned NumVectorInsts;

    /// \brief How many 'ret' instructions the blocks contain.
    unsigned NumRets;

    CodeMetrics() : exposesReturnsTwice(false), isRecursive(false),
                    containsIndirectBr(false), usesDynamicAlloca(false),
                    NumInsts(0), NumBlocks(0), NumCalls(0),
                    NumInlineCandidates(0), NumVectorInsts(0),
                    NumRets(0) {}

    /// \brief Add information about a block to the current state.
    void analyzeBasicBlock(const BasicBlock *BB, const TargetData *TD = 0);

    /// \brief Add information about a function to the current state.
    void analyzeFunction(Function *F, const TargetData *TD = 0);
  };
}

#endif


text:
namespace ExCSS
{
    public enum BorderRepeat : byte
    {
        Stretch,
        Repeat,
        Round
    }
}


text:
import csv

from oslo_config import cfg

from cloudkitty import tenant_fetcher

fake_fetcher_opts = [
    cfg.StrOpt('file',
               default='/var/lib/cloudkitty/tenants.csv',
               help='Fetcher input file.')]

cfg.CONF.register_opts(fake_fetcher_opts, 'fake_fetcher')
CONF = cfg.CONF

class FakeFetcher(tenant_fetcher.BaseFetcher):
    """Fake tenants fetcher."""

    def __init__(self):
        filename = cfg.CONF.fake_fetcher.file
        csvfile = open(filename, 'rb')
        reader = csv.DictReader(csvfile)
        self._csv = reader

    def get_tenants(self):
        return [row['id'] for row in self._csv]


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using Kudu.Contracts.Settings;
using Kudu.Contracts.Tracing;
using Kudu.Core;
using Kudu.Core.Diagnostics;
using Kudu.Core.Infrastructure;
using Kudu.Services.Infrastructure;

namespace Kudu.Services.Performance
{
    public class ProcessController : ApiController
    {
        private const string FreeSitePolicy = "Shared|Limited";

        private readonly ITracer _tracer;
        private readonly IEnvironment _environment;
        private readonly IFileSystem _fileSystem;
        private readonly IDeploymentSettingsManager _settings;

        public ProcessController(ITracer tracer,
                                 IEnvironment environment,
                                 IDeploymentSettingsManager settings,
                                 IFileSystem fileSystem)
        {
            _tracer = tracer;
            _environment = environment;
            _settings = settings;
            _fileSystem = fileSystem;
        }

        [HttpGet]
        public HttpResponseMessage GetThread(int processId, int threadId)
        {
            using (_tracer.Step("ProcessController.GetThread"))
            {
                var process = GetProcessById(processId);
                var thread = process.Threads.Cast<ProcessThread>().FirstOrDefault(t => t.Id == threadId);

                if (thread != null)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, GetProcessThreadInfo(thread, Request.RequestUri.AbsoluteUri, true));
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }
            }
        }

        [HttpGet]
        public HttpResponseMessage GetAllThreads(int id)
        {
            using (_tracer.Step("ProcessController.GetAllThreads"))
            {
                var process = GetProcessById(id);
                var results = new List<ProcessThreadInfo>();

                foreach (ProcessThread thread in process.Threads)
                {
                    results.Add(GetProcessThreadInfo(thread, Request.RequestUri.AbsoluteUri.TrimEnd('/') + '/' + thread.Id, false));
                }

                return Request.CreateResponse(HttpStatusCode.OK, results);
            }
        }

        [HttpGet]
        public HttpResponseMessage GetAllProcesses()
        {
            using (_tracer.Step("ProcessController.GetAllProcesses"))
            {
                var results = Process.GetProcesses().Select(p => GetProcessInfo(p, Request.RequestUri.AbsoluteUri.TrimEnd('/') + '/' + p.Id)).OrderBy(p => p.Name.ToLowerInvariant()).ToList();
                return Request.CreateResponse(HttpStatusCode.OK, results);
            }
        }

        [HttpGet]
        public HttpResponseMessage GetProcess(int id)
        {
            using (_tracer.Step("ProcessController.GetProcess"))
            {
                var process = GetProcessById(id);
                return Request.CreateResponse(HttpStatusCode.OK, GetProcessInfo(process, Request.RequestUri.AbsoluteUri, details: true));
            }
        }

        [HttpDelete]
        public void KillProcess(int id)
        {
            using (_tracer.Step("ProcessController.KillProcess"))
            {
                var process = GetProcessById(id);
                process.Kill(includesChildren: true, tracer: _tracer);
            }
        }

        [HttpGet]
        public HttpResponseMessage MiniDump(int id, int dumpType = 0, string format = null)
        {
            using (_tracer.Step("ProcessController.MiniDump"))
            {
                DumpFormat dumpFormat = ParseDumpFormat(format, DumpFormat.Raw);
                if (dumpFormat != DumpFormat.Raw && dumpFormat != DumpFormat.Zip)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                        String.Format(CultureInfo.CurrentCulture, Resources.Error_DumpFormatNotSupported, dumpFormat));
                }

                string sitePolicy = _settings.GetWebSitePolicy();
                if ((MINIDUMP_TYPE)dumpType == MINIDUMP_TYPE.WithFullMemory && sitePolicy.Equals(FreeSitePolicy, StringComparison.OrdinalIgnoreCase))
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                        String.Format(CultureInfo.CurrentCulture, Resources.Error_FullMiniDumpNotSupported, sitePolicy));
                }

                var process = GetProcessById(id);

                string dumpFile = Path.Combine(_environment.LogFilesPath, "minidump", "minidump.dmp");
                FileSystemHelpers.EnsureDirectory(_fileSystem, Path.GetDirectoryName(dumpFile));
                FileSystemHelpers.DeleteFileSafe(_fileSystem, dumpFile);

                try
                {
                    using (_tracer.Step(String.Format("MiniDump pid={0}, name={1}, file={2}", process.Id, process.ProcessName, dumpFile)))
                    {
                        process.MiniDump(dumpFile, (MINIDUMP_TYPE)dumpType);
                        _tracer.Trace("MiniDump size={0}", new FileInfo(dumpFile).Length);
                    }
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex);
                    FileSystemHelpers.DeleteFileSafe(_fileSystem, dumpFile);
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
                }

                if (dumpFormat == DumpFormat.Raw)
                {
                    string responseFileName = GetResponseFileName(process.ProcessName, "dmp");

                    HttpResponseMessage response = Request.CreateResponse();
                    response.Content = new StreamContent(FileStreamWrapper.OpenRead(dumpFile, _fileSystem));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = responseFileName;
                    return response;
                }
                else if (dumpFormat == DumpFormat.Zip)
                {
                    string responseFileName = GetResponseFileName(process.ProcessName, "zip");

                    HttpResponseMessage response = Request.CreateResponse();
                    response.Content = ZipStreamContent.Create(responseFileName, _tracer, zip =>
                    {
                        try
                        {
                            zip.AddFile(dumpFile, String.Empty);
                        }
                        finally
                        {
                            FileSystemHelpers.DeleteFileSafe(_fileSystem, dumpFile);
                        }

                        foreach (var fileName in new[] { "sos.dll", "mscordacwks.dll" })
                        {
                            string filePath = Path.Combine(ProcessExtensions.ClrRuntimeDirectory, fileName);
                            if (_fileSystem.File.Exists(filePath))
                            {
                                zip.AddFile(filePath, String.Empty);
                            }
                        }
                    });
                    return response;
                }
                else
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                        String.Format(CultureInfo.CurrentCulture, Resources.Error_DumpFormatNotSupported, dumpFormat));
                }
            }
        }

        [HttpGet]
        public HttpResponseMessage GCDump(int id, int maxDumpCountK = 0, string format = null)
        {
            using (_tracer.Step("ProcessController.GCDump"))
            {
                DumpFormat dumpFormat = ParseDumpFormat(format, DumpFormat.DiagSession);
                var process = GetProcessById(id);
                var ext = dumpFormat == DumpFormat.DiagSession ? "diagsession" : "gcdump";

                string dumpFile = Path.Combine(_environment.LogFilesPath, "minidump", "dump." + ext);
                FileSystemHelpers.EnsureDirectory(_fileSystem, Path.GetDirectoryName(dumpFile));
                FileSystemHelpers.DeleteFileSafe(_fileSystem, dumpFile);

                string resourcePath = GetResponseFileName(process.ProcessName, "gcdump");
                try
                {
                    using (_tracer.Step(String.Format("GCDump pid={0}, name={1}, file={2}", process.Id, process.ProcessName, dumpFile)))
                    {
                        process.GCDump(dumpFile, resourcePath, maxDumpCountK, _tracer, _settings.GetCommandIdleTimeout());
                        _tracer.Trace("GCDump size={0}", new FileInfo(dumpFile).Length);
                    }
                }
                catch (Exception ex)
                {
                    _tracer.TraceError(ex);
                    FileSystemHelpers.DeleteFileSafe(_fileSystem, dumpFile);
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
                }

                if (dumpFormat == DumpFormat.Zip)
                {
                    string responseFileName = GetResponseFileName(process.ProcessName, "zip");
                    HttpResponseMessage response = Request.CreateResponse();
                    response.Content = ZipStreamContent.Create(responseFileName, _tracer, zip =>
                    {
                        try
                        {
                            zip.AddFile(dumpFile, String.Empty);
                        }
                        finally
                        {
                            FileSystemHelpers.DeleteFileSafe(_fileSystem, dumpFile);
                        }
                    });
                    return response;
                }
                else
                {
                    string responseFileName = GetResponseFileName(process.ProcessName, ext);
                    HttpResponseMessage response = Request.CreateResponse();
                    response.Content = new StreamContent(FileStreamWrapper.OpenRead(dumpFile, _fileSystem));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                    response.Content.Headers.ContentDisposition.FileName = responseFileName;
                    return response;
                }
            }
        }

        private static string GetResponseFileName(string prefix, string ext)
        {
            var context = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);
            return String.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2:MM-dd-HH-mm-ss}.{3}", prefix, InstanceIdUtility.GetShortInstanceId(context), DateTime.UtcNow, ext);
        }

        private DumpFormat ParseDumpFormat(string format, DumpFormat defaultFormat)
        {
            if (String.IsNullOrEmpty(format))
            {
                return defaultFormat;
            }

            try
            {
                return (DumpFormat)Enum.Parse(typeof(DumpFormat), format, ignoreCase: true);
            }
            catch (Exception ex)
            {
                _tracer.TraceError(ex);

                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }

        private IEnumerable<ProcessThreadInfo> GetThreads(Process process, string href)
        {
            List<ProcessThreadInfo> threads = new List<ProcessThreadInfo>();
            foreach (ProcessThread thread in process.Threads)
            {
                threads.Add(GetProcessThreadInfo(thread, href + @"/threads/" + thread.Id));
            }

            return threads;
        }

        private ProcessThreadInfo GetProcessThreadInfo(ProcessThread thread, string href, bool details = false)
        {
            var threadInfo = new ProcessThreadInfo
            {
                Id = thread.Id,
                State = thread.ThreadState.ToString(),
                Href = new Uri(href)
            };

            if (details)
            {
                threadInfo.Process = new Uri(href.Substring(0, href.IndexOf(@"/threads/", StringComparison.OrdinalIgnoreCase)));
                threadInfo.BasePriority = SafeGetValue(() => thread.BasePriority, -1);
                threadInfo.PriorityLevel = thread.PriorityLevel.ToString();
                threadInfo.CurrentPriority = SafeGetValue(() => thread.CurrentPriority, -1);
                threadInfo.StartTime = SafeGetValue(() => thread.StartTime.ToUniversalTime(), DateTime.MinValue);
                threadInfo.TotalProcessorTime = SafeGetValue(() => thread.TotalProcessorTime, TimeSpan.FromSeconds(-1));
                threadInfo.UserProcessorTime = SafeGetValue(() => thread.UserProcessorTime, TimeSpan.FromSeconds(-1));
                threadInfo.PriviledgedProcessorTime = SafeGetValue(() => thread.PrivilegedProcessorTime, TimeSpan.FromSeconds(-1));
                threadInfo.StartAddress = "0x" + thread.StartAddress.ToInt64().ToString("X");

                if (thread.ThreadState == ThreadState.Wait)
                {
                    threadInfo.WaitReason = thread.WaitReason.ToString();
                }
                else
                {
                    threadInfo.WaitReason = "Cannot obtain wait reason unless thread is in waiting state";
                }
            }

            return threadInfo;
        }

        [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "")]
        private ProcessInfo GetProcessInfo(Process process, string href, bool details = false)
        {
            href = href.TrimEnd('/');
            if (href.EndsWith("/0", StringComparison.OrdinalIgnoreCase))
            {
                href = href.Substring(0, href.Length - 1) + process.Id;
            }

            var selfLink = new Uri(href);
            var info = new ProcessInfo
            {
                Id = process.Id,
                Name = process.ProcessName,
                Href = selfLink
            };

            if (details)
            {
                // this could fail access denied
                info.HandleCount = SafeGetValue(() => process.HandleCount, -1);
                info.ThreadCount = SafeGetValue(() => process.Threads.Count, -1);
                info.ModuleCount = SafeGetValue(() => process.Modules.Count, -1);
                info.FileName = SafeGetValue(() => process.MainModule.FileName, "N/A");

                // always return empty
                //info.Arguments = SafeGetValue(() => process.StartInfo.Arguments, "N/A");
                //info.UserName = SafeGetValue(() => process.StartInfo.UserName, "N/A");

                info.StartTime = SafeGetValue(() => process.StartTime.ToUniversalTime(), DateTime.MinValue);
                info.TotalProcessorTime = SafeGetValue(() => process.TotalProcessorTime, TimeSpan.FromSeconds(-1));
                info.UserProcessorTime = SafeGetValue(() => process.UserProcessorTime, TimeSpan.FromSeconds(-1));
                info.PrivilegedProcessorTime = SafeGetValue(() => process.PrivilegedProcessorTime, TimeSpan.FromSeconds(-1));

                info.PagedSystemMemorySize64 = SafeGetValue(() => process.PagedSystemMemorySize64, -1);
                info.NonpagedSystemMemorySize64 = SafeGetValue(() => process.NonpagedSystemMemorySize64, -1);
                info.PagedMemorySize64 = SafeGetValue(() => process.PagedMemorySize64, -1);
                info.PeakPagedMemorySize64 = SafeGetValue(() => process.PeakPagedMemorySize64, -1);
                info.WorkingSet64 = SafeGetValue(() => process.WorkingSet64, -1);
                info.PeakWorkingSet64 = SafeGetValue(() => process.PeakWorkingSet64, -1);
                info.VirtualMemorySize64 = SafeGetValue(() => process.VirtualMemorySize64, -1);
                info.PeakVirtualMemorySize64 = SafeGetValue(() => process.PeakVirtualMemorySize64, -1);
                info.PrivateMemorySize64 = SafeGetValue(() => process.PrivateMemorySize64, -1);

                info.MiniDump = new Uri(selfLink + "/dump");
                if (ProcessExtensions.SupportGCDump)
                {
                    info.GCDump = new Uri(selfLink + "/gcdump");
                }
                info.Parent = new Uri(selfLink, SafeGetValue(() => process.GetParentId(_tracer), 0).ToString());
                info.Children = SafeGetValue(() => process.GetChildren(_tracer, recursive: false), Enumerable.Empty<Process>()).Select(c => new Uri(selfLink, c.Id.ToString()));
                info.Threads = SafeGetValue(() => GetThreads(process, selfLink.ToString()), Enumerable.Empty<ProcessThreadInfo>());
            }

            return info;
        }

        private Process GetProcessById(int id)
        {
            try
            {
                return id <= 0 ? Process.GetCurrentProcess() : Process.GetProcessById(id);
            }
            catch (ArgumentException ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message));
            }
        }

        private T SafeGetValue<T>(Func<T> func, T defaultValue)
        {
            try
            {
                return func();
            }
            catch (Exception ex)
            {
                _tracer.TraceError(ex);
            }

            return defaultValue;
        }

        public enum DumpFormat
        {
            Raw,
            Zip,
            DiagSession,
        }

        public class FileStreamWrapper : DelegatingStream
        {
            private readonly string _path;
            private readonly IFileSystem _fileSystem;

            private FileStreamWrapper(string path, IFileSystem fileSystem)
                : base(fileSystem.File.OpenRead(path))
            {
                _path = path;
                _fileSystem = fileSystem;
            }

            protected override void Dispose(bool disposing)
            {
                try
                {
                    base.Dispose(disposing);
                }
                finally
                {
                    FileSystemHelpers.DeleteFileSafe(_fileSystem, _path);
                }
            }

            public static Stream OpenRead(string path, IFileSystem fileSystem)
            {
                return new FileStreamWrapper(path, fileSystem);
            }
        }
    }
}


text:
//
//  MXStrongObject.h
//  MXStrongObject
//
//  Created by longminxiang on 15/9/24.
//  Copyright © 2015年 eric. All rights reserved.
//

#import <Foundation/Foundation.h>

#define __MX_STRONG(__obj) [self mx_addStrongObject:__obj]

#define __MX_REMOVE(__obj) [__obj mx_removeStrongObjectFromOwner]

#define __MX_STRONG_ALLOC(__cls, __obj) \
__cls *__obj = [__cls new]; \
__MX_STRONG(__obj)

#define __MX_WEAK(__obj, __weakObj) __weak typeof(__obj) __weakObj = __obj

#define __MX_STRONG_ALLOC_AND_WEAK(__cls, __obj, __weakObj) \
__MX_STRONG_ALLOC(__cls, __obj); \
__MX_WEAK(__obj, __weakObj);

@interface NSObject (MXStrongObjectOwner)

/**
 *  make an object strong;
 *  the object will not release unless his owner did release once call this function.
 *
 *  @param obj could be global or local value
 */
- (void)mx_addStrongObject:(id)obj;

/**
 *  remove an object from strong manager
 *
 *  @param obj object
 */
- (void)mx_removeStrongObject:(id)obj;

@end

@interface NSObject (MXStrongObject)

/**
 *  init with the owner
 */
+ (instancetype)mx_initWithOwner:(__weak id)owner;

/**
 *  remove self from owner's strong manager
 */
- (void)mx_removeStrongObjectFromOwner;

@end


text:
//
//  AKFlute.h
//  AudioKit
//
//  Auto-generated on 5/25/15.
//  Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//

#import "AKAudio.h"
#import "AKParameter+Operation.h"

/** A physical model of a flute

 Audio output is a tone similar to a flute, using a physical model developed from Perry Cook
 */

NS_ASSUME_NONNULL_BEGIN
@interface AKFlute : AKAudio
/// Instantiates the flute with all values
/// @param frequency Frequency of the note. Updated at Control-rate. [Default Value: 440]
/// @param attackTime Time in seconds to reach full blowing pressure. [Default Value: 0.1]
/// @param releaseTime Time in seconds taken to stop blowing. [Default Value: 0.1]
/// @param airJetPressure a parameter controlling the air jet. Values should be positive, and the useful range is approximately 0.08 to 0.56. Updated at Control-rate. [Default Value: 0.2]
/// @param airJetReflection Amount of reflection in the breath jet that powers the flute. [Default Value: 0.5]
/// @param reflectionCoefficient Reflection coefficient of the breath jet. [Default Value: 0.5]
/// @param noiseAmplitude Amplitude of the noise component, about 0 to 0.5 Updated at Control-rate. [Default Value: 0.15]
/// @param amplitude Amplitude of the note, up to but not including 1. Updated at Control-rate. [Default Value: 0.5]
/// @param vibratoShape Table defining the shape of the vibrato. [Default Value: sine]
/// @param vibratoAmplitude Amplitude of the vibrato. Updated at Control-rate. [Default Value: 0]
/// @param vibratoFrequency Frequency of vibrato in Hertz. Suggested range is 0 to 12 Updated at Control-rate. [Default Value: 0]
- (instancetype)initWithFrequency:(AKParameter *)frequency
                       attackTime:(AKConstant *)attackTime
                      releaseTime:(AKConstant *)releaseTime
                   airJetPressure:(AKParameter *)airJetPressure
                 airJetReflection:(AKConstant *)airJetReflection
            reflectionCoefficient:(AKConstant *)reflectionCoefficient
                   noiseAmplitude:(AKParameter *)noiseAmplitude
                        amplitude:(AKParameter *)amplitude
                     vibratoShape:(AKTable *)vibratoShape
                 vibratoAmplitude:(AKParameter *)vibratoAmplitude
                 vibratoFrequency:(AKParameter *)vibratoFrequency;

/// Instantiates the flute with default values
- (instancetype)init;

/// Instantiates the flute with default values
+ (instancetype)flute;

/// Instantiates the flute with default values
+ (instancetype)presetDefaultFlute;

/// Instantiates the flute with a sound resembling microphone feedback
- (instancetype)initWithPresetMicFeedbackFlute;

/// Instantiates the flute with a sound resembling microphone feedback
+ (instancetype)presetMicFeedbackFlute;

/// Instantiates the flute with a sound resembling a large ship horn
- (instancetype)initWithPresetShipsHornFlute;

/// Instantiates the flute with a sound resembling a large ship horn
+ (instancetype)presetShipsHornFlute;

/// Instantiates the flute with a sci-fi type sound
- (instancetype)initWithPresetSciFiNoiseFlute;

/// Instantiates the flute with a sci-fi type sound
+ (instancetype)presetSciFiNoiseFlute;

/// Instantiates the flute with a screaming space sound
- (instancetype)initWithPresetScreamingFlute;

/// Instantiates the flute with a screaming space sound
+ (instancetype)presetScreamingFlute;

/// Frequency of the note. [Default Value: 440]
@property (nonatomic) AKParameter *frequency;

/// Set an optional frequency
/// @param frequency Frequency of the note. Updated at Control-rate. [Default Value: 440]
- (void)setOptionalFrequency:(AKParameter *)frequency;

/// Time in seconds to reach full blowing pressure. [Default Value: 0.1]
@property (nonatomic) AKConstant *attackTime;

/// Set an optional attack time
/// @param attackTime Time in seconds to reach full blowing pressure. [Default Value: 0.1]
- (void)setOptionalAttackTime:(AKConstant *)attackTime;

/// Time in seconds taken to stop blowing. [Default Value: 0.1]
@property (nonatomic) AKConstant *releaseTime;

/// Set an optional release time
/// @param releaseTime Time in seconds taken to stop blowing. [Default Value: 0.1]
- (void)setOptionalReleaseTime:(AKConstant *)releaseTime;

/// a parameter controlling the air jet. Values should be positive, and the useful range is approximately 0.08 to 0.56. [Default Value: 0.2]
@property (nonatomic) AKParameter *airJetPressure;

/// Set an optional air jet pressure
/// @param airJetPressure a parameter controlling the air jet. Values should be positive, and the useful range is approximately 0.08 to 0.56. Updated at Control-rate. [Default Value: 0.2]
- (void)setOptionalAirJetPressure:(AKParameter *)airJetPressure;

/// Amount of reflection in the breath jet that powers the flute. [Default Value: 0.5]
@property (nonatomic) AKConstant *airJetReflection;

/// Set an optional air jet reflection
/// @param airJetReflection Amount of reflection in the breath jet that powers the flute. [Default Value: 0.5]
- (void)setOptionalAirJetReflection:(AKConstant *)airJetReflection;

/// Reflection coefficient of the breath jet. [Default Value: 0.5]
@property (nonatomic) AKConstant *reflectionCoefficient;

/// Set an optional reflection coefficient
/// @param reflectionCoefficient Reflection coefficient of the breath jet. [Default Value: 0.5]
- (void)setOptionalReflectionCoefficient:(AKConstant *)reflectionCoefficient;

/// Amplitude of the noise component, about 0 to 0.5 [Default Value: 0.15]
@property (nonatomic) AKParameter *noiseAmplitude;

/// Set an optional noise amplitude
/// @param noiseAmplitude Amplitude of the noise component, about 0 to 0.5 Updated at Control-rate. [Default Value: 0.15]
- (void)setOptionalNoiseAmplitude:(AKParameter *)noiseAmplitude;

/// Amplitude of the note, up to but not including 1. [Default Value: 0.5]
@property (nonatomic) AKParameter *amplitude;

/// Set an optional amplitude
/// @param amplitude Amplitude of the note, up to but not including 1. Updated at Control-rate. [Default Value: 0.5]
- (void)setOptionalAmplitude:(AKParameter *)amplitude;

/// Table defining the shape of the vibrato. [Default Value: sine]
@property (nonatomic) AKTable *vibratoShape;

/// Set an optional vibrato shape
/// @param vibratoShape Table defining the shape of the vibrato. [Default Value: sine]
- (void)setOptionalVibratoShape:(AKTable *)vibratoShape;

/// Amplitude of the vibrato. [Default Value: 0]
@property (nonatomic) AKParameter *vibratoAmplitude;

/// Set an optional vibrato amplitude
/// @param vibratoAmplitude Amplitude of the vibrato. Updated at Control-rate. [Default Value: 0]
- (void)setOptionalVibratoAmplitude:(AKParameter *)vibratoAmplitude;

/// Frequency of vibrato in Hertz. Suggested range is 0 to 12 [Default Value: 0]
@property (nonatomic) AKParameter *vibratoFrequency;

/// Set an optional vibrato frequency
/// @param vibratoFrequency Frequency of vibrato in Hertz. Suggested range is 0 to 12 Updated at Control-rate. [Default Value: 0]
- (void)setOptionalVibratoFrequency:(AKParameter *)vibratoFrequency;

@end
NS_ASSUME_NONNULL_END


text:
require_relative '../test_helper'

describe Syphon::Source do
  before do
    Object.const_set(:TestIndex, Class.new)
    TestIndex.send :include, Syphon::Index
  end

  after do
    Object.send(:remove_const, :TestIndex)
  end

  let(:source) { TestIndex.source }

  describe "#initialize" do
    it "sets a default type" do
      source = Syphon::Source.new(TestIndex, :things_source)
      source.name.must_equal :things_source
      source.type.must_equal :test
    end

    it "sets the name and type" do
      source = Syphon::Source.new(TestIndex, :things_source, type: :custom_type)
      source.name.must_equal :things_source
      source.type.must_equal :custom_type
    end

    it "initializes the schema from the given block" do
      source = Syphon::Source.new(TestIndex, :things_source) do
        string :name, 'x'
      end
      source.schema.fields.keys.must_equal [:name]
    end
  end

  describe "#mapping" do
    it "returns the ElasticSearch mapping" do
      source = Syphon::Source.new(TestIndex, :things_source, type: :thing) do
        string :name, 'x'
      end

      source.mapping.must_equal({
        thing: {
          properties: {
            name: {
              type: :string
            },
          },
        },
      })
    end
  end

  describe "#import" do
    uses_users_table
    uses_elasticsearch

    before do
      TestIndex.class_eval do
        define_source do
          integer :id, 'id'
          string :login, 'login', stored: true
          from 'users'
        end
      end
      TestIndex.build(schema_only: true)
    end

    it "imports the data as configured by the SQL query" do
      db.query "INSERT INTO users(login) VALUES('alice')"
      source.import

      hits = client.search(index: TestIndex.index_name)['hits']['hits']
      hits.map { |doc| doc['_source']['login'] }.must_equal ['alice']
    end

    it "imports data correctly the second time" do
      db.query "INSERT INTO users(login) VALUES('alice')"
      source.import

      db.query "INSERT INTO users(login) VALUES('bob')"
      source.import

      hits = client.search(index: TestIndex.index_name)['hits']['hits']
      hits.map { |doc| doc['_source']['login'] }.sort.must_equal ['alice', 'bob']
    end

    it "uses the given index name" do
      client.indices.create(index: 'syphon_custom')
      db.query "INSERT INTO users(login) VALUES('alice')"
      source.import(index: 'syphon_custom')

      hits = client.search(index: 'syphon_custom')['hits']['hits']
      hits.map { |doc| doc['_source']['login'] }.must_equal ['alice']
    end
  end

  describe "#update" do
    uses_users_table
    uses_elasticsearch

    before do
      TestIndex.class_eval do
        define_source do
          integer :id, 'id'
          string :login, 'login', stored: true
          from 'users'
        end
      end
      TestIndex.build(schema_only: true)
    end

    it "updates the index from the database, scoping with the given conditions" do
      db.query "INSERT INTO users(login) VALUES('alice'), ('bob')"
      TestIndex.build

      hits = client.search(index: TestIndex.index_name)['hits']['hits']
      hits.map { |doc| doc['_source']['login'] }.sort.must_equal ['alice', 'bob']

      db.query "UPDATE users SET login = 'superalice' WHERE login = 'alice'"
      db.query "UPDATE users SET login = 'wonderbob' WHERE login = 'bob'"
      bob_id = db.query("SELECT id FROM users WHERE login = 'wonderbob'", as: :array).to_a[0][0]
      source.update_ids([bob_id])

      hits = client.search(index: TestIndex.index_name)['hits']['hits']
      hits.map { |doc| doc['_source']['login'] }.sort.must_equal ['alice', 'wonderbob']
    end

    it "deletes records that should no longer exist" do
      db.query "INSERT INTO users(login) VALUES('alice'), ('bob')"
      TestIndex.build

      bob_id = db.query("SELECT id FROM users WHERE login = 'bob'", as: :array).to_a[0][0]
      db.query "DELETE FROM users WHERE id = #{bob_id}"
      source.update_ids([bob_id])

      hits = client.search(index: TestIndex.index_name)['hits']['hits']
      hits.map { |doc| doc['_source']['login'] }.must_equal ['alice']
    end
  end
end


text:
using System;
using System.Text;
using csogg;

namespace csvorbis
{
	public class Info
	{
		private static int OV_EBADPACKET=-136;
		private static int OV_ENOTAUDIO=-135;
		private static string _vorbis="vorbis";
		private static int VI_TIMEB=1;
		private static int VI_FLOORB=2;
		private static int VI_RESB=3;
		private static int VI_MAPB=1;
		private static int VI_WINDOWB=1;

		public int version;
		public int channels;
		public int rate;

		// The below bitrate declarations are *hints*.
		// Combinations of the three values carry the following implications:
		//
		// all three set to the same value:
		// implies a fixed rate bitstream
		// only nominal set:
		// implies a VBR stream that averages the nominal bitrate.  No hard
		// upper/lower limit
		// upper and or lower set:
		// implies a VBR bitstream that obeys the bitrate limits. nominal
		// may also be set to give a nominal rate.
		// none set:
		//  the coder does not care to speculate.

		internal int bitrate_upper;
		internal int bitrate_nominal;
		internal int bitrate_lower;

		// Vorbis supports only short and long blocks, but allows the
		// encoder to choose the sizes

		internal int[] blocksizes=new int[2];

		// modes are the primary means of supporting on-the-fly different
		// blocksizes, different channel mappings (LR or mid-side),
		// different residue backends, etc.  Each mode consists of a
		// blocksize flag and a mapping (along with the mapping setup

		internal int modes;
		internal int maps;
		internal int times;
		internal int floors;
		internal int residues;
		internal int books;
		internal int psys;     // encode only

		internal InfoMode[] mode_param=null;

		internal int[] map_type=null;
		internal Object[] map_param=null;

		internal int[] time_type=null;
		internal Object[] time_param=null;

		internal int[] floor_type=null;
		internal Object[] floor_param=null;

		internal int[] residue_type=null;
		internal Object[] residue_param=null;

		internal StaticCodeBook[] book_param=null;

		internal PsyInfo[] psy_param=new PsyInfo[64]; // encode only

		// for block long/sort tuning; encode only
		//internal int envelopesa;
		//internal float preecho_thresh;
		//internal float preecho_clamp;

		// used by synthesis, which has a full, alloced vi
		public void init()
		{
			rate=0;
			//memset(vi,0,sizeof(vorbis_info));
		}

		public void clear()
		{
			for(int i=0;i<modes;i++){ mode_param[i]=null; }
			mode_param=null;

			for(int i=0;i<maps;i++)
			{ // unpack does the range checking
				FuncMapping.mapping_P[map_type[i]].free_info(map_param[i]);
			}
			map_param=null;

			for(int i=0;i<times;i++)
			{ // unpack does the range checking
				FuncTime.time_P[time_type[i]].free_info(time_param[i]);
			}
			time_param=null;

			for(int i=0;i<floors;i++)
			{ // unpack does the range checking
				FuncFloor.floor_P[floor_type[i]].free_info(floor_param[i]);
			}
			floor_param=null;

			for(int i=0;i<residues;i++)
			{ // unpack does the range checking
				FuncResidue.residue_P[residue_type[i]].free_info(residue_param[i]);
			}
			residue_param=null;

			// the static codebooks *are* freed if you call info_clear, because
			// decode side does alloc a 'static' codebook. Calling clear on the
			// full codebook does not clear the static codebook (that's our
			// responsibility)
			for(int i=0;i<books;i++)
			{
				// just in case the decoder pre-cleared to save space
				if(book_param[i]!=null)
				{
					book_param[i].clear();
					book_param[i]=null;
				}
			}
			//if(vi->book_param)free(vi->book_param);
			book_param=null;

			for(int i=0;i<psys;i++)
			{
				psy_param[i].free();
			}
			//if(vi->psy_param)free(vi->psy_param);
			//memset(vi,0,sizeof(vorbis_info));
		}

		// Header packing/unpacking
		int unpack_info(csBuffer opb)
		{
			version=opb.read(32);
			if(version!=0)return(-1);

			channels=opb.read(8);
			rate=opb.read(32);

			bitrate_upper=opb.read(32);
			bitrate_nominal=opb.read(32);
			bitrate_lower=opb.read(32);

			blocksizes[0]=1<<opb.read(4);
			blocksizes[1]=1<<opb.read(4);

			if((rate<1) ||
				(channels<1)||
				(blocksizes[0]<8)||
				(blocksizes[1]<blocksizes[0]) ||
				(opb.read(1)!=1))
			{
				//goto err_out; // EOP check
				clear();
				return(-1);
			}
			return(0);
			// err_out:
			// vorbis_info_clear(vi);
			// return(-1);
		}

		// all of the real encoding details are here.  The modes, books,
		// everything
		int unpack_books(csBuffer opb)
		{

			//d* codebooks
			books=opb.read(8)+1;

			if(book_param==null || book_param.Length!=books)
				book_param=new StaticCodeBook[books];
			for(int i=0;i<books;i++)
			{
				book_param[i]=new StaticCodeBook();
				if(book_param[i].unpack(opb)!=0)
				{
					//goto err_out;
					clear();
					return(-1);
				}
			}

			// time backend settings
			times=opb.read(6)+1;
			if(time_type==null || time_type.Length!=times) time_type=new int[times];
			if(time_param==null || time_param.Length!=times)
				time_param=new Object[times];
			for(int i=0;i<times;i++)
			{
				time_type[i]=opb.read(16);
				if(time_type[i]<0 || time_type[i]>=VI_TIMEB)
				{
					//goto err_out;
					clear();
					return(-1);
				}
				time_param[i]=FuncTime.time_P[time_type[i]].unpack(this, opb);
				if(time_param[i]==null)
				{
					//goto err_out;
					clear();
					return(-1);
				}
			}

			// floor backend settings
			floors=opb.read(6)+1;
			if(floor_type==null || floor_type.Length!=floors)
				floor_type=new int[floors];
			if(floor_param==null || floor_param.Length!=floors)
				floor_param=new Object[floors];

			for(int i=0;i<floors;i++)
			{
				floor_type[i]=opb.read(16);
				if(floor_type[i]<0 || floor_type[i]>=VI_FLOORB)
				{
					//goto err_out;
					clear();
					return(-1);
				}

				floor_param[i]=FuncFloor.floor_P[floor_type[i]].unpack(this,opb);
				if(floor_param[i]==null)
				{
					//goto err_out;
					clear();
					return(-1);
				}
			}

			// residue backend settings
			residues=opb.read(6)+1;

			if(residue_type==null || residue_type.Length!=residues)
				residue_type=new int[residues];

			if(residue_param==null || residue_param.Length!=residues)
				residue_param=new Object[residues];

			for(int i=0;i<residues;i++)
			{
				residue_type[i]=opb.read(16);
				if(residue_type[i]<0 || residue_type[i]>=VI_RESB)
				{
					//	goto err_out;
					clear();
					return(-1);
				}
				residue_param[i]=FuncResidue.residue_P[residue_type[i]].unpack(this,opb);
				if(residue_param[i]==null)
				{
					//	goto err_out;
					clear();
					return(-1);
				}
			}

			// map backend settings
			maps=opb.read(6)+1;
			if(map_type==null || map_type.Length!=maps)  map_type=new int[maps];
			if(map_param==null || map_param.Length!=maps)  map_param=new Object[maps];
			for(int i=0;i<maps;i++)
			{
				map_type[i]=opb.read(16);
				if(map_type[i]<0 || map_type[i]>=VI_MAPB)
				{
					//	goto err_out;
					clear();
					return(-1);
				}
				map_param[i]=FuncMapping.mapping_P[map_type[i]].unpack(this,opb);
				if(map_param[i]==null)
				{
					//    goto err_out;
					clear();
					return(-1);
				}
			}

			// mode settings
			modes=opb.read(6)+1;
			if(mode_param==null || mode_param.Length!=modes)
				mode_param=new InfoMode[modes];
			for(int i=0;i<modes;i++)
			{
				mode_param[i]=new InfoMode();
				mode_param[i].blockflag=opb.read(1);
				mode_param[i].windowtype=opb.read(16);
				mode_param[i].transformtype=opb.read(16);
				mode_param[i].mapping=opb.read(8);

				if((mode_param[i].windowtype>=VI_WINDOWB)||
					(mode_param[i].transformtype>=VI_WINDOWB)||
					(mode_param[i].mapping>=maps))
				{
					//      goto err_out;
					clear();
					return(-1);
				}
			}

			if(opb.read(1)!=1)
			{
				//goto err_out; // top level EOP check
				clear();
				return(-1);
			}

			return(0);
			// err_out:
			//  vorbis_info_clear(vi);
			//  return(-1);
		}

		// The Vorbis header is in three packets; the initial small packet in
		// the first page that identifies basic parameters, a second packet
		// with bitstream comments and a third packet that holds the
		// codebook.

		public int synthesis_headerin(Comment vc, Packet op)
		{
			csBuffer opb=new csBuffer();

			if(op!=null)
			{
				opb.readinit(op.packet_base, op.packet, op.bytes);

				// Which of the three types of header is this?
				// Also verify header-ness, vorbis
			{
				byte[] buffer=new byte[6];
				int packtype=opb.read(8);
				//memset(buffer,0,6);
				opb.read(buffer,6);
				if(buffer[0]!='v' || buffer[1]!='o' || buffer[2]!='r' ||
					buffer[3]!='b' || buffer[4]!='i' || buffer[5]!='s')
				{
					// not a vorbis header
					return(-1);
				}
				switch(packtype)
				{
					case 0x01: // least significant *bit* is read first
						if(op.b_o_s==0)
						{
							// Not the initial packet
							return(-1);
						}
						if(rate!=0)
						{
							// previously initialized info header
							return(-1);
						}
						return(unpack_info(opb));
					case 0x03: // least significant *bit* is read first
						if(rate==0)
						{
							// um... we didn't get the initial header
							return(-1);
						}
						return(vc.unpack(opb));
					case 0x05: // least significant *bit* is read first
						if(rate==0 || vc.vendor==null)
						{
							// um... we didn;t get the initial header or comments yet
							return(-1);
						}
						return(unpack_books(opb));
					default:
						// Not a valid vorbis header type
						//return(-1);
						break;
				}
			}
			}
			return(-1);
		}

		// pack side
		int pack_info(csBuffer opb)
		{
			Encoding AE = Encoding.UTF8;
			byte[] _vorbis_byt = AE.GetBytes(_vorbis);

			// preamble
			opb.write(0x01,8);
			opb.write(_vorbis_byt);

			// basic information about the stream
			opb.write(0x00,32);
			opb.write(channels,8);
			opb.write(rate,32);

			opb.write(bitrate_upper,32);
			opb.write(bitrate_nominal,32);
			opb.write(bitrate_lower,32);

			opb.write(ilog2(blocksizes[0]),4);
			opb.write(ilog2(blocksizes[1]),4);
			opb.write(1,1);
			return(0);
		}

		int pack_books(csBuffer opb)
		{
			Encoding AE = Encoding.UTF8;
			byte[] _vorbis_byt = AE.GetBytes(_vorbis);

			opb.write(0x05,8);
			opb.write(_vorbis_byt);

			// books
			opb.write(books-1,8);
			for(int i=0;i<books;i++)
			{
				if(book_param[i].pack(opb)!=0)
				{
					//goto err_out;
					return(-1);
				}
			}

			// times
			opb.write(times-1,6);
			for(int i=0;i<times;i++)
			{
				opb.write(time_type[i],16);
				FuncTime.time_P[time_type[i]].pack(this.time_param[i],opb);
			}

			// floors
			opb.write(floors-1,6);
			for(int i=0;i<floors;i++)
			{
				opb.write(floor_type[i],16);
				FuncFloor.floor_P[floor_type[i]].pack(floor_param[i],opb);
			}

			// residues
			opb.write(residues-1,6);
			for(int i=0;i<residues;i++)
			{
				opb.write(residue_type[i],16);
				FuncResidue.residue_P[residue_type[i]].pack(residue_param[i],opb);
			}

			// maps
			opb.write(maps-1,6);
			for(int i=0;i<maps;i++)
			{
				opb.write(map_type[i],16);
				FuncMapping.mapping_P[map_type[i]].pack(this,map_param[i],opb);
			}

			// modes
			opb.write(modes-1,6);
			for(int i=0;i<modes;i++)
			{
				opb.write(mode_param[i].blockflag,1);
				opb.write(mode_param[i].windowtype,16);
				opb.write(mode_param[i].transformtype,16);
				opb.write(mode_param[i].mapping,8);
			}
			opb.write(1,1);
			return(0);
			//err_out:
			//return(-1);
		}

		//  static void v_writestring(csBuffer o, byte[] s){
		//    int i=0;
		//    while(s[i]!=0){
		//      o.write(s[i++],8);
		//    }
		//  }

		//  static void v_readstring(csBuffer o, byte[] buf, int bytes){
		//    int i=0
		//    while(bytes--!=0){
		//      buf[i++]=o.read(8);
		//    }
		//  }

		//  private csBuffer opb_blocksize=new csBuffer();
		public int blocksize(Packet op)
		{
			//codec_setup_info     *ci=vi->codec_setup;
			csBuffer opb=new csBuffer();
			//    synchronized(opb_blocksize){
			int mode;

			opb.readinit(op.packet_base, op.packet, op.bytes);

			/* Check the packet type */
			if(opb.read(1)!=0)
			{
				/* Oops.  This is not an audio data packet */
				return(OV_ENOTAUDIO);
			}
		{
			int modebits=0;
			int v=modes;
			while(v>1)
			{
				modebits++;
				v = (int)((uint)v >> 1);
			}

			/* read our mode and pre/post windowsize */
			mode=opb.read(modebits);
		}
			if(mode==-1)return(OV_EBADPACKET);
			return(blocksizes[mode_param[mode].blockflag]);
			//    }
		}

		private static int ilog2(int v)
		{
			int ret=0;
			while(v>1)
			{
				ret++;
				v = (int)((uint)v >> 1);
			}
			return(ret);
		}

		public String toString()
		{
			return "version:"+ version.ToString() +
				", channels:"+ channels.ToString() +
				", rate:"+ rate.ToString() +
				", bitrate:"+ bitrate_upper.ToString() +","+
				bitrate_nominal.ToString() +","+
				bitrate_lower.ToString();
		}
	}
}


text:
layout: archive
permalink:
title: "Art"
excerpt: ""
image:
  feature:
---

<div class="tiles">
{% for post in site.categories.art %}
	{% include post-grid.html %}
{% endfor %}
</div><!-- /.tiles -->


text:
package com.projectplace.android.syncmanager.sample.models;

public class Item {
    private String mName;

    public Item(String name) {
        mName = name;
    }

    public String getName() {
        return mName;
    }
}


text:
/**
* @file PopulationMember.hpp
* @brief File in which the PopulationMember structure is defined.
*/
#ifndef CLUSTERER_BACKEND_POPULATION_MEMBER_HPP
#define CLUSTERER_BACKEND_POPULATION_MEMBER_HPP

// standard headers

// external headers

// internal headers

/**
* @namespace clusterer
* @brief The namespace clusterer is the main namespace of the clusterer project.
*/
namespace clusterer
{

/**
* @namespace backend
* @brief The namespace backend is the namespace for all backend components of the
* project.
*/
namespace backend
{

/**
* @struct PopulationMember
* @brief A member of a clustering population.
* @tparam Encoding The Encoding used.
*/
template<class Encoding, class FitnessType>
struct PopulationMember
{
    /**
    * @var populationEncoding
    * @brief The encoding of a clusterer solution.
    */
    Encoding populationEncoding;

    /**
    * @var fitnessValue
    * @brief The fitness value of the encoding.
    */
    FitnessType fitnessValue;

    /**
    * @var modified
    * @brief A boolean flag that determines whether or not a modification took place during an iteration.
    */
    bool modified;
};

}
}

/**
* @namespace clb
* @brief The namespace clb is a namespace alias for the namespace clusterer::backend.
*/
namespace clb = clusterer::backend;

#endif


text:
curecoin-qt: Qt5 GUI for Curecoin
================================

Build instructions
===================

##Debian
-------

First, make sure that the required packages for Qt5 development of your
distribution are installed, for Debian and Ubuntu these are:

This involves downloading the source, meeting the dependencies, compiling the code, and then installing the resulting software.

git clone https://github.com/cygnusxi/CurecoinSource.git

##FOR THE GUI CLIENT:

sudo apt-get install qt5-default qt5-qmake qtbase5-dev-tools qttools5-dev-tools libboost-dev libboost-system-dev libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev libssl-dev libminiupnpc-dev libdb5.3++-dev dh-make build-essential

From the main directory, run the following:

qmake && make

sudo make install

Alternatively, don't run that command and just place the binary wherever you want.

##FOR THE HEADLESS CURECOIND:

sudo apt-get install libboost-all-dev libqrencode-dev libssl-dev libdb5.3-dev libdb5.3++-dev libminiupnpc-dev dh-make build-essential
cd src/ && mkdir obj/ && make -f makefile.unix

sudo make

install

Alternatively, don't run that command and just place the binary wherever you want.
libdb4.8 should also work if libdb5.1 is too high a version for you. Newer versions of Linux will need libdb5.3++-dev

Alternatively, install `Qt Creator`_ and open the `curecoin-qt.pro` file.

An executable named `curecoin-qt` will be built.

.. _`Qt Creator`: http://qt.nokia.com/downloads/

##Windows
--------

Windows build instructions:

- Download the `Qt Windows SDK`_ and install it. You don't need the Symbian stuff, just the desktop Qt.

- Download and extract the `dependencies archive`_  [#]_, or compile openssl, boost and dbcxx yourself.

- Copy the contents of the folder "deps" to "X:\\QtSDK\\mingw", replace X:\\ with the location where you installed the Qt SDK. Make sure that the contents of "deps\\include" end up in the current "include" directory.

- Open the bitcoin-qt.pro file in Qt Creator and build as normal (ctrl-B)

.. _`Qt Windows SDK`: http://qt.nokia.com/downloads/sdk-windows-cpp
.. _`dependencies archive`: https://download.visucore.com/bitcoin/qtgui_deps_1.zip
.. [#] PGP signature: https://download.visucore.com/bitcoin/qtgui_deps_1.zip.sig (signed with RSA key ID `610945D0`_)
.. _`610945D0`: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x610945D0

##Mac OS X
--------

- Download and install the `Qt Mac OS X SDK`_. It is recommended to also install Apple's Xcode with UNIX tools.

- Download and install `MacPorts`_.

- Execute the following commands in a terminal to get the dependencies:

::

	sudo port selfupdate
	sudo port install boost db48 miniupnpc

- Open the bitcoin-qt.pro file in Qt Creator and build as normal (cmd-B)

.. _`Qt Mac OS X SDK`: http://qt.nokia.com/downloads/sdk-mac-os-cpp
.. _`MacPorts`: http://www.macports.org/install.php

Build configuration options
============================

UPnP port forwarding
---------------------

To use UPnP for port forwarding behind a NAT router (recommended, as more connections overall allow for a faster and more stable curecoin experience), pass the following argument to qmake:

::

    qmake "USE_UPNP=1"

(in **Qt Creator**, you can find the setting for additional qmake arguments under "Projects" -> "Build Settings" -> "Build Steps", then click "Details" next to **qmake**)

This requires miniupnpc for UPnP port mapping.  It can be downloaded from
http://miniupnp.tuxfamily.org/files/.  UPnP support is not compiled in by default.

Set USE_UPNP to a different value to control this:

+------------+--------------------------------------------------------------------------+
| USE_UPNP=- | no UPnP support, miniupnpc not required;                                 |
+------------+--------------------------------------------------------------------------+
| USE_UPNP=0 | (the default) built with UPnP, support turned off by default at runtime; |
+------------+--------------------------------------------------------------------------+
| USE_UPNP=1 | build with UPnP support turned on by default at runtime.                 |
+------------+--------------------------------------------------------------------------+

Notification support for recent (k)ubuntu versions
---------------------------------------------------

To see desktop notifications on (k)ubuntu versions starting from 10.04, enable usage of the
FreeDesktop notification interface through DBUS using the following qmake option:

::

    qmake "USE_DBUS=1"

Generation of QR codes
-----------------------

libqrencode may be used to generate QRCode images for payment requests.
It can be downloaded from http://fukuchi.org/works/qrencode/index.html.en, or installed via your package manager. Pass the USE_QRCODE
flag to qmake to control this:

+--------------+--------------------------------------------------------------------------+
| USE_QRCODE=0 | (the default) No QRCode support - libarcode not required                 |
+--------------+--------------------------------------------------------------------------+
| USE_QRCODE=1 | QRCode support enabled                                                   |
+--------------+--------------------------------------------------------------------------+

Berkely DB version warning
==========================

A warning for people using the *static binary* version of curecoin on a Linux/UNIX-ish system (tl;dr: **Berkely DB databases are not forward compatible**).

The static binary version of curecoin is linked against libdb4.8 (see also `this Debian issue`_).

Now the nasty thing is that databases from 5.X are not compatible with 4.X.

If the globally installed development package of Berkely DB installed on your system is 5.X, any source you
build yourself will be linked against that. The first time you run with a 5.X version the database will be upgraded,
and 4.X cannot open the new format. This means that you cannot go back to the old statically linked version without
significant hassle!

.. _`this Debian issue`: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=621425


text:
package my.com.codeplay.android_demo;

import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Tham on 04/08/2017.
 */

public class TermsOfUseFragment extends Fragment {
    private TextView tvCopyright;

    public static TermsOfUseFragment newInstance() {
        TermsOfUseFragment fragment = new TermsOfUseFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_terms_of_use, container, false);

        tvCopyright = (TextView) view.findViewById(R.id.copyright);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        String versionName = "";

        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).clearNavSelection();

            try {
                versionName = " v" + getActivity().getPackageManager()
                        .getPackageInfo(getActivity().getPackageName(), 0).versionName;
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }

        tvCopyright.setText(getString(R.string.copyright, versionName));
    }
}


text:
#import "APHCustomSurveyQuestionViewController.h"
#import "APHMoodSurveyIntroStepViewController.h"
#import "APHLocalization.h"

static NSInteger const doneButtonYOffset = 20;
static NSInteger const kMaximumNumberOfCharacters = 90;

@interface APHCustomSurveyQuestionViewController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *characterCounterLabel;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpaceConstraint;
@property  (nonatomic, assign) CGFloat savedContainerSpacing;
@end

@implementation APHCustomSurveyQuestionViewController

- (void)viewDidLoad {
    [super viewDidLoad];

        self.edgesForExtendedLayout = UIRectEdgeNone;

    self.title = NSLocalizedStringWithDefaultValue(@"APH_MOOD_SURVEY_CUSTOM_TITLE", nil, APHLocaleBundle(),@"Custom Daily Question", @"Title for Custom Mood survey question");

    [self.textView setDelegate:self];

    [self.view setBackgroundColor:[UIColor whiteColor]];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillEmerge:) name:UIKeyboardWillShowNotification object:nil];

}

- (void)viewWillAppear:(BOOL) __unused animated {
    [super viewWillAppear:animated];

    APCAppDelegate * delegate = (APCAppDelegate*)[UIApplication sharedApplication].delegate;

    NSString *customQuestion = delegate.dataSubstrate.currentUser.customSurveyQuestion;

    if (customQuestion != nil) {
        self.textView.text = customQuestion;
        self.characterCounterLabel.text = [NSString     stringWithFormat:@"%lu / %lu", (unsigned long)self.textView.text.length, (unsigned long)kMaximumNumberOfCharacters];
    }

}

#pragma  mark  -  Text View Delegate Methods

- (BOOL)textView:(UITextView *) __unused textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString *updatedText = [self.textView.text stringByReplacingCharactersInRange:range withString:text];

    BOOL shouldChangeText = NO;

    if (updatedText.length <= kMaximumNumberOfCharacters) {
        shouldChangeText = YES;

        self.characterCounterLabel.text = [NSString stringWithFormat:@"%lu / %lu", (unsigned long)updatedText.length, (unsigned long)kMaximumNumberOfCharacters];
    }

    return shouldChangeText;
}

- (void)textViewDidEndEditing:(UITextView *)textView {

    APCAppDelegate * delegate = (APCAppDelegate*)[UIApplication sharedApplication].delegate;
    delegate.dataSubstrate.currentUser.customSurveyQuestion = textView.text;

    if ([textView.text isEqualToString:@""]) {
        delegate.dataSubstrate.currentUser.customSurveyQuestion = nil;
    }

}

#pragma  mark  -  Keyboard Notification Methods

- (void)keyboardWillEmerge:(NSNotification *)notification
{
    CGFloat  keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;

    double   animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    self.bottomSpaceConstraint.constant = keyboardHeight - doneButtonYOffset;

    [UIView animateWithDuration:animationDuration animations:^{

        [self.view layoutIfNeeded];
    }];
}

- (IBAction)doneButtonHandler:(id) __unused sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) viewWillDisappear:(BOOL) __unused animated {
    [super viewWillDisappear:animated];
    [self.textView resignFirstResponder];
}

@end


text:
package io.grpc.internal;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;

import com.google.census.Census;
import com.google.census.CensusContextFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.MoreExecutors;

import io.grpc.Attributes;
import io.grpc.ClientInterceptor;
import io.grpc.CompressorRegistry;
import io.grpc.DecompressorRegistry;
import io.grpc.Internal;
import io.grpc.LoadBalancer;
import io.grpc.ManagedChannelBuilder;
import io.grpc.NameResolver;
import io.grpc.NameResolverProvider;
import io.grpc.PickFirstBalancerFactory;
import io.grpc.ResolvedServerInfo;
import io.grpc.ResolvedServerInfoGroup;

import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;

import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;

/**
 * The base class for channel builders.
 *
 * @param <T> The concrete type of this builder.
 */
public abstract class AbstractManagedChannelImplBuilder
        <T extends AbstractManagedChannelImplBuilder<T>> extends ManagedChannelBuilder<T> {
  private static final String DIRECT_ADDRESS_SCHEME = "directaddress";

  /**
   * An idle timeout larger than this would disable idle mode.
   */
  @VisibleForTesting
  static final long IDLE_MODE_MAX_TIMEOUT_DAYS = 30;

  /**
   * The default idle timeout.
   */
  @VisibleForTesting
  static final long IDLE_MODE_DEFAULT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(30);

  /**
   * An idle timeout smaller than this would be capped to it.
   */
  @VisibleForTesting
  static final long IDLE_MODE_MIN_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(1);

  @Nullable
  private Executor executor;
  private final List<ClientInterceptor> interceptors = new ArrayList<ClientInterceptor>();

  private final String target;

  @Nullable
  private final SocketAddress directServerAddress;

  @Nullable
  private String userAgent;

  @Nullable
  private String authorityOverride;

  @Nullable
  private NameResolver.Factory nameResolverFactory;

  @Nullable
  private LoadBalancer.Factory loadBalancerFactory;

  @Nullable
  private DecompressorRegistry decompressorRegistry;

  @Nullable
  private CompressorRegistry compressorRegistry;

  private long idleTimeoutMillis = IDLE_MODE_DEFAULT_TIMEOUT_MILLIS;

  private int maxInboundMessageSize = GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE;

  // Can be overriden by subclasses.
  @Override
  public T maxInboundMessageSize(int max) {
    checkArgument(max >= 0, "negative max");
    maxInboundMessageSize = max;
    return thisT();
  }

  protected final int maxInboundMessageSize() {
    return maxInboundMessageSize;
  }

  @Nullable
  private CensusContextFactory censusFactory;

  protected AbstractManagedChannelImplBuilder(String target) {
    this.target = Preconditions.checkNotNull(target, "target");
    this.directServerAddress = null;
  }

  /**
   * Returns a target string for the SocketAddress. It is only used as a placeholder, because
   * DirectAddressNameResolverFactory will not actually try to use it. However, it must be a valid
   * URI.
   */
  @VisibleForTesting
  static String makeTargetStringForDirectAddress(SocketAddress address) {
    try {
      return new URI(DIRECT_ADDRESS_SCHEME, "", "/" + address, null).toString();
    } catch (URISyntaxException e) {
      // It should not happen.
      throw new RuntimeException(e);
    }
  }

  protected AbstractManagedChannelImplBuilder(SocketAddress directServerAddress, String authority) {
    this.target = makeTargetStringForDirectAddress(directServerAddress);
    this.directServerAddress = directServerAddress;
    this.nameResolverFactory = new DirectAddressNameResolverFactory(directServerAddress, authority);
  }

  @Override
  public final T directExecutor() {
    return executor(MoreExecutors.directExecutor());
  }

  @Override
  public final T executor(Executor executor) {
    this.executor = executor;
    return thisT();
  }

  @Override
  public final T intercept(List<ClientInterceptor> interceptors) {
    this.interceptors.addAll(interceptors);
    return thisT();
  }

  @Override
  public final T intercept(ClientInterceptor... interceptors) {
    return intercept(Arrays.asList(interceptors));
  }

  @Override
  public final T nameResolverFactory(NameResolver.Factory resolverFactory) {
    Preconditions.checkState(directServerAddress == null,
        "directServerAddress is set (%s), which forbids the use of NameResolverFactory",
        directServerAddress);
    this.nameResolverFactory = resolverFactory;
    return thisT();
  }

  @Override
  public final T loadBalancerFactory(LoadBalancer.Factory loadBalancerFactory) {
    Preconditions.checkState(directServerAddress == null,
        "directServerAddress is set (%s), which forbids the use of LoadBalancerFactory",
        directServerAddress);
    this.loadBalancerFactory = loadBalancerFactory;
    return thisT();
  }

  @Override
  public final T decompressorRegistry(DecompressorRegistry registry) {
    this.decompressorRegistry = registry;
    return thisT();
  }

  @Override
  public final T compressorRegistry(CompressorRegistry registry) {
    this.compressorRegistry = registry;
    return thisT();
  }

  @Override
  public final T userAgent(@Nullable String userAgent) {
    this.userAgent = userAgent;
    return thisT();
  }

  @Override
  public final T overrideAuthority(String authority) {
    this.authorityOverride = checkAuthority(authority);
    return thisT();
  }

  @Override
  public final T idleTimeout(long value, TimeUnit unit) {
    checkArgument(value > 0, "idle timeout is %s, but must be positive", value);
    // We convert to the largest unit to avoid overflow
    if (unit.toDays(value) >= IDLE_MODE_MAX_TIMEOUT_DAYS) {
      // This disables idle mode
      this.idleTimeoutMillis = ManagedChannelImpl.IDLE_TIMEOUT_MILLIS_DISABLE;
    } else {
      this.idleTimeoutMillis = Math.max(unit.toMillis(value), IDLE_MODE_MIN_TIMEOUT_MILLIS);
    }
    return thisT();
  }

  /**
   * Override the default Census implementation.  This is meant to be used in tests.
   */
  @VisibleForTesting
  @Internal
  public T censusContextFactory(CensusContextFactory censusFactory) {
    this.censusFactory = censusFactory;
    return thisT();
  }

  @VisibleForTesting
  final long getIdleTimeoutMillis() {
    return idleTimeoutMillis;
  }

  /**
   * Verifies the authority is valid.  This method exists as an escape hatch for putting in an
   * authority that is valid, but would fail the default validation provided by this
   * implementation.
   */
  protected String checkAuthority(String authority) {
    return GrpcUtil.checkAuthority(authority);
  }

  @Override
  public ManagedChannelImpl build() {
    ClientTransportFactory transportFactory = buildTransportFactory();
    if (authorityOverride != null) {
      transportFactory = new AuthorityOverridingTransportFactory(
        transportFactory, authorityOverride);
    }
    NameResolver.Factory nameResolverFactory = this.nameResolverFactory;
    if (nameResolverFactory == null) {
      // Avoid loading the provider unless necessary, as a way to workaround a possibly-costly
      // and poorly optimized getResource() call on Android. If any other piece of code calls
      // getResource(), then this shouldn't be a problem unless called on the UI thread.
      nameResolverFactory = NameResolverProvider.asFactory();
    }
    return new ManagedChannelImpl(
        target,
        // TODO(carl-mastrangelo): Allow clients to pass this in
        new ExponentialBackoffPolicy.Provider(),
        nameResolverFactory,
        getNameResolverParams(),
        firstNonNull(loadBalancerFactory, PickFirstBalancerFactory.getInstance()),
        transportFactory,
        firstNonNull(decompressorRegistry, DecompressorRegistry.getDefaultInstance()),
        firstNonNull(compressorRegistry, CompressorRegistry.getDefaultInstance()),
        GrpcUtil.TIMER_SERVICE, GrpcUtil.STOPWATCH_SUPPLIER, idleTimeoutMillis,
        executor, userAgent, interceptors,
        firstNonNull(censusFactory,
            firstNonNull(Census.getCensusContextFactory(), NoopCensusContextFactory.INSTANCE)));
  }

  /**
   * Subclasses should override this method to provide the {@link ClientTransportFactory}
   * appropriate for this channel. This method is meant for Transport implementors and should not
   * be used by normal users.
   */
  protected abstract ClientTransportFactory buildTransportFactory();

  /**
   * Subclasses can override this method to provide additional parameters to {@link
   * NameResolver.Factory#newNameResolver}. The default implementation returns {@link
   * Attributes#EMPTY}.
   */
  protected Attributes getNameResolverParams() {
    return Attributes.EMPTY;
  }

  private static class AuthorityOverridingTransportFactory implements ClientTransportFactory {
    final ClientTransportFactory factory;
    final String authorityOverride;

    AuthorityOverridingTransportFactory(
        ClientTransportFactory factory, String authorityOverride) {
      this.factory = Preconditions.checkNotNull(factory, "factory should not be null");
      this.authorityOverride = Preconditions.checkNotNull(
        authorityOverride, "authorityOverride should not be null");
    }

    @Override
    public ConnectionClientTransport newClientTransport(SocketAddress serverAddress,
        String authority, @Nullable String userAgent) {
      return factory.newClientTransport(serverAddress, authorityOverride, userAgent);
    }

    @Override
    public void close() {
      factory.close();
    }
  }

  private static class DirectAddressNameResolverFactory extends NameResolver.Factory {
    final SocketAddress address;
    final String authority;

    DirectAddressNameResolverFactory(SocketAddress address, String authority) {
      this.address = address;
      this.authority = authority;
    }

    @Override
    public NameResolver newNameResolver(URI notUsedUri, Attributes params) {
      return new NameResolver() {
        @Override
        public String getServiceAuthority() {
          return authority;
        }

        @Override
        public void start(final Listener listener) {
          listener.onUpdate(Collections.singletonList(
              ResolvedServerInfoGroup.builder().add(new ResolvedServerInfo(address)).build()),
              Attributes.EMPTY);
        }

        @Override
        public void shutdown() {}
      };
    }

    @Override
    public String getDefaultScheme() {
      return DIRECT_ADDRESS_SCHEME;
    }
  }
}


text:
void resetCoreDataStack(CoreDataManager *manager) {
    [manager setValue:nil forKey:@"persistentStoreCoordinator"];
    [manager setValue:nil forKey:@"managedObjectContext"];
    [manager setValue:nil forKey:@"managedObjectModel"];
}

SPEC_BEGIN(CoreDataManagerTests)

describe(@"Core data stack", ^{

    CoreDataManager *manager = [CoreDataManager new];

    afterEach(^{
        resetCoreDataStack(manager);
    });

    it(@"can use in-memory store", ^{
        [manager useInMemoryStore];
        NSPersistentStore *store = [manager.persistentStoreCoordinator persistentStores][0];
        [[store.type should] equal:NSInMemoryStoreType];
    });

    it(@"uses documents directory on iphone", ^{
        [manager stub:@selector(isOSX) andReturn:theValue(NO)];
        NSPersistentStore *store = manager.persistentStoreCoordinator.persistentStores[0];
        [[store.URL.absoluteString should] containString:[manager applicationDocumentsDirectory].absoluteString];
    });

    it(@"uses application support directory on osx", ^{
        [manager stub:@selector(isOSX) andReturn:theValue(YES)];
        NSPersistentStore *store = manager.persistentStoreCoordinator.persistentStores[0];
        [[store.URL.absoluteString should] containString:[manager applicationSupportDirectory].absoluteString];
    });

    it(@"creates application support directory on OSX if needed", ^{
        [manager stub:@selector(isOSX) andReturn:theValue(YES)];
        [[NSFileManager defaultManager] removeItemAtURL:manager.applicationSupportDirectory error:nil];

        NSPersistentStore *store = [manager.persistentStoreCoordinator persistentStores][0];
        [[store.URL.absoluteString should] endWithString:@".sqlite"];
    });

});

SPEC_END


text:
/**
 * Created by ramon on 25/09/15.
 */
//mqu : {color : '#e78808', name:'Tech',      link:'http://tech.mequedouno.com',      logo: 'http://str.yeeday.net/img/cm/es/mqu/logo-mqu.png'},
"use strict";

module.exports = function(sequelize, DataTypes) {
    var Nshop = sequelize.define("Nshop", {
        shop_name   : DataTypes.STRING,
        value       : DataTypes.STRING,
        deleted     : {type:DataTypes.BOOLEAN,allowNull:false,defaultValue:false}
    },{
        classMethods : {
            associate : function(models){

            }
        }
    });
    return Nshop;
};


text:
/* Epilogue UI elements */
$epilogueScreen = $('#epilogue-screen');

$epiloguePrevButton = $('#epilogue-prev-button');
$epilogueNextButton = $('#epilogue-next-button');
$epilogueResetButton = $('#epilogue-restart-button');

/* Epilogue selection modal elements */
$epilogueSelectionModal = $('#epilogue-modal'); //the modal box
$epilogueHeader = $('#epilogue-header-text'); //the header text for the epilogue selection box
$epilogueList = $('#epilogue-list'); //the list of epilogues
$epilogueAcceptButton = $('#epilogue-modal-accept-button'); //click this button to go with the chosen ending

var textBoxDivName = "#epilogueDivBox";

var epilogueSelections = []; //references to the epilogue selection UI elements

var winStr = "You've won the game, and possibly made some friends. Who among these players did you become close with?"; //Winning the game, with endings available
var winStrNone = "You've won the game, and possibly made some friends? Unfortunately, none of your competitors are ready for a friend like you."; //Player won the game, but none of the characters have an ending written
var lossStr = "Well you lost. And you didn't manage to make any new friends. But you saw some people strip down and show off, and isn't that what life is all about?"; //Player lost the game. Currently no support for ending scenes when other players win

/* NPC chosen for epilogue */
var epilogueCharacter = -1; //the character whose epilogue is playing
var epilogueScreen = 0; //screen in the epilogue
var epilogueTextCount = 0; //current latest text box in the current screen of the epilogue

var epilogues = []; //list of epilogue data objects
var chosenEpilogue = null;

var openEpilogueTextBoxes = []; //currently open text boxes on the Epilogue screen

/************************************************************
 * Return the numerical part of a string s. E.g. "20%" -> 20
 ************************************************************/

function getNumericalPart(s){
	return parseFloat(s); //apparently I don't actually need to remove the % (or anything else) from the string before I do the conversion
}

/************************************************************
 * Return the approriate left: setting so that a text box of the specified width is centred
 * Assumes a % width
 ************************************************************/
function getCenteredPosition(width){
	var w = getNumericalPart(width); //numerical value of the width
	var left = 50 - (w/2); //centre of the text box is at the 50% position
	return left + "%";
}

/************************************************************
 * Load the Epilogue data for a character
 ************************************************************/
function loadEpilogueData(player){
    if (!players[player]) {
        return [];
    }

	var xml = players[player].xml;
	if (!xml) {return [];} //return an empty list if a character doesn't have an XML variable. (Most likely because they're the player.)

	var playerGender = players[HUMAN_PLAYER].gender;

	//get the XML tree that relates to the epilogue, for the specific player gender
	//var epXML = $($.parseXML(xml)).find('epilogue[gender="'+playerGender+'"]'); //use parseXML() so that <image> tags come through properly //IE doesn't like this

	var epilogues = [];

	$(xml).find('epilogue[gender="'+playerGender+'"],epilogue[gender="any"]').each(function() {
		//use parseXML() so that <image> tags come through properly
		//not using parseXML() because internet explorer doesn't like it

		var epilogueTitle = $(this).find("title").html().trim();

		var screens = []; //the list of screens for the epilogue

		$(this).find("screen").each(function() {
			var image = players[player].folder + $(this).attr("img").trim(); //get the full path for the screen's image
			//use an attribute rather than a tag because IE doesn't like parsing XML

			//get the information for all the text boxes
			var textBoxes = [];
			$(this).find("text").each(function() {

				//the text box's position and width
				var x = $(this).find("x").html().trim();
				var y = $(this).find("y").html().trim();
				var w = $(this).find("width").html();
				var a = $(this).find("arrow").html();

				//the width component is optional. Use a default of 20%.
				if (w) {
					w = w.trim();
				}
				if (!w || (w.length <= 0)) {
					w = "20%"; //default to text boxes having a width of 20%
				}

				//dialogue bubble arrow
				if (a) {
					a = a.trim().toLowerCase();
					if (a.length >= 1) {
						a = "arrow-" + a; //class name for the different arrows. Only use if the writer specified something.
					}
				} else {
					a = "";
				}

				//automatically centre the text box, if the writer wants that.
				if (x.toLowerCase() == "centered") {
					x = getCenteredPosition(w);
				}

				var text = $(this).find("content").html().trim(); //the actual content of the text box

				textBoxes.push({x:x, y:y, width:w, arrow:a, text:text}); //add a textBox object to the list of textBoxes
			});

			screens.push({image:image, textBoxes:textBoxes}); //add a screen object to the list of screens
		});

		if (screens.length > 0) { //if there isn't any epilogue data, don't do anything
			var epilogue = {player:player,title:epilogueTitle,screens:screens}; //epilogue object
			epilogues.push(epilogue);
		}
	});

	return epilogues;
}

/************************************************************
 * Draw Epilogue Text Box num for the current screen
 ************************************************************/
function drawEpilogueBox(num){
	if (num <= openEpilogueTextBoxes.length - 1) return; //have already drawn this box, so don't do anything
	var boxDivName = textBoxDivName+num;
	var screenData = chosenEpilogue.screens[epilogueScreen];
	var boxData = screenData.textBoxes[num];

	//make new div element
	var newEpilogueDiv = $(document.createElement('div')).attr('id', boxDivName);

	//allow the writer to use ~name~ to refer to the player
	var content = boxData.text.replace([NAME], [players[HUMAN_PLAYER].label]);

	//add the contents of the text box
	var dialogueID = 'epilogue-dialogue-'+num;
	newEpilogueDiv.after().html(
					'
' +
						'
' +
							''+content+''+
						'
' +
					'
');

	//use css to position the text box
	newEpilogueDiv.css('position', "absolute");
	newEpilogueDiv.css('left', boxData.x);
	newEpilogueDiv.css('top', boxData.y);
	newEpilogueDiv.css('width', boxData.width);
	//newEpilogueDiv

	//attach new div element to screen
	newEpilogueDiv.appendTo("#epilogue-screen");

	$('#'+dialogueID).addClass(boxData.arrow);

	//keep track of the open Epilogue Text Boxes, so they can be removed later
	openEpilogueTextBoxes.push(newEpilogueDiv);
}

/************************************************************
 * Draw all Epilogue Text Boxes from 0 to num for the current screen
 ************************************************************/
function drawEpilogueBoxesTo(num){
	//the existing text boxes are [0, openEpilogueTextBoxes.length - 1], inclusive

	//if there's too many, close the extra ones
	while (openEpilogueTextBoxes.length - 1 > num){
		var textBox = openEpilogueTextBoxes.pop();
		textBox.remove();
	}

	//if there's not enough boxes open, make the required ones
	for (var i = openEpilogueTextBoxes.length; i <= num; i++){
		drawEpilogueBox(i);
	}
}

/************************************************************
 * Clear any Epilogue Text Boxes
 ************************************************************/
function clearEpilogueBoxes(){
	while (openEpilogueTextBoxes.length > 0){
		var textBox = openEpilogueTextBoxes.pop();
		textBox.remove();
	}
}

/************************************************************
 * Add the epilogue to the Epilogue modal
 ************************************************************/

function addEpilogueEntry(epilogue){
	var num = epilogues.length; //index number of the new epilogue
	var player = players[epilogue.player]

	var nameStr = player.first+" "+player.last;
	if (player.first.length <= 0 || player.last.length <= 0){
		nameStr = player.first+player.last; //only use a space if they have both first and last names
	}

	var epilogueTitle = nameStr+": "+epilogue.title;
	var idName = 'epilogue-option-'+num;
	var clickAction = "selectEpilogue("+num+")";

	var htmlStr = '
<button onclick="'+clickAction+'">'+epilogueTitle+'</button>
';

	$epilogueList.append(htmlStr);
	epilogueSelections.push($('#'+idName));
}

/************************************************************
 * Clear the Epilogue modal
 ************************************************************/

function clearEpilogueList(){
	$epilogueHeader.html('');
	$epilogueList.html('');
	epilogues = [];
	epilogueSelections = [];
}

/************************************************************
 * The user has clicked on a button to choose a particular Epilogue
 ************************************************************/

function selectEpilogue(epNumber){
	chosenEpilogue = epilogues[epNumber]; //select the chosen epilogues
	epilogueCharacter = chosenEpilogue.player;

	for (var i = 0; i < epilogues.length; i++){
		epilogueSelections[i].removeClass("active"); //make sure no other epilogue is selected
	}
	epilogueSelections[epNumber].addClass("active"); //mark the selected epilogue as selected
	$epilogueAcceptButton.prop("disabled", false); //allow the player to accept the epilogue
}

/************************************************************
 * Show the modal for the player to choose an Epilogue, or restart the game.
 ************************************************************/
function doEpilogueModal(){

	clearEpilogueList(); //remove any already loaded epilogues
	chosenEpilogue = null; //reset any currently-chosen epilogue
	$epilogueAcceptButton.prop("disabled", true); //don't let the player accept an epilogue until they've chosen one

	//identify the winning player
	var winner = -1;
	for (var i = 0; i < players.length; i++){
		if (players[i] && !players[i].out){
			winner = i;
			break;
		}
	}

	//whether or not the human player won
	var playerWon = (winner == HUMAN_PLAYER);

	if (playerWon) { //all the epilogues are for when the player wins, so don't allow them to choose one if they lost
		//load the epilogue data for each player
		for (var i = 0; i < players.length; i++){
			var playerIEpilogues = loadEpilogueData(i);
			for (var j = 0; j < playerIEpilogues.length; j++){
				addEpilogueEntry(playerIEpilogues[j]);
				epilogues.push(playerIEpilogues[j]);
			}
		}
	}

	//are there any epilogues available for the player to see?
	var haveEpilogues = (epilogues.length >= 1); //whether or not there are any epilogues available
	$epilogueAcceptButton.css("visibility", haveEpilogues ? "visible" : "hidden");

	//decide which header string to show the player. This describes the situation.
	var headerStr = '';
	if (playerWon){
		headerStr = winStr; //player won, and there are epilogues available
		if (!haveEpilogues){
			headerStr = winStrNone; //player won, but none of the NPCs have epilogues
		}
	} else {
		headerStr = lossStr; //player lost
	}

	$epilogueHeader.html(headerStr); //set the header string
	$epilogueSelectionModal.modal("show");//show the epilogue selection modal
}

/************************************************************
 * Start the Epilogue
 ************************************************************/
function doEpilogue(){

	//just in case, clear any open text boxes
	clearEpilogueBoxes();

	epilogueScreen = 0; //reset epilogue position in case a previous epilogue played before this one
	epilogueText = 0;

	progressEpilogue(0); //initialise buttons and text boxes
	screenTransition($titleScreen, $epilogueScreen); //currently transitioning from title screen, because this is for testing
	$epilogueSelectionModal.modal("hide");
}

/************************************************************
 * Move the Epilogue forwards and backwards.
 ************************************************************/

function progressEpilogue(direction){
	//direction should be +1 to move to the next line, -1 to go to the previous line
	var screens = chosenEpilogue.screens; //the epilogue being shown
	var fullOpacity = 1;
	var disabledOpacity = 0.4;

	epilogueTextCount += direction;

	if (epilogueTextCount < 0){ //moving back, possibly to the previous screen
		epilogueScreen--;
		if (epilogueScreen < 0){ //not actually changing screen
			epilogueScreen = 0;
			epilogueTextCount = 0; //if already on the first screen, stay at the first position
		} else {
			epilogueTextCount = screens[epilogueScreen].textBoxes.length - 1; //set text box count to the final box in the new current screen
			clearEpilogueBoxes();
		}

	} else if (epilogueTextCount >= screens[epilogueScreen].textBoxes.length){ //moving forwards, possibly to the next screen
		epilogueScreen++;
		if (epilogueScreen >= screens.length){ //not actually changing screen
			epilogueScreen = screens.length - 1;
			epilogueTextCount = screens[epilogueScreen].textBoxes.length - 1;
		} else {
			epilogueTextCount = 0;
			clearEpilogueBoxes();
		}
	}

	drawEpilogueBoxesTo(epilogueTextCount); //actually draw the text boxes

	var screen = screens[epilogueScreen]; //the current screen, after the next/prev button is pressed

	var atFirst = (epilogueScreen <= 0) && (epilogueTextCount <= 0); //at the first position. disable the "previous" button
	var atLast  = (epilogueScreen >= screens.length - 1) && (epilogueTextCount >= screen.textBoxes.length - 1); //at the last position. disable the "next" button and enable the "restart" button

	//set previous/next/restart buttons properly
	$epiloguePrevButton.prop("disabled", atFirst);
	$epilogueNextButton.prop("disabled",  atLast);
	$epilogueResetButton.prop("disabled", !atLast);
	$epiloguePrevButton.css("opacity", atFirst ? disabledOpacity : fullOpacity);
	$epilogueNextButton.css("opacity", atLast  ? disabledOpacity : fullOpacity);
	$epilogueResetButton.css("visibility", atLast ? "visible" : "hidden");

	//set the background image
	var imageString = "url("+ screen.image + ")";
	//console.log("setting image string to: "+imageString);
	$epilogueScreen.css('background-image', imageString);
}