text:
use ::{ErrorCode, IndyError};
use ffi::CommandHandle;

use libc::c_char;

use std::collections::HashMap;
use std::ffi::CStr;
use std::sync::Mutex;

use futures::*;
use futures::sync::oneshot;

lazy_static! {
    static ref CALLBACKS_EMPTY: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(), IndyError>>>> = Default::default();
    static ref CALLBACKS_SLICE: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<Vec<u8>, IndyError>>>> = Default::default();
    static ref CALLBACKS_HANDLE: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<CommandHandle, IndyError>>>> = Default::default();
    static ref CALLBACKS_BOOL: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<bool, IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_SLICE: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, Vec<u8>), IndyError>>>> = Default::default();
    static ref CALLBACKS_HANDLE_USIZE: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(CommandHandle, usize), IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_STR_U64: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, String, u64), IndyError>>>> = Default::default();
    static ref CALLBACKS_STR: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<String, IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_I64: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, i64), IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_STR: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, String), IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_OPTSTR: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, Option<String>), IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_STR_STR: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, String, String), IndyError>>>> = Default::default();
    static ref CALLBACKS_STR_OPTSTR_OPTSTR: Mutex<HashMap<CommandHandle, oneshot::Sender<Result<(String, Option<String>, Option<String>), IndyError>>>> = Default::default();
}

macro_rules! cb_ec {
    ($name:ident($($cr:ident:$crt:ty),*)->$rrt:ty, $cbs:ident, $res:expr) => (
    pub fn $name() -> (sync::oneshot::Receiver<Result<$rrt, IndyError>>,
                          CommandHandle,
                          Option<extern fn(command_handle: CommandHandle, err: i32, $($crt),*)>) {
        extern fn callback(command_handle: CommandHandle, err: i32, $($cr:$crt),*) {
            let tx = {
                let mut callbacks = $cbs.lock().unwrap();
                callbacks.remove(&command_handle).unwrap()
            };

            let res = if err != 0 {
                Err(IndyError::new(ErrorCode::from(err)))
            } else {
                Ok($res)
            };

            tx.send(res).unwrap();
        }

        let (rx, command_handle) = {
            let (tx, rx) = oneshot::channel();
            let command_handle = ::utils::sequence::SequenceUtils::get_next_id();
            let mut callbacks = $cbs.lock().unwrap();
            callbacks.insert(command_handle, tx);
            (rx, command_handle)
        };
        (rx, command_handle, Some(callback))
    }
    )
}

pub struct ClosureHandler {}

impl ClosureHandler {
    cb_ec!(cb_ec()->(), CALLBACKS_EMPTY, ());

    cb_ec!(cb_ec_handle(handle:CommandHandle)->CommandHandle, CALLBACKS_HANDLE, handle);

    cb_ec!(cb_ec_handle_usize(handle:CommandHandle, u: usize)->(CommandHandle, usize), CALLBACKS_HANDLE_USIZE, (handle, u));

    cb_ec!(cb_ec_string(str1:*const c_char)->String,
           CALLBACKS_STR,
           rust_str!(str1));

    cb_ec!(cb_ec_string_i64(str1:*const c_char, num: i64)->(String, i64),
           CALLBACKS_STR_I64,
           (rust_str!(str1), num));

    cb_ec!(cb_ec_string_string(str1:*const c_char, str2:*const c_char)->(String, String),
           CALLBACKS_STR_STR,
           (rust_str!(str1), rust_str!(str2)));

    cb_ec!(cb_ec_string_opt_string(str1:*const c_char, str2:*const c_char)->(String, Option<String>),
           CALLBACKS_STR_OPTSTR,
           (rust_str!(str1), opt_rust_str!(str2)));

    cb_ec!(cb_ec_string_string_string(str1: *const c_char, str2: *const c_char, str3: *const c_char)->(String, String, String),
           CALLBACKS_STR_STR_STR,
           (rust_str!(str1), rust_str!(str2), rust_str!(str3)));

    cb_ec!(cb_ec_string_opt_string_opt_string(str1: *const c_char, str2: *const c_char, str3: *const c_char)->(String, Option<String>, Option<String>),
           CALLBACKS_STR_OPTSTR_OPTSTR,
           (rust_str!(str1), opt_rust_str!(str2), opt_rust_str!(str3)));

    cb_ec!(cb_ec_string_string_u64(str1:*const c_char, str2:*const c_char, u: u64)->(String, String, u64),
           CALLBACKS_STR_STR_U64,
           (rust_str!(str1), rust_str!(str2), u));

    cb_ec!(cb_ec_slice(data:*const u8, len:u32)->Vec<u8>, CALLBACKS_SLICE, rust_slice!(data, len).to_owned());

    cb_ec!(cb_ec_string_slice(str: *const c_char, data:*const u8, len:u32)->(String, Vec<u8>),
           CALLBACKS_STR_SLICE,
           (rust_str!(str), rust_slice!(data, len).to_owned()));

    cb_ec!(cb_ec_bool(b: bool)->bool, CALLBACKS_BOOL, b);
}

macro_rules! result_handler {
    ($name:ident($res_type:ty), $map:ident) => (
    pub fn $name(command_handle: CommandHandle,
                 err: ErrorCode,
                 rx: sync::oneshot::Receiver<Result<$res_type, IndyError>>) -> Box<dyn Future<Item=$res_type, Error= IndyError>> {
        if err != ErrorCode::Success {
            let mut callbacks = $map.lock().unwrap();
            callbacks.remove(&command_handle).unwrap();
            Box::new(future::err(IndyError::new(err)))
        } else {
            Box::new(rx
                .map_err(|_| panic!("channel error!"))
                .and_then(|res| res))
        }
    }
    )
}

pub struct ResultHandler {}

impl ResultHandler {
    result_handler!(empty(()), CALLBACKS_EMPTY);
    result_handler!(handle(CommandHandle), CALLBACKS_HANDLE);
    result_handler!(slice(Vec<u8>), CALLBACKS_SLICE);
    result_handler!(bool(bool), CALLBACKS_BOOL);
    result_handler!(str(String), CALLBACKS_STR);
    result_handler!(str_i64((String, i64)), CALLBACKS_STR_I64);
    result_handler!(handle_usize((CommandHandle, usize)), CALLBACKS_HANDLE_USIZE);
    result_handler!(str_slice((String, Vec<u8>)), CALLBACKS_STR_SLICE);
    result_handler!(str_str((String, String)), CALLBACKS_STR_STR);
    result_handler!(str_optstr((String, Option<String>)), CALLBACKS_STR_OPTSTR);
    result_handler!(str_optstr_optstr((String, Option<String>, Option<String>)), CALLBACKS_STR_OPTSTR_OPTSTR);
    result_handler!(str_str_str((String, String, String)), CALLBACKS_STR_STR_STR);
    result_handler!(str_str_u64((String, String, u64)), CALLBACKS_STR_STR_U64);
}

#[cfg(test)]
mod test {
    use super::*;

    use std::ffi::CString;
    use std::ptr::null;

    #[test]
    fn cb_ec_slice() {
        let (receiver, command_handle, cb) = ClosureHandler::cb_ec_slice();

        let test_vec: Vec<u8> = vec![250, 251, 252, 253, 254, 255];
        let callback = cb.unwrap();
        callback(command_handle, 0, test_vec.as_ptr(), test_vec.len() as u32);

        let slice1 = receiver.wait().unwrap().unwrap();
        assert_eq!(test_vec, slice1);
    }

    #[test]
    fn ec_string_opt_string_null() {
        let (receiver, command_handle, cb) = ClosureHandler::cb_ec_string_opt_string();

        let callback = cb.unwrap();
        callback(command_handle, 0, CString::new("This is a test").unwrap().as_ptr(), null());

        let (str1, str2) = receiver.wait().unwrap().unwrap();
        assert_eq!(str1, "This is a test".to_string());
        assert_eq!(str2, None);
    }

    #[test]
    fn ec_string_opt_string_some() {
        let (receiver, command_handle, cb) = ClosureHandler::cb_ec_string_opt_string();

        let callback = cb.unwrap();
        callback(command_handle, 0, CString::new("This is a test").unwrap().as_ptr(), CString::new("The second string has something").unwrap().as_ptr());

        let (str1, str2) = receiver.wait().unwrap().unwrap();
        assert_eq!(str1, "This is a test".to_string());
        assert_eq!(str2, Some("The second string has something".to_string()));
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Realms.Schema;

namespace Realms
{
    /// <summary>
    /// Base for any object that can be persisted in a <see cref="Realm"/>.
    /// </summary>
    [Preserve(AllMembers = true, Conditional = false)]
    public class RealmObject : INotifyPropertyChanged, ISchemaSource, IThreadConfined, NotificationsHelper.INotifiable
    {
        private Realm _realm;
        private ObjectHandle _objectHandle;
        private Metadata _metadata;
        private NotificationTokenHandle _notificationToken;

        private event PropertyChangedEventHandler _propertyChanged;

        /// <inheritdoc />
        public event PropertyChangedEventHandler PropertyChanged
        {
            add
            {
                if (IsManaged && _propertyChanged == null)
                {
                    SubscribeForNotifications();
                }

                _propertyChanged += value;
            }

            remove
            {
                _propertyChanged -= value;

                if (IsManaged &&
                    _propertyChanged == null)
                {
                    UnsubscribeFromNotifications();
                }
            }
        }

        internal ObjectHandle ObjectHandle => _objectHandle;

        internal Metadata ObjectMetadata => _metadata;

        /// <summary>
        /// Gets a value indicating whether the object has been associated with a Realm, either at creation or via
        /// <see cref="Realm.Add"/>.
        /// </summary>
        /// <value><c>true</c> if object belongs to a Realm; <c>false</c> if standalone.</value>
        public bool IsManaged => _realm != null;

        /// <summary>
        /// Gets a value indicating whether this object is managed and represents a row in the database.
        /// If a managed object has been removed from the Realm, it is no longer valid and accessing properties on it
        /// will throw an exception.
        /// Unmanaged objects are always considered valid.
        /// </summary>
        /// <value><c>true</c> if managed and part of the Realm or unmanaged; <c>false</c> if managed but deleted.</value>
        public bool IsValid => _objectHandle?.IsValid != false;

        /// <summary>
        /// Gets the <see cref="Realm"/> instance this object belongs to, or <c>null</c> if it is unmanaged.
        /// </summary>
        /// <value>The <see cref="Realm"/> instance this object belongs to.</value>
        public Realm Realm => _realm;

        /// <summary>
        /// Gets the <see cref="Schema.ObjectSchema"/> instance that describes how the <see cref="Realm"/> this object belongs to sees it.
        /// </summary>
        /// <value>A collection of properties describing the underlying schema of this object.</value>
        public ObjectSchema ObjectSchema => _metadata?.Schema;

        Metadata IThreadConfined.Metadata => ObjectMetadata;

        IThreadConfinedHandle IThreadConfined.Handle => ObjectHandle;

        /// <inheritdoc/>
        ~RealmObject()
        {
            UnsubscribeFromNotifications();
        }

        internal void _SetOwner(Realm realm, ObjectHandle objectHandle, Metadata metadata)
        {
            _realm = realm;
            _objectHandle = objectHandle;
            _metadata = metadata;

            if (_propertyChanged != null)
            {
                SubscribeForNotifications();
            }
        }

        #region Getters

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected string GetStringValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetString(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected char GetCharValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (char)_objectHandle.GetInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected char? GetNullableCharValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (char?)_objectHandle.GetNullableInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected byte GetByteValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (byte)_objectHandle.GetInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected byte? GetNullableByteValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (byte?)_objectHandle.GetNullableInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected short GetInt16Value(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (short)_objectHandle.GetInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected short? GetNullableInt16Value(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (short?)_objectHandle.GetNullableInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected int GetInt32Value(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (int)_objectHandle.GetInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected int? GetNullableInt32Value(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return (int?)_objectHandle.GetNullableInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected long GetInt64Value(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected long? GetNullableInt64Value(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetNullableInt64(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected float GetSingleValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetSingle(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected float? GetNullableSingleValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetNullableSingle(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected double GetDoubleValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetDouble(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected double? GetNullableDoubleValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetNullableDouble(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected bool GetBooleanValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetBoolean(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected bool? GetNullableBooleanValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetNullableBoolean(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected DateTimeOffset GetDateTimeOffsetValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetDateTimeOffset(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected DateTimeOffset? GetNullableDateTimeOffsetValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetNullableDateTimeOffset(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected IList<T> GetListValue<T>(string propertyName) where T : RealmObject
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            Property property;
            _metadata.Schema.TryFindProperty(propertyName, out property);
            var relatedMeta = _realm.Metadata[property.ObjectType];

            var listHandle = _objectHandle.TableLinkList(_metadata.PropertyIndices[propertyName]);
            return new RealmList<T>(_realm, listHandle, relatedMeta);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected T GetObjectValue<T>(string propertyName) where T : RealmObject
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            var linkedObjectPtr = _objectHandle.GetLink(_metadata.PropertyIndices[propertyName]);
            if (linkedObjectPtr == IntPtr.Zero)
            {
                return null;
            }

            Property property;
            _metadata.Schema.TryFindProperty(propertyName, out property);
            var objectType = property.ObjectType;
            return (T)_realm.MakeObject(objectType, linkedObjectPtr);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected byte[] GetByteArrayValue(string propertyName)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            return _objectHandle.GetByteArray(_metadata.PropertyIndices[propertyName]);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected IQueryable<T> GetBacklinks<T>(string propertyName) where T : RealmObject
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            var resultsHandle = _objectHandle.GetBacklinks(_metadata.PropertyIndices[propertyName]);
            return GetBacklinksForHandle<T>(propertyName, resultsHandle);
        }

        internal RealmResults<T> GetBacklinksForHandle<T>(string propertyName, ResultsHandle resultsHandle) where T : RealmObject
        {
            Property property;
            _metadata.Schema.TryFindProperty(propertyName, out property);
            var relatedMeta = _realm.Metadata[property.ObjectType];

            return new RealmResults<T>(_realm, resultsHandle, relatedMeta);
        }

        #endregion

        #region Setters

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetStringValue(string propertyName, string value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetString(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetStringValueUnique(string propertyName, string value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetStringUnique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetCharValue(string propertyName, char value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetCharValueUnique(string propertyName, char value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableCharValue(string propertyName, char? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableCharValueUnique(string propertyName, char? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetByteValue(string propertyName, byte value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetByteValueUnique(string propertyName, byte value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableByteValue(string propertyName, byte? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableByteValueUnique(string propertyName, byte? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetInt16Value(string propertyName, short value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetInt16ValueUnique(string propertyName, short value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableInt16Value(string propertyName, short? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableInt16ValueUnique(string propertyName, short? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetInt32Value(string propertyName, int value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetInt32ValueUnique(string propertyName, int value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableInt32Value(string propertyName, int? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableInt32ValueUnique(string propertyName, int? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetInt64Value(string propertyName, long value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetInt64ValueUnique(string propertyName, long value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableInt64Value(string propertyName, long? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableInt64ValueUnique(string propertyName, long? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableInt64Unique(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetSingleValue(string propertyName, float value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetSingle(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableSingleValue(string propertyName, float? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableSingle(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetDoubleValue(string propertyName, double value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetDouble(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableDoubleValue(string propertyName, double? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableDouble(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetBooleanValue(string propertyName, bool value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetBoolean(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableBooleanValue(string propertyName, bool? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableBoolean(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetDateTimeOffsetValue(string propertyName, DateTimeOffset value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetDateTimeOffset(_metadata.PropertyIndices[propertyName], value);
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetNullableDateTimeOffsetValue(string propertyName, DateTimeOffset? value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetNullableDateTimeOffset(_metadata.PropertyIndices[propertyName], value);
        }

        // Originally a generic fallback, now used only for RealmObject To-One relationship properties
        // most other properties handled with woven type-specific setters above
        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetObjectValue<T>(string propertyName, T value) where T : RealmObject
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            if (value == null)
            {
                _objectHandle.ClearLink(_metadata.PropertyIndices[propertyName]);
            }
            else
            {
                if (!value.IsManaged)
                {
                    _realm.Add(value);
                }

                _objectHandle.SetLink(_metadata.PropertyIndices[propertyName], value.ObjectHandle);
            }
        }

        [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
        protected void SetByteArrayValue(string propertyName, byte[] value)
        {
            Debug.Assert(IsManaged, "Object is not managed, but managed access was attempted");

            _objectHandle.SetByteArray(_metadata.PropertyIndices[propertyName], value);
        }

        #endregion

        /// <inheritdoc/>
        public override bool Equals(object obj)
        {
            // If parameter is null, return false.
            if (ReferenceEquals(obj, null))
            {
                return false;
            }

            // Optimization for a common success case.
            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            // If run-time types are not exactly the same, return false.
            if (GetType() != obj.GetType())
            {
                return false;
            }

            // standalone objects cannot participate in the same store check
            if (!IsManaged)
            {
                return false;
            }

            // Return true if the fields match.
            // Note that the base class is not invoked because it is
            // System.Object, which defines Equals as reference equality.
            return ObjectHandle.Equals(((RealmObject)obj).ObjectHandle);
        }

        /// <summary>
        /// Allows you to raise the PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed. If not specified, we'll use the caller name.</param>
        protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            _propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            OnPropertyChanged(propertyName);
        }

        /// <summary>
        /// Called when a property has changed on this class.
        /// </summary>
        /// <param name="propertyName">The name of the property.</param>
        /// <remarks>
        /// For this method to be called, you need to have first subscribed to <see cref="PropertyChanged"/>.
        /// This can be used to react to changes to the current object, e.g. raising <see cref="PropertyChanged"/> for computed properties.
        /// </remarks>
        /// <example>
        /// <code>
        /// class MyClass : RealmObject
        /// {
        ///     public int StatusCodeRaw { get; set; }
        ///
        ///     public StatusCodeEnum StatusCode => (StatusCodeEnum)StatusCodeRaw;
        ///
        ///     protected override void OnPropertyChanged(string propertyName)
        ///     {
        ///         if (propertyName == nameof(StatusCodeRaw))
        ///         {
        ///             RaisePropertyChanged(nameof(StatusCode));
        ///         }
        ///     }
        /// }
        /// </code>
        /// Here, we have a computed property that depends on a persisted one. In order to notify any <see cref="PropertyChanged"/>
        /// subscribers that <c>StatusCode</c> has changed, we override <see cref="OnPropertyChanged"/> and
        /// raise <see cref="PropertyChanged"/> manually by calling <see cref="RaisePropertyChanged"/>.
        /// </example>
        protected virtual void OnPropertyChanged(string propertyName)
        {
        }

        private void SubscribeForNotifications()
        {
            Debug.Assert(_notificationToken == null, "_notificationToken must be null before subscribing.");

            _realm.ExecuteOutsideTransaction(() =>
            {
                if (ObjectHandle.IsValid)
                {
                    var managedObjectHandle = GCHandle.Alloc(this, GCHandleType.Weak);
                    var token = new NotificationTokenHandle(ObjectHandle);
                    var tokenHandle = ObjectHandle.AddNotificationCallback(GCHandle.ToIntPtr(managedObjectHandle), NotificationsHelper.NotificationCallback);

                    token.SetHandle(tokenHandle);

                    _notificationToken = token;
                }
            });
        }

        private void UnsubscribeFromNotifications()
        {
            _notificationToken?.Dispose();
            _notificationToken = null;
        }

        void NotificationsHelper.INotifiable.NotifyCallbacks(NotifiableObjectHandleBase.CollectionChangeSet? changes, NativeException? exception)
        {
            var managedException = exception?.Convert();

            if (managedException != null)
            {
                Realm.NotifyError(managedException);
            }
            else if (changes.HasValue)
            {
                foreach (var propertyIndex in changes.Value.Properties.AsEnumerable())
                {
                    var property = ObjectSchema.ElementAtOrDefault((int)propertyIndex);
                    RaisePropertyChanged(property.PropertyInfo?.Name ?? property.Name);
                }
            }
        }

        internal class Metadata
        {
            internal TableHandle Table;

            internal Weaving.IRealmObjectHelper Helper;

            internal Dictionary<string, IntPtr> PropertyIndices;

            internal ObjectSchema Schema;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace dai {

struct RGBColor {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    //u_int8_t alpha; // padding
};

typedef GenericFrame<RGBColor, DataFrame::Color> ColorFrame;
typedef shared_ptr<ColorFrame> ColorFramePtr;

} // End Namespace

#endif // COLOR_FRAME_H


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.0.2] - 2019-05-14

- Catching an exception on Send (HEAD) ([#534])

## [2.0.0] - 2018-10-17

- Removed eval to resolve CSP ([#465])

## [2.0.0-rc.4] - 2018-10-17

- Don't throw on module.exports

## [2.0.0-rc.3] - 2018-09-27

- Switch export method

## [2.0.0-rc.2] - 2018-09-26

- Added a changelog.md
- Reverted `a.click()` to use dispatch with a try-catch ([#465], [#382])
- Made third argument to an object where you have to pass `{ autoBom: true }`
  - boolean are depricated but still works

## [2.0.0-rc.1] - 2018-09-26

- saveAs don't return anything
  - The object that dispatched `writestart progress write writeend` are gone
  - detecting such features was never possible and nobody seems to use it.
- Removed the demo folder
- Removed date/version from top of the file
- Dosen't crash in web workers ([#449])
- Support saving urls ([#260] with workarounds for cross origin)
- Uses babel universal module pattern (UMD) to export the package
- Provides source map now as well.
- use a[download] before msSaveAs ([#193], [#294])
- removed dist from .gitignore (npm uses it if it don't find a .npmignore)
- autoBom is now reversed so you have to tell when you want to use autoBom ([#432])
- `a.click()` since there are new and depricated event constructors that works differently ([#382])
- opens up a new popup (tab) directly for the fallback method since the FileReader is async
- removed the explicitly MSIE [1-9] check
- Uses new anchor link for each save (might solve multiple download problems)

  [#382]: https://github.com/eligrey/FileSaver.js/issues/382
  [#449]: https://github.com/eligrey/FileSaver.js/issues/449
  [#260]: https://github.com/eligrey/FileSaver.js/issues/260
  [#193]: https://github.com/eligrey/FileSaver.js/issues/193
  [#294]: https://github.com/eligrey/FileSaver.js/issues/294
  [#432]: https://github.com/eligrey/FileSaver.js/issues/432
  [#382]: https://github.com/eligrey/FileSaver.js/issues/382
  [#465]: https://github.com/eligrey/FileSaver.js/issues/465
  [#469]: https://github.com/eligrey/FileSaver.js/issues/469
  [#470]: https://github.com/eligrey/FileSaver.js/issues/470
  [#491]: https://github.com/eligrey/FileSaver.js/issues/491
  [#534]: https://github.com/eligrey/FileSaver.js/issues/534


text:
"use strict";

var compression = require('compression'),
    http = require('http'),
    express = require('express');

var HTTPserver = function(config) {
    this.app = express();

    // GZIP
    this.app.use(compression());

    // Expose entire client folder
    this.app.use('/', express.static(__dirname + '/../client'));

    // Expose shared lib files
    this.app.use('/js/lib', express.static(__dirname + '/../lib'));

    this.server = this.app.listen(config.port);
}

module.exports = HTTPserver;


text:
import nltk
import os
import collections
from nltk.classify import NaiveBayesClassifier
from nltk.metrics import precision, recall, f_measure
import datetime
import pickle
from statistics import mode

import trainer.corpora as crp
import trainer.features as ftr

from nltk.classify import ClassifierI
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC, NuSVC

class VoteClassifier(ClassifierI):
    def __init__(self, *classifiers):
        self._classifiers = classifiers

    def classify(self, features):
        votes = []
        for c in self._classifiers:
            v = c.classify(features)
            votes.append(v)
        # print(mode(votes))

        if votes.count("pos") >= 5:
            return "pos"
        elif votes.count("neg") >= 5:
            return "neg"
        else:
            return "neu"

        # return mode(votes)

    def confidence(self, features):
        votes = []
        for c in self._classifiers:
            v = c.classify(features)
            votes.append(v)

        choice_votes = votes.count(mode(votes))
        conf = choice_votes / len(votes)
        return conf

def get_precision(trainfeats, testfeats, my_classifier, dataset, classifier_name):

    dir = "output/" + dataset + "/algos5new/"
    os.makedirs(dir, exist_ok=True)

    file_name = dir + dataset + "-" + classifier_name + ".csv"
    output = open(file_name, 'a')
    # output.write(str(datetime.datetime.today()) + "\n")

    refsets = collections.defaultdict(set)
    testsets = collections.defaultdict(set)

    tpos = 0
    fpos = 0
    tneg = 0
    fneg = 0
    fneu = 0

    for i, (feats, label) in enumerate(testfeats):
        refsets[label].add(i)
        observed = my_classifier.classify(feats)
        testsets[observed].add(i)

        if label == observed:
            if observed == 'pos':
                tpos += 1
            else:
                tneg += 1
        elif observed == 'pos':
            fpos += 1
        elif observed == 'neg':
            fneg += 1
        elif observed == 'neu':
            fneu += 1

    print(tpos)
    print(fpos)
    print(tneg)
    print(fneg)
    print(fneu)

    accuracy2 = round(((tpos + tneg) / (tpos + tneg + fpos + fneg)) * 100, 1)
    pos_prec2 = round((tpos / (tpos + fpos)) * 100, 1)
    pos_rec2 = round((tpos / (tpos + fneg)) * 100, 1)
    neg_prec2 = round((tneg / (tneg + fneg)) * 100, 1)
    neg_rec2 = round((tneg / (tneg + fpos)) * 100, 1)

    output_text2 = classifier_name + "-new, " + str(accuracy2) + ", " + str(pos_prec2) + ", " + str(neg_prec2) + ", " + str(
        pos_rec2) + ", " + str(neg_rec2) + "\n"
    print(output_text2)

    # precision and recall
    accuracy = nltk.classify.util.accuracy(my_classifier, testfeats) * 100
    pos_prec = precision(refsets['pos'], testsets['pos']) * 100
    pos_rec = recall(refsets['pos'], testsets['pos']) * 100
    neg_prec = precision(refsets['neg'], testsets['neg']) * 100
    neg_rec = recall(refsets['neg'], testsets['neg']) * 100

    # round
    accuracy = round(accuracy, 1)
    pos_prec = round(pos_prec, 1)
    pos_rec = round(pos_rec, 1)
    neg_prec = round(neg_prec, 1)
    neg_rec = round(neg_rec, 1)

    output_text = classifier_name + ", " + str(accuracy) + ", " + str(pos_prec) + ", " + str(neg_prec) + ", " + str(
        pos_rec) + ", " + str(neg_rec) + "\n"
    print(output_text)

    output.write(output_text2)
    output.flush()

def train(trainfeats, testfeats, dataset, nlt = True, skl = True, most = 0):
    # print('train on %d instances, test on %d instances' % (len(trainfeats), len(testfeats)))

    nltk_output = "none"
    sklearn_output = "none"

    if nlt:

        my_classifier = NaiveBayesClassifier.train(trainfeats)
        refsets = collections.defaultdict(set)
        testsets = collections.defaultdict(set)

        for i, (feats, label) in enumerate(testfeats):
            refsets[label].add(i)
            observed = my_classifier.classify(feats)
            testsets[observed].add(i)

        # precision and recall
        accuracy = nltk.classify.util.accuracy(my_classifier, testfeats) * 100
        pos_prec = precision(refsets['pos'], testsets['pos']) * 100
        pos_rec = recall(refsets['pos'], testsets['pos']) * 100
        neg_prec = precision(refsets['neg'], testsets['neg']) * 100
        neg_rec = recall(refsets['neg'], testsets['neg']) * 100

        # round
        accuracy = round(accuracy, 1)
        pos_prec = round(pos_prec, 1)
        pos_rec = round(pos_rec, 1)
        neg_prec = round(neg_prec, 1)
        neg_rec = round(neg_rec, 1)

        # print('pos F-measure:', f_measure(refsets['pos'], testsets['pos']))
        # print('neg F-measure:', f_measure(refsets['neg'], testsets['neg']))
        my_classifier.show_most_informative_features(most)

        nltk_output = "nlt, " + str(accuracy) + ", " + str(pos_prec) + ", " + str(neg_prec) + ", " + str(
            pos_rec) + ", " + str(neg_rec) + "\n"

    if skl:

        MNB_classifier = SklearnClassifier(MultinomialNB())
        MNB_classifier._vectorizer.sort = False
        my_classifier = MNB_classifier.train(trainfeats)
        # get_precision(trainfeats, testfeats, my_classifier, dataset, "mnb")

        # mnb = (nltk.classify.accuracy(MNB_classifier, testfeats)) * 100
        # mnb = round(mnb, 1)
        # print(mnb)

        BernoulliNB_classifier = SklearnClassifier(BernoulliNB())
        BernoulliNB_classifier._vectorizer.sort = False
        my_classifier = BernoulliNB_classifier.train(trainfeats)
        # get_precision(trainfeats, testfeats, my_classifier, dataset, "bnb")

        # bnb = (nltk.classify.accuracy(BernoulliNB_classifier, testfeats)) * 100
        # bnb = round(bnb, 1)
        # print(bnb)

        LogisticRegression_classifier = SklearnClassifier(LogisticRegression())
        LogisticRegression_classifier._vectorizer.sort = False
        my_classifier = LogisticRegression_classifier.train(trainfeats)
        # get_precision(trainfeats, testfeats, my_classifier, dataset, "lr")

        # lr = (nltk.classify.accuracy(LogisticRegression_classifier, testfeats)) * 100
        # lr = round(lr, 1)
        # print(lr)

        LinearSVC_classifier = SklearnClassifier(LinearSVC())
        LinearSVC_classifier._vectorizer.sort = False
        my_classifier = LinearSVC_classifier.train(trainfeats)
        # get_precision(trainfeats, testfeats, my_classifier, dataset, "lsvc")

        # lsvc = (nltk.classify.accuracy(LinearSVC_classifier, testfeats)) * 100
        # lsvc = round(lsvc, 1)
        # print(lsvc)

        NuSVC_classifier = SklearnClassifier(NuSVC())
        NuSVC_classifier._vectorizer.sort = False
        my_classifier = NuSVC_classifier.train(trainfeats)
        # get_precision(trainfeats, testfeats, my_classifier, dataset, "nsvc")

        # nsvc = (nltk.classify.accuracy(NuSVC_classifier, testfeats)) * 100
        # nsvc = round(nsvc, 1)
        # print(nsvc)

        voted_classifier = VoteClassifier(
            NuSVC_classifier,
            LinearSVC_classifier,
            MNB_classifier,
            BernoulliNB_classifier,
            LogisticRegression_classifier)
        get_precision(trainfeats, testfeats, voted_classifier, dataset, "voted")

        # voted = (nltk.classify.accuracy(voted_classifier, testfeats)) * 100
        # voted = round(voted, 1)
        # print(voted)

        # sklearn_output = "skl, " + str(mnb) + ", " + str(bnb) + ", " + str(lr) + ", " + str(lsvc) + ", " + str(nsvc) + ", " + str(voted) + "\n"
        sklearn_output = ""

    return (nltk_output, sklearn_output)

if __name__ == '__main__':
    COUNT = 5000
    cut = int((COUNT/2)*4/5)

    corpora = crp.Corpora("stwits", count=COUNT, shuffle=True)
    features = ftr.Features(corpora, total=COUNT, stem="porter", bigram=True, stop=True, inf_count=-1, lower=True)
    # features = ftr.Features(corpora, total=COUNT, bigram=True, stem="porter")

    posfeats = features.get_features_pos()
    negfeats = features.get_fearures_neg()

    trainfeats = negfeats[:cut] + posfeats[:cut]
    testfeats = negfeats[cut:] + posfeats[cut:]

    print('train on %d instances, test on %d instances' % (len(trainfeats), len(testfeats)))
    nlt, skl = train(trainfeats, testfeats, skl=False, most=50)
    print(nlt, skl)


text:
// Code generated by go-swagger; DO NOT EDIT.

package operations

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command

import (
	"net/http"

	middleware "github.com/go-openapi/runtime/middleware"
)

// CreatePoolHandlerFunc turns a function with the right signature into a create pool handler
type CreatePoolHandlerFunc func(CreatePoolParams) middleware.Responder

// Handle executing the request and returning a response
func (fn CreatePoolHandlerFunc) Handle(params CreatePoolParams) middleware.Responder {
	return fn(params)
}

// CreatePoolHandler interface for that can handle valid create pool params
type CreatePoolHandler interface {
	Handle(CreatePoolParams) middleware.Responder
}

// NewCreatePool creates a new http.Handler for the create pool operation
func NewCreatePool(ctx *middleware.Context, handler CreatePoolHandler) *CreatePool {
	return &CreatePool{Context: ctx, Handler: handler}
}

/*CreatePool swagger:route PUT /pools/{id} createPool

Create a new pool

*/
type CreatePool struct {
	Context *middleware.Context
	Handler CreatePoolHandler
}

func (o *CreatePool) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	route, rCtx, _ := o.Context.RouteInfo(r)
	if rCtx != nil {
		r = rCtx
	}
	var Params = NewCreatePoolParams()

	if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
		o.Context.Respond(rw, r, route.Produces, route, err)
		return
	}

	res := o.Handler.Handle(Params) // actually handle the request

	o.Context.Respond(rw, r, route.Produces, route, res)

}


text:
title: "Keras"
meta_title: "Keras"
meta_description: "Polyaxon allows to schedule Keras experiments, and supports tracking metrics, outputs, and models natively."
custom_excerpt: "Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano."
image: "../../content/images/integrations/keras.png"
author:
  name: "Polyaxon"
  slug: "Polyaxon"
  website: "https://polyaxon.com"
  twitter: "polyaxonAI"
  github: "polyaxon"
tags:
  - tracking
featured: false
popularity: 2
visibility: public
status: published
---

Polyaxon allows to schedule Keras experiments, and supports tracking metrics, outputs, and models.

With Polyaxon you can:

 * log hyperparameters for every run
 * see learning curves for losses and metrics during training
 * see hardware consumption and stdout/stderr output during training
 * log images, charts, and other assets
 * log git commit information
 * log env information
 * log model
 * ...

## Tracking API

Polyaxon provides a [tracking API](/docs/experimentation/tracking/) to track experiment and report metrics, artifacts, logs, and results to the Polyaxon dashboard.

You can use the tracking API to create a custom tracking experience with Keras.

## Setup

In order to use Polyaxon tracking with Keras, you need to install Polyaxon library

```bash
pip install polyaxon
```

## Initialize your script with Polyaxon

This is an optional step if you need to perform some manual tracking or to track some information before passing the callback.

```python
from polyaxon import tracking

tracking.init(...)
```

## Polyaxon callback

Polyaxon provides a Keras callback, you can use this callback with your experiment to report metrics automatically

```python
from polyaxon import tracking
from polyaxon.tracking.contrib.keras import PolyaxonCallback

# ...
tracking.init()
#...
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          validation_data=(x_test, y_test),
          callbacks=[PolyaxonCallback()])  # Polyaxon
```

## Customizing the callback

Polyaxon's callback can be customized to alter the default behavior:

 * It will use the current initialized run unless you pass a different run
 * It log all metrics unless you pass a list of metrics to logs
 * It logs the model by default unless you disable the model logging

```python
PolyaxonCallback(run=run, metrics=["metric1", "metric2", ...], log_model=False)
```

all args:

 * `run`: optional run to use, if not provided it will be initialized automatically.
 * `metrics`: optional, list of metrics to log, if not provided all metrics will be tracked.
 * `log_model`: optional, to log the model or not.
 * `save_weights_only`: optional, to log the weights only or the complete model data.
 * `log_best_prefix`: optional, to log the best metric and epoch prefixed, default `best`.
 * `mode`: optional, a mode to detect if the metric to monitor should be maximized or minimized, default `auto`, other options: `min` and `max`.
 * `monitor`: optional, the metric to monitor for best checkpoint, default `val_loss`.

## Manual logging

If you want to have more control and use Polyaxon to log metrics in your custom Keras training loops:

 * log metrics

```python
tracking.log_mtrics(metric1=value1, metric2=value2, ...)
```

## Example

```python
import argparse

import tensorflow as tf

# Polyaxon
from polyaxon import tracking
from polyaxon.tracking.contrib.keras import PolyaxonCallback

OPTIMIZERS = {
    'adam': tf.keras.optimizers.Adam,
    'rmsprop': tf.keras.optimizers.RMSprop,
    'sgd': tf.keras.optimizers.SGD,
}

def transform_data(x_train, y_train, x_test, y_test):
    x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
    x_train = x_train.astype('float32') / 255

    x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
    x_test = x_test.astype('float32') / 255

    y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
    y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)

    return x_train, y_train, x_test, y_test

def train(conv1_size, conv2_size, dropout, hidden1_size, optimizer, log_learning_rate, epochs):
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Conv2D(filters=conv1_size,
                                     kernel_size=(3, 3),
                                     activation='relu',
                                     input_shape=x_train.shape[1:]))
    model.add(tf.keras.layers.Conv2D(filters=conv2_size,
                                     kernel_size=(3, 3),
                                     activation='relu'))
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
    model.add(tf.keras.layers.Dropout(dropout))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(hidden1_size, activation='relu'))
    model.add(tf.keras.layers.Dense(10, activation='softmax'))

    optimizer = OPTIMIZERS[optimizer](lr=10 ** log_learning_rate)
    model.compile(
        optimizer=optimizer,
        loss='categorical_crossentropy',
        metrics=['accuracy'],
    )

    model.fit(
        x_train,
        y_train,
        epochs=epochs,
        batch_size=100,
        callbacks=[PolyaxonCallback()],  # Polyaxon
    )
    return model.evaluate(x_test, y_test)[1]

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--conv1_size',
        type=int,
        default=32)
    parser.add_argument(
        '--conv2_size',
        type=int,
        default=64
    )
    parser.add_argument(
        '--dropout',
        type=float,
        default=0.8
    )
    parser.add_argument(
        '--hidden1_size',
        type=int,
        default=500
    )
    parser.add_argument(
        '--optimizer',
        type=str,
        default='adam'
    )
    parser.add_argument(
        '--log_learning_rate',
        type=int,
        default=-3
    )
    parser.add_argument(
        '--epochs',
        type=int,
        default=1
    )
    args = parser.parse_args()

    # Polyaxon
    tracking.init()

    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

    # Polyaxon
    tracking.log_data_ref(content=x_train, name='x_train', is_input=True)
    tracking.log_data_ref(content=y_train, name='y_train', is_input=True)
    tracking.log_data_ref(content=x_test, name='x_test', is_input=True)
    tracking.log_data_ref(content=y_test, name='y_test', is_input=True)

    x_train, y_train, x_test, y_test = transform_data(x_train, y_train, x_test, y_test)
    model = tf.keras.models.Sequential([
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(256, activation=tf.keras.activations.relu),
        tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(10, activation=tf.keras.activations.softmax)
    ])

    accuracy = train(conv1_size=args.conv1_size,
                     conv2_size=args.conv2_size,
                     dropout=args.dropout,
                     hidden1_size=args.hidden1_size,
                     optimizer=args.optimizer,
                     log_learning_rate=args.log_learning_rate,
                     epochs=args.epochs)

    # Polyaxon
    tracking.log_metrics(eval_accuracy=accuracy)
```


text:
(function FileSystemServiceModule() {
	"use strict";

	angular.module('translate.app')
		.factory('fileSystemService', FileSystemService);

	FileSystemService.$inject = ['$q'];

	function FileSystemService($q) {
		return {
			readTextFile: function () {
				var deferred = $q.defer();
				chrome.fileSystem.chooseEntry({
						type: 'openFile',
						accepts: [
							{
								description: 'Text based files (*.txt, *.json, *.csv)',
								extensions: ['txt', 'json', 'csv']
							}
						]
					},
					function (entry) {
						entry.file(function (file) {
							var reader = new FileReader();

							reader.onerror = function (err) {
								deferred.reject(err);
							};

							reader.onloadend = function (e) {
								deferred.resolve(
									{
										entry: entry,
										data: e.target.result
									}
								);
							};

							reader.readAsText(file);
						});
					}
				);

				return deferred.promise;
			},

			saveToFile: function (data, description, extensions, type) {
				description = description || 'Text based files (*.json)';
				extensions = extensions || ['json'];
				type = type || 'application/json';
				var deferred = $q.defer();
				chrome.fileSystem.chooseEntry({
						type: 'saveFile',
						accepts: [
							{
								description: description,
								extensions: extensions
							}
						]
					},
					function (entry) {
						entry.createWriter(function (writer) {
							writer.onerror = function (err) {
								deferred.reject(err);
							};
							writer.onwriteend = function() {
								deferred.resolve();
							};

							writer.write(new Blob([data]), type);
						});
					});

				return deferred.promise;
			}
		};
	}
})();


text:
#include "greentop/betting/ListEventTypesResponse.h"

namespace greentop {
ListEventTypesResponse::ListEventTypesResponse() {
}

ListEventTypesResponse::ListEventTypesResponse(const std::vector<EventTypeResult>& eventTypeResults) :
    eventTypeResults(eventTypeResults) {
}

void ListEventTypesResponse::fromJson(const Json::Value& json) {
    if (validateJson(json)) {
        for (unsigned i = 0; i < json.size(); ++i) {
            EventTypeResult eventTypeResult;
            eventTypeResult.fromJson(json[i]);
            eventTypeResults.push_back(eventTypeResult);
        };
    }
}

Json::Value ListEventTypesResponse::toJson() const {
    Json::Value json(Json::arrayValue);
    if (eventTypeResults.size() > 0) {
        for (unsigned i = 0; i < eventTypeResults.size(); ++i) {
            json.append(eventTypeResults[i].toJson());
        };
    }
    return json;
}

bool ListEventTypesResponse::isValid() const {
    return eventTypeResults.size() > 0;
}

const std::vector<EventTypeResult>& ListEventTypesResponse::getEventTypeResults() const {
    return eventTypeResults;
}
void ListEventTypesResponse::setEventTypeResults(const std::vector<EventTypeResult>& eventTypeResults) {
    this->eventTypeResults = eventTypeResults;
}

}


text:
import utils
import settings
import importlib
import tornado.web
import json

from models import Song

class JsonResponse(tornado.web.RequestHandler):
    """
        Request handler where requests and responses speak JSON.
        From: https://gist.github.com/mminer/5464753
    """
    def prepare(self):
        # Incorporate request JSON into arguments dictionary.
        if self.request.body:
            try:
                json_data = json.loads(self.request.body)
                self.request.arguments.update(json_data)
            except ValueError:
                message = 'Unable to parse JSON.'
                self.send_error(400, message=message) # Bad Request

        # Set up response dictionary.
        self.response = dict()

    def set_default_headers(self):
        self.set_header('Content-Type', 'application/json')

    def write_error(self, status_code, **kwargs):
        if 'message' not in kwargs:
            if status_code == 405:
                kwargs['message'] = 'Invalid HTTP method.'
            else:
                kwargs['message'] = 'Unknown error.'

        self.response = kwargs
        self.write_json()

    def write_json(self):
        output = json.dumps(self.response)
        self.write(output)

class DiscoverController(JsonResponse):

    def get(self):

        self.response = []
        return self.write_json()

class SearchController(JsonResponse):

    def get(self, slug):
        servname = settings.SERVICES.get(slug)
        if servname:
            q = self.get_argument('q')
            remote = self.get_argument('remote', 0)

            service = utils.get_service_class(servname)()

            if remote == '1':
                service.connect()
                result = service.search(q)
            else:
                result = service.search_in_cache(q)
                if not result:
                    service.connect()
                    service.search(q)
                    result = service.search_in_cache(q)

            self.response['songs'] = result
            return self.write_json()
        else:
            return self.write_error(404)

class PlaySongController(JsonResponse):

    def get(self, slug, song_id):

        servname = settings.SERVICES.get(slug)
        if servname:
            service = utils.get_service_class(servname)()
            service.connect()

            result = service.get_song(song_id)

            self.response = result
            return self.write_json()
        else:
            return self.write_error(404)

class CacheController(tornado.web.RequestHandler):

    def get(self, file_name):

        full_path = '%s%s' % (settings.CACHE_PATH, file_name)

        buf_size = 4096
        self.set_header('Content-Type', 'audio/mpeg')
        self.set_header('Content-Disposition', 'attachment; filename=' + file_name)
        with open(full_path, 'r') as f:
            while True:
                data = f.read(buf_size)
                if not data:
                    break
                self.write(data)
        self.finish()


text:
package org.sewas.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.sewas.domain.model.Match;
import org.sewas.exception.MatchdayNotAvailableException;
import org.sewas.exception.OpenLigaDbNotOkException;
import org.sewas.rest.dto.MatchDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import utils.testing.IntegrationTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

/**
 * Created by sebastian on 11/06/17.
 */
@Category(IntegrationTest.class)
@RunWith(SpringRunner.class)
@ActiveProfiles("clientTest")
@RestClientTest(OpenLigaDBClient.class)
@ContextConfiguration(classes = {ClientTestConfig.class})
public class OpenLigaDBClientMatchdayForLeagueIT {

    @Autowired
    private OpenLigaDBClient openLigaDBClient;

    @Autowired
    private MockRestServiceServer server;

    ObjectMapper o;

    @Before
    public void setUp() {
        this.o = new ObjectMapper();
    }

    @Test
    public void shouldReturnMatchDTOForExistingMatchday() throws OpenLigaDbNotOkException, JsonProcessingException, MatchdayNotAvailableException {

        Match[] responseMatches = {new Match(), new Match(), new Match()};

        this.server.expect(requestTo("http://localhost:1234/api/getmatchdata/myLeague/anySeason/anyMatchday"))
                .andRespond(withSuccess(o.writeValueAsString(responseMatches), MediaType.APPLICATION_JSON));

        MatchDTO result = this.openLigaDBClient.getMatchesForLeagueMatchday("myLeague", "anySeason", "anyMatchday");

        assertThat(result.getStatusCode()).isEqualTo(200);
        assertThat(result.getMatches()).hasSize(3);
    }

    @Test(expected = OpenLigaDbNotOkException.class)
    public void shouldThrowExceptionIfOpenLigaDbAnswersNotWithOK() throws JsonProcessingException, OpenLigaDbNotOkException, MatchdayNotAvailableException {

        Match[] responseMatches = {new Match(), new Match(), new Match()};

        this.server.expect(requestTo("http://localhost:1234/api/getmatchdata/anyLeague/anyYear/anyMatchday"))
                .andRespond(withStatus(HttpStatus.NOT_FOUND));

        MatchDTO result = this.openLigaDBClient.getMatchesForLeagueMatchday("anyLeague", "anyYear", "anyMatchday");
    }

    @Test(expected = MatchdayNotAvailableException.class)
    public void shouldThrowExceptionIfOpenLigaDbResponseIsEmpty() throws JsonProcessingException, OpenLigaDbNotOkException, MatchdayNotAvailableException {

        Match[] responseMatches = {};

        this.server.expect(requestTo("http://localhost:1234/api/getmatchdata/anyLeague/anyYear/anyMatchday"))
                .andRespond(withSuccess(o.writeValueAsString(responseMatches), MediaType.APPLICATION_JSON));

        MatchDTO result = this.openLigaDBClient.getMatchesForLeagueMatchday("anyLeague", "anyYear", "anyMatchday");
    }
}


text:
title: Checkboxes
---

* use these to select either on/off toggles or multiple selections
* make it clear with words when users can select one or multiple options

```
[TODO: Add example from here](http://govuk-elements.herokuapp.com/form-elements/example-radios-checkboxes/)
```


text:
class RiderPaymentMethod < ClassyEnum::Base
end

class RiderPaymentMethod::Cash < RiderPaymentMethod
end

class RiderPaymentMethod::Check < RiderPaymentMethod
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="browser_activityName">FileBrowser</string>
    <string name="browser_pathPlaceholder">Opened file\'s path goes here</string>
    <string name="browser_currentDirectory">Current directory:</string>
    <string name="browser_placeholder">ads:DsaDF:FdsADS:F</string>
    <string name="browser_titleOpenFile">Open File…</string>
    <string name="browser_titleSaveFile">Save File as…</string>
    <string name="browser_titleSelectDir">Select Directory…</string>
    <string name="browser_emptyFolder">This folder is empty.</string>
    <string name="browser_filenamePlaceholder">Enter filename here…</string>
    <string name="browser_fileExists_title">File exists</string>
    <string name="browser_fileExists_message">Overwrite?</string>
    <string name="browser_menu_newFolder">New folder</string>
    <string name="browser_menu_sortBy">Sort by…</string>
    <string name="browser_menu_viewAsList">View as List</string>
    <string name="browser_menu_viewAsGrid">View as Grid</string>
    <string name="browser_toast_noParentDir">Can\'t go further up.</string>
    <string name="browser_error_folderCantBeOpened_title">Can\'t Open Folder</string>
    <string name="browser_error_folderCantBeOpened_message">This folder is not readable.</string>
    <string-array name="browser_sortOptions">
        <item>Name (ascending)</item>
        <item>Name (descending)</item>
        <item>Extension (ascending)</item>
        <item>Extension (descending)</item>
        <item>Date (ascending)</item>
        <item>Date (descending)</item>
        <item>Size (ascending)</item>
        <item>Size (descending)</item>
    </string-array>
    <plurals name="browser_numberOfFiles">
        <item quantity="one">%d file</item>
        <item quantity="other">%d files</item>
    </plurals>
    <string name="browser_unknown">N/A</string>
    <string name="browser_newFolderHint">Enter folder name here…</string>
    <string name="browser_error_cantCreateFolder_title">Couldn\'t Create Folder</string>
    <string name="browser_error_cantCreateFolder_message">The folder could not be created.</string>
    <string name="browser_error_invalidFilename_title">Invalid Filename</string>
    <string name="browser_error_invalidFilename_message">The specified filename is invalid.</string>
    <string name="browser_error_invalidFolderName_title">Invalid Folder Name</string>
    <string name="browser_error_invalidFolderName_message">The specified folder name is invalid.</string>
    <string name="browser_pressAgainToCancel">Press again to cancel.</string>
    <string name="browser_upFolder">..</string>
</resources>


text:
npm install yarn
yarn install


text:
/* eslint-disable no-new, no-unused-expressions */
const { expect } = require('chai');
const fs = require('fs');
const path = require('path');

const ApplicationTypes = require('../../../jdl/jhipster/application-types');
const JHipsterEntityExporter = require('../../../jdl/exporters/jhipster-entity-exporter');
const FileUtils = require('../../../jdl/utils/file-utils');
const { MapperTypes, PaginationTypes, ServiceTypes } = require('../../../jdl/jhipster/entity-options');

const { SERVICE_CLASS } = ServiceTypes;
const NO_DTO = MapperTypes.NO;
const NO_PAGINATION = PaginationTypes.NO;
const NO_SERVICE = ServiceTypes.NO;

describe('JHipsterEntityExporter', () => {
  describe('exportEntities', () => {
    context('when passing invalid parameters', () => {
      context('such as undefined', () => {
        it('should fail', () => {
          expect(() => {
            JHipsterEntityExporter.exportEntities();
          }).to.throw('Entities have to be passed to be exported.');
        });
      });
    });
    context('when passing valid arguments', () => {
      context('for only entities and a monolith app', () => {
        let entities;
        let aEntityContent;
        let returned;

        before(() => {
          entities = [
            {
              name: 'A',
              fields: [
                {
                  fieldName: 'myEnum',
                  fieldType: 'MyEnum',
                  fieldValues: 'FRENCH,ENGLISH',
                },
              ],
              relationships: [],
              changelogDate: '42',
              javadoc: '',
              entityTableName: 'a',
              dto: NO_DTO,
              pagination: NO_PAGINATION,
              service: NO_SERVICE,
              fluentMethods: true,
              jpaMetamodelFiltering: false,
              applications: [],
            },
          ];
          returned = JHipsterEntityExporter.exportEntities({
            entities,
            application: {
              name: 'MyApp',
              type: ApplicationTypes.MONOLITH,
            },
          });
          aEntityContent = JSON.parse(fs.readFileSync(path.join('.jhipster', 'A.json'), { encoding: 'utf-8' }));
        });

        after(() => {
          fs.unlinkSync('.jhipster/A.json');
          fs.rmdirSync('.jhipster');
        });

        it('should return the exported entities', () => {
          expect(returned).to.deep.equal(entities);
        });
        it('should export the entities', () => {
          expect(aEntityContent).to.deep.equal(entities[0]);
        });
      });
      context('when not exporting entities', () => {
        let returned;

        before(() => {
          returned = JHipsterEntityExporter.exportEntities({
            entities: [],
            application: {
              name: 'MyApp',
              type: ApplicationTypes.MONOLITH,
            },
          });
        });
        it('should return an empty list', () => {
          expect(returned).to.deep.equal([]);
        });
        it('should not create a .jhipster folder', () => {
          expect(FileUtils.doesDirectoryExist('.jhipster')).to.be.false;
        });
      });
      context('when exporting the same entity', () => {
        let entities;
        let previousChangelogDate;
        let newChangelogDate;
        let returned;

        before(done => {
          entities = [
            {
              name: 'A',
              fields: [
                {
                  fieldName: 'myEnum',
                  fieldType: 'MyEnum',
                  fieldValues: 'FRENCH,ENGLISH',
                },
              ],
              relationships: [],
              changelogDate: '42',
              javadoc: '',
              entityTableName: 'a',
              dto: NO_DTO,
              pagination: NO_PAGINATION,
              service: NO_SERVICE,
              fluentMethods: true,
              jpaMetamodelFiltering: false,
              applications: [],
            },
          ];
          returned = JHipsterEntityExporter.exportEntities({
            entities,
            application: {
              name: 'MyApp',
              type: ApplicationTypes.MONOLITH,
            },
          });
          previousChangelogDate = JSON.parse(fs.readFileSync('.jhipster/A.json', { encoding: 'utf-8' })).changelogDate;
          setTimeout(() => {
            JHipsterEntityExporter.exportEntities({
              entities,
              application: {
                name: 'MyApp',
                type: ApplicationTypes.MONOLITH,
              },
            });
            newChangelogDate = JSON.parse(fs.readFileSync('.jhipster/A.json', { encoding: 'utf-8' })).changelogDate;
            done();
          }, 1000);
        });

        it('should return the exported entities', () => {
          expect(returned).to.deep.equal([
            {
              name: 'A',
              applications: [],
              changelogDate: '42',
              dto: 'no',
              entityTableName: 'a',
              fields: [
                {
                  fieldName: 'myEnum',
                  fieldType: 'MyEnum',
                  fieldValues: 'FRENCH,ENGLISH',
                },
              ],
              fluentMethods: true,
              javadoc: '',
              jpaMetamodelFiltering: false,
              pagination: NO_PAGINATION,
              relationships: [],
              service: NO_SERVICE,
            },
          ]);
        });
        it('should export it with same changelogDate', () => {
          expect(newChangelogDate).to.equal(previousChangelogDate);
        });

        after(() => {
          fs.unlinkSync('.jhipster/A.json');
          fs.rmdirSync('.jhipster');
        });
      });
      context('when passing an application name and application type', () => {
        context('inside a monolith', () => {
          let entities;
          let returned;

          before(() => {
            entities = [
              {
                name: 'Client',
                fields: [],
                relationships: [
                  {
                    relationshipType: 'many-to-one',
                    relationshipName: 'location',
                    otherEntityName: 'location',
                  },
                ],
                changelogDate: '20180303092308',
                entityTableName: 'client',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'client',
              },
              {
                name: 'Location',
                fields: [],
                relationships: [
                  {
                    relationshipType: 'one-to-many',
                    relationshipName: 'clients',
                    otherEntityName: 'client',
                    otherEntityRelationshipName: 'location',
                  },
                ],
                changelogDate: '20180303092309',
                entityTableName: 'location',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'client',
              },
              {
                name: 'LocalStore',
                fields: [],
                relationships: [
                  {
                    relationshipType: 'one-to-many',
                    relationshipName: 'products',
                    otherEntityName: 'product',
                    otherEntityRelationshipName: 'store',
                  },
                ],
                changelogDate: '20180303092310',
                entityTableName: 'local_store',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'store',
              },
              {
                name: 'Product',
                fields: [
                  {
                    fieldName: 'name',
                    fieldType: 'String',
                  },
                ],
                relationships: [
                  {
                    relationshipType: 'many-to-one',
                    relationshipName: 'store',
                    otherEntityName: 'localStore',
                  },
                ],
                changelogDate: '20180303092311',
                entityTableName: 'product',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'store',
              },
            ];
            returned = JHipsterEntityExporter.exportEntities({
              entities,
              application: {
                name: 'client',
                type: ApplicationTypes.MONOLITH,
              },
            });
          });

          it('should return the exported entities', () => {
            expect(returned).to.deep.equal([
              {
                name: 'Client',
                fields: [],
                relationships: [
                  {
                    relationshipType: 'many-to-one',
                    relationshipName: 'location',
                    otherEntityName: 'location',
                  },
                ],
                changelogDate: '20180303092308',
                entityTableName: 'client',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'client',
              },
              {
                name: 'Location',
                fields: [],
                relationships: [
                  {
                    relationshipType: 'one-to-many',
                    relationshipName: 'clients',
                    otherEntityName: 'client',
                    otherEntityRelationshipName: 'location',
                  },
                ],
                changelogDate: '20180303092309',
                entityTableName: 'location',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'client',
              },
              {
                name: 'LocalStore',
                fields: [],
                relationships: [
                  {
                    relationshipType: 'one-to-many',
                    relationshipName: 'products',
                    otherEntityName: 'product',
                    otherEntityRelationshipName: 'store',
                  },
                ],
                changelogDate: '20180303092310',
                entityTableName: 'local_store',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'store',
              },
              {
                name: 'Product',
                fields: [
                  {
                    fieldName: 'name',
                    fieldType: 'String',
                  },
                ],
                relationships: [
                  {
                    relationshipType: 'many-to-one',
                    relationshipName: 'store',
                    otherEntityName: 'localStore',
                  },
                ],
                changelogDate: '20180303092311',
                entityTableName: 'product',
                dto: NO_DTO,
                pagination: NO_PAGINATION,
                service: SERVICE_CLASS,
                jpaMetamodelFiltering: true,
                fluentMethods: true,
                applications: '*',
                microserviceName: 'store',
              },
            ]);
          });
          it('should export every entity', () => {
            expect(FileUtils.doesFileExist('.jhipster/Client.json'));
            expect(FileUtils.doesFileExist('.jhipster/Location.json'));
            expect(FileUtils.doesFileExist('.jhipster/LocalStore.json'));
            expect(FileUtils.doesFileExist('.jhipster/Product.json'));
          });

          after(() => {
            fs.unlinkSync('.jhipster/Client.json');
            fs.unlinkSync('.jhipster/Location.json');
            fs.unlinkSync('.jhipster/LocalStore.json');
            fs.unlinkSync('.jhipster/Product.json');
            fs.rmdirSync('.jhipster');
          });
        });
        context('inside a microservice', () => {
          context('and when entities without the microservice option are passed', () => {
            let entities;
            let returnedContent;

            before(() => {
              entities = [
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092920',
                  entityTableName: 'a',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'A',
                },
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092921',
                  entityTableName: 'b',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'B',
                },
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092922',
                  entityTableName: 'c',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'C',
                },
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092923',
                  entityTableName: 'd',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'D',
                },
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092924',
                  entityTableName: 'e',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'E',
                },
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092925',
                  entityTableName: 'f',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'F',
                },
                {
                  fields: [],
                  relationships: [],
                  changelogDate: '20180303092926',
                  entityTableName: 'g',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: NO_SERVICE,
                  jpaMetamodelFiltering: false,
                  fluentMethods: true,
                  applications: '*',
                  name: 'G',
                },
              ];
              returnedContent = JHipsterEntityExporter.exportEntities({
                entities,
                application: {
                  name: 'client',
                  type: ApplicationTypes.MICROSERVICE,
                },
              });
            });

            it('should export every entity', () => {
              ['A', 'B', 'C', 'D', 'E', 'F', 'G'].forEach(entityName => {
                expect(FileUtils.doesFileExist(`.jhipster/${entityName}.json`)).to.be.true;
              });
            });

            it('should return every entity', () => {
              expect(returnedContent.length).to.be.equal(7);
              ['A', 'B', 'C', 'D', 'E', 'F', 'G'].forEach(entityName => {
                expect(returnedContent.filter(entity => entity.name === entityName) !== undefined).to.be.true;
              });
            });

            after(() => {
              ['A', 'B', 'C', 'D', 'E', 'F', 'G'].forEach(entityName => {
                fs.unlinkSync(`.jhipster/${entityName}.json`);
              });
              fs.rmdirSync('.jhipster');
            });
          });
          context('and when microservice entities are passed', () => {
            let entities;
            let returnedContent;

            before(() => {
              entities = [
                {
                  fields: [],
                  relationships: [[Object]],
                  changelogDate: '20180303093006',
                  entityTableName: 'client',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: SERVICE_CLASS,
                  jpaMetamodelFiltering: true,
                  fluentMethods: true,
                  applications: '*',
                  microserviceName: 'client',
                  name: 'Client',
                },
                {
                  fields: [],
                  relationships: [[Object]],
                  changelogDate: '20180303093007',
                  entityTableName: 'location',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: SERVICE_CLASS,
                  jpaMetamodelFiltering: true,
                  fluentMethods: true,
                  applications: '*',
                  microserviceName: 'client',
                  name: 'Location',
                },
                {
                  fields: [],
                  relationships: [[Object]],
                  changelogDate: '20180303093008',
                  entityTableName: 'local_store',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: SERVICE_CLASS,
                  jpaMetamodelFiltering: true,
                  fluentMethods: true,
                  applications: '*',
                  microserviceName: 'store',
                  name: 'LocalStore',
                },
                {
                  fields: [[Object]],
                  relationships: [[Object]],
                  changelogDate: '20180303093009',
                  entityTableName: 'product',
                  dto: NO_DTO,
                  pagination: NO_PAGINATION,
                  service: SERVICE_CLASS,
                  jpaMetamodelFiltering: true,
                  fluentMethods: true,
                  applications: '*',
                  microserviceName: 'store',
                  name: 'Product',
                },
              ];
              returnedContent = JHipsterEntityExporter.exportEntities({
                entities,
                application: {
                  name: 'client',
                  type: ApplicationTypes.MICROSERVICE,
                },
              });
            });

            it('should export the entities that should be inside the microservice', () => {
              expect(FileUtils.doesFileExist('.jhipster/Client.json'));
              expect(FileUtils.doesFileExist('.jhipster/Location.json'));
            });

            it('should return the entities that should be inside the microservice', () => {
              expect(returnedContent.length).to.be.equal(2);
            });

            after(() => {
              fs.unlinkSync('.jhipster/Client.json');
              fs.unlinkSync('.jhipster/Location.json');
              fs.rmdirSync('.jhipster');
            });
          });
        });
      });
      context('when exporting updated entities', () => {
        let originalContent;
        let newContent;
        let returnedContent;

        before(() => {
          originalContent = {
            fields: [
              {
                fieldName: 'myEnum',
                fieldType: 'MyEnum',
                fieldValues: 'FRENCH,ENGLISH',
              },
            ],
            relationships: [],
            changelogDate: '42',
            javadoc: '',
            entityTableName: 'a',
            dto: NO_DTO,
            pagination: NO_PAGINATION,
            service: NO_SERVICE,
            fluentMethods: true,
            jpaMetamodelFiltering: false,
            applications: [],
          };
          FileUtils.createFolderIfItDoesNotExist('.jhipster');
          fs.writeFileSync(path.join('.jhipster', 'A.json'), JSON.stringify({ ...originalContent, customAttribute: '42' }));
          const changedContent = {
            ...JSON.parse(JSON.stringify(originalContent)),
            name: 'A',
            changelogDate: '43',
          };
          const entities = [changedContent];
          returnedContent = JHipsterEntityExporter.exportEntities({
            entities,
            application: {
              name: 'MyApp',
              type: ApplicationTypes.MONOLITH,
            },
          });
          newContent = JSON.parse(fs.readFileSync(path.join('.jhipster', 'A.json'), { encoding: 'utf-8' }));
        });

        after(() => {
          fs.unlinkSync('.jhipster/A.json');
          fs.rmdirSync('.jhipster');
        });

        it('should merge the existing content with the new one', () => {
          expect(newContent).to.deep.equal({
            ...originalContent,
            name: 'A',
            customAttribute: '42',
          });
        });

        it('should keep changelogDate original value', () => {
          expect(newContent.customAttribute).to.equal('42');
        });

        it('should return the new content', () => {
          expect(newContent).to.deep.equal(returnedContent[0]);
        });
      });
    });
  });
});


text:
<?php

namespace CacheBundle\Services;

use FilmBundle\Services\ListFilms;
use FilmBundle\Services\ListFilmsInterface;

class ListFilmsFromCache implements ListFilmsInterface
{
    private $listFilms;

    public function __construct(ListFilms $listFilms)
    {
        $this->listFilms = $listFilms;
    }

    public function __invoke()
    {
        if (file_exists(FilmsCacher::CACHE_FILE)) {
            $fileContents       = file_get_contents(FilmsCacher::CACHE_FILE);
            $serializedFilmList = explode("\n", $fileContents);
            $filmList           = [];
            foreach ($serializedFilmList as $serializedFilm) {
                $unserializedFilm = unserialize($serializedFilm);
                if ($unserializedFilm) {
                    $filmList[] = $unserializedFilm;
                }
            }
            return $filmList;
        }

        return call_user_func($this->listFilms);
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href=/biz.aQute.openapi.authentication.example/favicon.ico">

<title></title>

<link rel="stylesheet" type="text/css"
	href="/osgi.enroute.webresource/${bsn}/${Bundle-Version}/*.css">

Home

About

OpenAPI Authentication Example

				{{alert.msg}}
				<button type="button" ng-click='closeAlert($index)' class="close pull-right">×Close</button>

© ${def;Bundle-Vendor;Company} ${tstamp;YYYY}