text:
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] || o[this.name] == '') {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

(function() {
    Tube = {
        api: 1,

        video: null,
        mod: false,
        leader: false,
        connected: false,
        connectionAttempts: 0,
        provider: null,
        handlers: {}, // Video handlers
        userList: {}, // Quick hash lookup for user ids

        channel: null,
        user: null,
        playlist: null,

        tripcode: null, // authentication tripcode

        Views: {},
        Models: {}
    };

    // Models
    var TubeUser = Backbone.Model.extend({
    });

    var TubeVideo = Backbone.Model.extend({
    });

    var TubeChannel = Backbone.Model.extend({
    });

    // Collections

    var TubeUsers = Backbone.Collection.extend({
       model: TubeUser,

       comparator: function(user) {
          return user.get('name')
       }
    });

    var TubePlaylist = Backbone.Collection.extend({
       model: TubeVideo,

       comparator: function(video) {
          return video.get('position')
       }
    });

    var TubeUserItem = Backbone.View.extend({
      tagName: 'li',

      className: 'user',

      events: {
        'click .title':   'open'
      },

      open: function() {
        if (this.model.get('id') == Tube.user.get('id')) {
          // Edit
          //inner.

        }
      },

      render: function() {
        var el = $(this.el).empty();
        var item = this.model;

        el.attr('user_id', this.model.get('id'));

        if (item.get('anon'))
          el.addClass('anon');
        else
          el.addClass('auth');

        var name = el.append('').children().last();
        var tripcode = el.append('').children().last();
        name.text(item.get('name'));
        tripcode.text(item.get('tripcode'));

        if (item.get('leader')) {
          el.append('*')
        }

        if (Tube.mod) {
          el.append('(K)');
          el.append('(B)');
        }
        return this;
      }
    });

    var PlaylistView = {
      tagName: 'div',
      id: 'playlist',

      events: {
        'click .item .title':   'openItem',
        'click .item .delete':  'destroyItem'
      }
    };

    PlaylistView.initialize = function(options) {
      // Playlist
      Tube.playlist.bind('add', this.addVideo, this);
      Tube.playlist.bind('change', this.updateVideo, this);
      Tube.playlist.bind('remove', this.removeVideo, this);
      Tube.playlist.bind('reset', this.addVideos, this);
    }

    PlaylistView.openItem = function(event) {
      if (!Tube.mod)
        return;
      var item = Tube.playlist.get($(event.target).parents('.item:first').attr('video_id'));
      if (!item)
        return;

      Tube.sendMessage({'t': 'video', 'video_id': item.get('id')});
    }

    PlaylistView.destroyItem = function(event) {
      if (!Tube.mod)
        return;

      var item = Tube.playlist.get($(event.target).parents('.item:first').attr('video_id'));
      if (!item)
        return;

      Tube.sendMessage({'t': 'del_video', 'video_id': item.get('id')});
    }

    PlaylistView.addVideo = function(video) {
        var item = $(this.el).append('

').children().last();
        this.renderItem(video, item);
    }

    PlaylistView.addVideos = function(videos) {
      this.render();
      videos.each(this.addVideo, this);
    }

    PlaylistView.updateVideo = function(video, attrs) {
      var attrs = video.changedAttributes();
      var el = $('#playlist_video_' + video.get('id'));
      this.renderItem(video, el);

      Tube.playlist.sort({silent: true});

      if (attrs.position != undefined) {
          var idx = Tube.playlist.indexOf(video);
          var rest = Tube.playlist.rest(idx+1);
          var next = rest[0];

          if (next) {
            // Before the next element
            el.insertBefore('#playlist_video_' + next.get('id'));
          } else if (idx == 0) {
            // At the start
            $(this.el).prepend(el);
          } else {
            // At the end
            $(this.el).append(el);
          }
      }
    }

    PlaylistView.removeVideo = function(video) {
      var item = $('#playlist_video_' + video.get('id'));
      item.unbind();
      item.remove();
    }

    PlaylistView.render = function() {
      $(this.el).empty();
    }

    PlaylistView.renderItem = function(item, el) {
      var inner = el;
      el.empty();
      inner.append('

');
      inner.append('

');

      if (Tube.mod)
      inner.append('
[X]
');

      inner.append('

');

      inner.attr('id', 'playlist_video_' + item.id)
      .attr('position', item.get('position'))
      .attr('video_id', item.get('id'));
      inner.children('.title').text(item.get('title'));
      inner.children('.time').text(Tube.parseDuration(item.get('duration')));

      if (Tube.video_id == item.get('id'))
        el.addClass('active');

      return this;
    }

    Tube.Views.PlaylistView = Backbone.View.extend(PlaylistView);

    // Init collections
    Tube.channel = new TubeChannel();
    Tube.users = new TubeUsers();
    Tube.playlist = new TubePlaylist();

    // Bind events

    // Channel
    Tube.onChannelChange = function(channel, attrs) {
      // ...
      $('#tab_chan_' + channel.get('id') + ' a').text(channel.get('permalink'));
      $('#chanTitle').text(channel.get('name'));
      if (channel.get('banner'))
        $('#chanBanner').html(channel.get('banner'));
      if (channel.get('footer'))
        $('#chanFooter').html(channel.get('footer'));

      Tube.onChangeSkipCount(channel);

      if (channel.get('locked')) {
        $('#playlistEntryBox').hide();
        $('#lockButton').text('Unlock Playlist');
      } else {
        $('#playlistEntryBox').show();
        $('#lockButton').text('Lock Playlist');
      }
    }
    Tube.onChangeSkipCount = function(channel) {
      var button = $('#skipButton');
      if (button) {
        var limit = channel.get('skip_limit')||-1;
        if (limit == -1 || limit > 100) {
          button.hide();
        } else {
          button.show();
          var real_limit = Tube.users.length * (channel.get('skip_limit') / 100.0);
          button.text('Skip (' + (channel.get('skip')||0) + '/' + real_limit + ')');
        }
      }
    }

    // User list
    Tube.users.bind('add', function(user){
      // Add to the list
      //if (user.get('id') != Tube.user.get('id')) {
        var item = new TubeUserItem({model: user, id:'list_' + user.get('id')});
        $('#userList').append(item.render().el);

        user.bind('change', function(model){ item.render() });
        //}
        Tube.onUsersChanged();
    });

    Tube.users.bind('reset', function(users) {
      $('#userList').empty();
      users.each(function(user){
          var item = new TubeUserItem({model: user, id:'list_' + user.get('id')});
          $('#userList').append(item.render().el);

          user.bind('change', function(model){ item.render() });
      });

      Tube.onUsersChanged();
    });

    Tube.users.bind('remove', function(user){
      var item = $('#list_' + user.get('id'));
      user.unbind();
      delete Tube.userList[user.get('id')];
      item.remove();
      Tube.onUsersChanged();
    });

    // Controller
    Tube.registerHandler = function(provider, handler) {
      Tube.handlers[provider] = handler;
    };
    Tube.setChannel = function(channel) {
       if (Tube.channel)
          Tube.channel.unbind();
       Tube.channel = new TubeChannel(channel);
       Tube.channel.bind('change', Tube.onChannelChange, Tube);

       // Connect if possible
       if (!Tube.connected)
          Tube.connect();
    };
    Tube.setTime = function(newTime) {
        if (this.video) {
            this.offsetTime = (new Date()) - (newTime*1000);
            this.video.seek(newTime);
        }
    };
    Tube.setVideo = function(opts) {
        var id = opts.id;
        var url = opts.url;
        var startTime = opts.time;
        var provider = opts.provider;
        var force = opts.force;

        if (this.video == null || this.video.provider != provider) {
            if (this.video) {
                this.video.stop();
            }
            this.video = null;
        }
        if (!this.video) {
            var handler = Tube.handlers[provider];
            if (handler) {
               this.video = new handler();
            } else {
              return;
            }
        }
        this.video_id = id;
        this.video.setVideo(url, startTime, force);
        this.offsetTime = (new Date()) - (startTime*1000);
        this.onSetVideo(opts);
    };
    Tube.onSetVideo = function(video) {
      $('#videoTitle').text(video.title);
      $('#playlist .item').removeClass('active');

      if (video.id) {
        $('#playlist_video_' + video.id).addClass('active');
      }
    };
    Tube.onTimeChange = function(newTime) {
        if (Tube.leader) {
          var currentTime = ((new Date()) - Tube.offsetTime) / 1000.0;
          if ((newTime - currentTime < -Tube.video.timeMargin) || (newTime - currentTime > Tube.video.timeMargin)) {
            Tube.offsetTime = (new Date()) - (newTime*1000);
            Tube.sendMessage({
                't': 'video_time',
                'time': newTime
            });
          }
        } else {
          var currentTime = ((new Date()) - Tube.offsetTime) / 1000.0;
          if ((newTime - currentTime < -Tube.video.timeMargin) || (newTime - currentTime > Tube.video.timeMargin)) {
            // Verify we haven't just got to the end of the video
            if (currentTime > Tube.video.duration())
              return;
            Tube.setTime(((new Date()) - Tube.offsetTime) / 1000.0);
          }
        }
    };
    Tube.onNewVideo = function(url, time) {
      $('#videoTitle').text(url);
      if (Tube.leader)
        Tube.sendMessage({'t': 'video', 'url': url, 'time': time, 'provider': this.video.provider});
    };
    Tube.onVideoFinished = function() {
      Tube.sendMessage({'t': 'video_finished'});
    };
    Tube.parseDuration = function(time) {
      var calc = time;
      var minutes = Math.floor(time / 60.0);
      var seconds = time % 60;
      return minutes + ':' + seconds;
    };
    Tube.addPlaylistItem = function(item) {
      var existing = Tube.playlist.get(item.id);
      if (existing)
        existing.set(item);
      else
        Tube.playlist.add(item);
    };
    Tube.removePlaylistItem = function(item) {
      Tube.playlist.remove(item.id);
    };
    Tube.sendMessage = function(data) {
      Tube.socket.send(JSON.stringify(data));
    };
    Tube.sendChat = function(content) {
      Tube.sendMessage({'t': 'message', 'content': content});
    }

    Tube.messageHandlers = {
      'hello': function(msg) { Tube.onauthenticated(msg); },
      'goaway': function(msg) { Tube.onauthfailed(msg); },
      'userjoined': function(msg) {
          var user = Tube.users.get(msg.user.id);
          if (user)
            Tube.users.remove(msg.user.id);
          Tube.users.add(msg.user);
          user = Tube.users.get(msg.user.id);
          if (Tube.user.get('id') == msg.user.id) {
            Tube.mod = msg['scope'] != '';
            Tube.leader = msg['leader'] ? true : false;
            Tube.users.each(function(user){ user.trigger('change') }); // hack: update mod ui controls
            Tube.onSetupUI();
          }
          Tube.userList[msg.user.id] = user;
       },
      'userleft': function(msg) { Tube.users.remove(msg.user.id); },
      'usermod': function(msg) {
          var oldName = Tube.userList[msg.user.id].get('name');
          var oldTripcode = Tube.userList[msg.user.id].get('tripcode');
          Tube.userList[msg.user.id].set(msg.user);
          if (Tube.user.get('id') == msg.user.id) { // Tube.user is separate
            Tube.user.set(msg.user);
          }
          // Handle name changes
          if (msg.user.name && msg.user.name != oldName) {
             Tube.chat.onchangename(msg.user.id, oldName, oldTripcode);
             if (Tube.user.get('id') == msg.user.id) {
                // Remember our tripcode
                $.ajax({
                    type: 'POST',
                    contentType: 'json',
                    data: JSON.stringify({name: Tube.tripcode}),
                    url: '/auth/name'});
            }
          }
          // Handle leader changes
          if (msg.user.leader) {
             Tube.leader = Tube.user.get('id') == msg.user.id;
             Tube.chat.onchangeleader(Tube.userList[msg.user.id]);
          }
      },
      'message': function(msg) { Tube.chat.onmessage(msg.uid, msg.content); },
      'playlist_video': function(msg) { Tube.addPlaylistItem(msg); },
      'playlist_video_removed': function(msg) { Tube.removePlaylistItem(msg); },
      'video': function(msg) {
          if (!Tube.admin || Tube.video == null || msg.force) {
            Tube.setVideo(msg);
            Tube.channel.set({'skip': 0});
          }
      },
      'video_time': function(msg) {
          // Set the time of the video, ignoring minor offsets
          if (!Tube.admin && Tube.video && Tube.video.control) {
              var currentTime = Tube.video.currentTime();
              if ((msg.time - currentTime < -Tube.video.timeMargin) || (msg.time - currentTime > Tube.video.timeMargin)) {
                  //console.log('Adjust offset:', msg.time - currentTime);
                  Tube.setTime(msg.time);
              }
          }
      },
      'chanmod': function(msg) {
        if (Tube.channel.get('id') == msg.id) {
          Tube.channel.set(msg);
        }
      },
      'skip': function(msg) { Tube.channel.set({'skip': msg.count}); }
    };

    Tube.connect = function() {
        Tube.setStatus('info', 'Connecting...');
        Tube.connected = true;

        Tube.socket = new WebSocket(WEB_SOCKET_PATH);
        Tube.socket.onmessage = function(evt) {
            var message = JSON.parse(evt.data);
            //console.log(message.t,message);
            //$('#debug').append('
' + evt.data + '
');

            if (Tube.messageHandlers[message.t])
              Tube.messageHandlers[message.t](message);
        };
        Tube.socket.onerror = function() {
          this.onclose();
        };
        Tube.socket.onclose = function() {
          Tube.users.reset();
          Tube.userList = {};
          if (Tube.connected) {
            // Connection failed, retry
            if (Tube.connectionAttempts > 10) {
               Tube.setStatus('critical', 'Server down, try again later');
            } else {
               Tube.setStatus('warning', 'Connection failed, retrying...');
               Tube.connectTimer = setTimeout(function(){ Tube.connectionAttempts += 1; Tube.connect(); }, 4000+(Math.random()*1000));
            }
          } else {
             Tube.connectionAttempts = 0;
          }
        };
        Tube.socket.onopen = function() {
            Tube.admin = false;

            // Tie the user with the websocket
            $.ajax({
                type: 'POST',
                url: '/auth/socket_token',
                success: function(data) {
                    Tube.sendMessage({
                        't': 'auth',
                        'auth_token': data.auth_token,
                        'name': data.name
                    });
                    Tube.tripcode = data.name;
                },
                error: function(xhr, status, error) {
                    if (error == 'Unauthorized') {
                      var name = Tube.tripcode ? Tube.tripcode : 'Anonymous'
	                    Tube.sendMessage({
	                        't': 'auth',
	                        'name': name
	                    });
                    } else {
                      Tube.socket.close();
                    }
                }
            });
        };
    };
    Tube.disconnect = function() {
        Tube.connected = false;
        Tube.socket.disconnect();
        Tube.socket = null;
    };

    Tube.onauthenticated = function(message) {
      // Verify we are using the correct version
      if (message.api != Tube.api) {
        window.location.reload();
        return;
      }
      if (Tube.user)
         Tube.user.unbind();
      Tube.user = new TubeUser(message.user);
      Tube.sendMessage({
          't': 'subscribe',
          'channel_id': Tube.channel.get('id')
      });

      // Remember our tripcode
      $.ajax({
          type: 'POST',
          contentType: 'json',
          data: JSON.stringify({name: Tube.tripcode}),
          url: '/auth/name'});
      Tube.clearStatus();
    };
    Tube.onauthfailed = function(message) {
       if (message.reason == 'ban') {
         Tube.setStatus('critical', 'You are banned from this channel: ' + message.comment);
       } else {
         Tube.setStatus('critical', 'Authorization failed');
         //console.log('OTHER REASON AUTH FAILED:', message);
       }
       Tube.connected = false;
       Tube.socket.close();
    };

    Tube.setStatus = function(code, message) {
       $('#status').attr('class', code).text(message);
    };

    Tube.clearStatus = function() {
       $('#status').attr('class', '');
    };
    Tube.setName = function(tripcode) {
      Tube.tripcode = tripcode;
      Tube.sendMessage({'t': 'usermod', 'name': tripcode});
    };
    Tube.onSetupUI = function() {
      // Basically we need to make sure all ui controls we need are shown
      if (Tube.mod)
        $('#playlistContainer').addClass('editable');
      else
        $('#playlistContainer').removeClass('editable');

      var toolbar = $('#userToolbar').empty();

      if (Tube.mod) {
        toolbar.append('Take Lead');
        toolbar.append('Sort Playlist');
        toolbar.append('Lock Playlist');
      }
      toolbar.append('Skip');
      toolbar.append('
Name:<input id="nameEntry" type="text" value=""/>');
      $('#nameEntry')[0].value = Tube.tripcode||'';
    }
    Tube.onUsersChanged = function() {
      $('#userCount').text(Tube.users.length);
      Tube.onChangeSkipCount(Tube.channel);
    }
})();

// Entry
$(document).ready(function() {
  function initVideo()
  {
    var plView = new Tube.Views.PlaylistView({el: $('#playlist')});
    $('#messageEntryBox').keypress(function(evt){
      if (evt.keyCode == 13 && evt.target.value != "") {
        if (evt.target.value.indexOf('/nick') == 0) {
          var newName = evt.target.value.split(' ')[1];
          if (newName)
            Tube.setName(newName);
        } else {
          Tube.sendChat(evt.target.value);
        }
        evt.target.value = '';
      }
    });

    $('#userToolbar').on('click', '#leadButton', function(event){
      event.preventDefault();
      Tube.sendMessage({'t': 'leader', 'user_id':Tube.user.get('id')});
    });

    $('#userToolbar').on('click', '#skipButton', function(event){
      event.preventDefault();
      Tube.sendMessage({'t': 'skip'});
    });

    $('#userToolbar').on('click', '#lockButton', function(event){
      event.preventDefault();
      Tube.sendMessage({'t': 'lock'});
    });

    $('#userList').on('click', 'a.buttonKickUser', function(event){
      event.preventDefault();
      var el = $(event.target).parents('li:first');
      Tube.sendMessage({'t': 'kick', 'user_id':el.attr('user_id')});
    });

    $('#userList').on('click', 'a.buttonBanUser', function(event){
      event.preventDefault();
      var el = $(event.target).parents('li:first');
      Tube.sendMessage({'t': 'ban', 'user_id':el.attr('user_id')});
    });

    $('#userToolbar').on('keypress', '#nameEntry', function(event){
      if (event.keyCode == 13 && event.target.value != "") {
        Tube.setName(event.target.value);
      }
    })

    $('#userToolbar').on('click', '#sortButton', function(event){
      event.preventDefault();
      if (Tube.sort) {
        $('#sortButton').text('Sort Playlist');
        $('#playlist').sortable('destroy');
        Tube.sort = false;
      } else {
        Tube.sort = true;
        $('#sortButton').text('Stop Sorting Playlist');
        $('#playlist').sortable({
          update : function () {
            var order = _.map($('#playlist').sortable('toArray'), function(el){ var l=el.split('_'); return parseInt(l[l.length-1]); });
            Tube.sendChat({'t': 'sort_videos', 'order':order});
          }
        })
      }
    });

    $('#userToolbar').on('click', '#lockButton', function(event){
      event.preventDefault();
      Tube.sendMessage({'t': 'lock', 'locked':!Tube.channel.get('locked')});
    });

    $('#playlistEntryBox').keypress(function(evt){
      if (evt.keyCode == 13 && evt.target.value != "") {
        Tube.sendMessage({'t': 'add_video', 'url': evt.target.value});
        evt.target.value = '';
      }
    });
  };

  function initAdmin()
  {
    Tube.makeAdmin($('#adminroot'));
  };

  if ($('#video')[0])
    initVideo();
  else if ($('#adminroot')[0])
    initAdmin();
});


text:
{
  if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
    return false;
  }

  return typeof window !== "undefined" && typeof document !== "undefined";
}

redpajama_set_name: RedPajamaGithub


text:
/* Russian
 * Boris Mihajlovic & Brian Mason
 */

var localizedStrings = new Array;

localizedStrings[": "]
	= ": ";
localizedStrings["Unable to load plugin"]
	= "Невозможно загрузить плагин";
localizedStrings["Calendars:"]
	= "Календари:";
localizedStrings["Show events happening within the next:"]
	= "Показывать события происходящие в течение:";
localizedStrings["Check for new version"]
	= "Проверить обновление";
localizedStrings["No calendars selected."]
	= "Нет выбранных календарей.";
localizedStrings["No events today or in the next %i day(s)."]
	= "Нет событий сегодня или в следующие %i дней.";
localizedStrings["Done"]
	= "Выполнено";
localizedStrings["1 day"]
	= "1 дня";
localizedStrings["%i days"]
	= "%i дней";
localizedStrings["Today"]
	= "Сегодня";
localizedStrings["Tomorrow"]
	= "Завтра";
localizedStrings["Location: "]
	= "Место: ";
localizedStrings["Birthdays"]
	= "Календарь дней рождений";
localizedStrings["%@'s Birthday"]
	= "День Рождения %@";
localizedStrings["Open iCal"]
	= "Открыть iCal";


text:
module RuboCop
  # This module holds the RuboCop version information.
  module Version
    STRING = '0.53.0'.freeze

    MSG = '%<version>s (using Parser %<parser_version>s, running on ' \
          '%<ruby_engine>s %<ruby_version>s %<ruby_platform>s)'.freeze

    def self.version(debug = false)
      if debug
        format(MSG, version: STRING, parser_version: Parser::VERSION,
                    ruby_engine: RUBY_ENGINE, ruby_version: RUBY_VERSION,
                    ruby_platform: RUBY_PLATFORM)
      else
        STRING
      end
    end
  end
end


text: typedef Interrupt<EE_READY_vect_num> EE_READYInterrupt;


text:
<?php

namespace PDepend\Source\Language\PHP;

use PDepend\Source\AST\ASTClosure;
use PDepend\Source\AST\ASTFieldDeclaration;
use PDepend\Source\AST\ASTType;
use PDepend\Source\Parser\UnexpectedTokenException;
use PDepend\Source\Tokenizer\Tokens;

/**
 * Concrete parser implementation that supports features up to PHP version 7.4.
 *
 * @copyright 2008-2017 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 *
 * @since 2.4
 */
abstract class PHPParserVersion74 extends PHPParserVersion73
{
    /**
     * Regular expression for integer numbers representation.
     * (Add support for octal explicit notation.)
     *
     * @see https://php.net/manual/en/language.types.integer.php
     * @see https://github.com/php/doc-en/blob/085c38d45e466691062b4444c71f4dbe4198f884/language/types/integer.xml#L79-L91
     */
    const REGEXP_INTEGER = '/^(
                       0
                       |
                       [1-9][0-9]*(?:_[0-9]+)*
                       |
                       0[xX][0-9a-fA-F]+(?:_[0-9a-fA-F]+)*
                       |
                       0[0-7]+(?:_[0-7]+)*
                       |
                       0[bB][01]+(?:_[01]+)*
                     )$/x';

    protected $possiblePropertyTypes = array(
        Tokens::T_STRING,
        Tokens::T_ARRAY,
        Tokens::T_QUESTION_MARK,
        Tokens::T_BACKSLASH,
        Tokens::T_CALLABLE,
        Tokens::T_SELF,
    );

    protected function parseUnknownDeclaration($tokenType, $modifiers)
    {
        /**
         * Typed properties
         * https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.typed-properties
         */
        if (in_array($tokenType, $this->possiblePropertyTypes, true)) {
            $type = $this->parseTypeHint();
            $declaration = $this->parseFieldDeclaration();
            $declaration->prependChild($type);
            $declaration->setModifiers($modifiers);

            return $declaration;
        }

        return parent::parseUnknownDeclaration($tokenType, $modifiers);
    }

    /**
     * @return ASTClosure
     */
    protected function parseLambdaFunctionDeclaration()
    {
        $this->tokenStack->push();

        if (Tokens::T_FN === $this->tokenizer->peek()) {
            $this->consumeToken(Tokens::T_FN);
        }

        $closure = $this->builder->buildAstClosure();
        $closure->setReturnsByReference($this->parseOptionalByReference());
        $closure->addChild($this->parseFormalParameters($closure));
        $this->parseCallableDeclarationAddition($closure);

        $closure->addChild(
            $this->buildReturnStatement(
                $this->consumeToken(Tokens::T_DOUBLE_ARROW)
            )
        );

        return $this->setNodePositionsAndReturn($closure);
    }

    /**
     * Override PHP 7.3 checkEllipsisInExpressionSupport to stop throwing the
     * parsing exception.
     *
     * @return void
     */
    protected function checkEllipsisInExpressionSupport()
    {
        // Do not throw the exception from parent PHP 7.3
    }
}


text:
package gov.med.va.innovations.domain;

import gov.med.va.innovations.service.EventManager;

import java.io.Serializable;

public abstract class VistaTO implements Serializable {

	private static final long serialVersionUID = -7656569560070101993L;
	private String errorMessage;
	private boolean htmlApplied;
	public String getErrorMessage() {
		return errorMessage;
	}
	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public abstract Integer getListLength();

	public abstract EventManager.EventCode getEventCode();

	public void setHtmlApplied(boolean htmlApplied) {
		this.htmlApplied = htmlApplied;
	}
	public boolean isHtmlApplied() {
		return htmlApplied;
	}
}


text:
@interface UINavigationItem (Margin)

@end


text:
<?php
namespace Test\Cache;

class TestListModel{
    public $name = "Hello";
    public $address = "World";
    public $city = "";
}

class RedisListCacheTest extends \Tests\TestCase
{
    public function testExpireOnMethod()
    {
        $conf = include(__DIR__ . "/../../testconf.php");
        $redisConnection = $conf['redis'];
        $expirable = new \QzPhp\Cache\RedisListCache("redis.cache", [
            "connection" => $redisConnection,
            "expire" => 3
        ]);
        $context = (object)[
            "cacheCall" => []
        ];

        $onExpire = function($key) use($context){
            if(empty($context->cacheCall[$key])){
                $context->cacheCall[$key] = 0;
            }
            $context->cacheCall[$key]++;
            return [
                new TestListModel()
            ];
        };
        $value1 = $expirable->get('Luke', $onExpire);
        $value1_1 = $expirable->get('Luke', $onExpire);
        $value2 = $expirable->get('Anakin', $onExpire);
        sleep(4);
        $value1 = $expirable->get('Luke', $onExpire);
        $value1_1 = $expirable->get('Luke', $onExpire);
        $value2 = $expirable->get('Anakin', $onExpire);
        $value2 = $expirable->reseed('Anakin', $onExpire);
        $value2 = $expirable->get('Anakin', $onExpire);

        $this->assertEquals(2, $context->cacheCall['Luke']);
        $this->assertEquals(3, $context->cacheCall['Anakin']);

        $redis = new \Predis\Client($redisConnection);
        $redis->flushAll();
    }
}


text:
package com.bionic.dao;

import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;

import com.bionic.dao.generic.AbstractDAO;
import com.bionic.ejb.Comment;
import com.bionic.ejb.Notice;
import com.bionic.ejb.User;

public class NoticeDAO extends AbstractDAO<Notice, Long> {
	@Inject
	private UserDAO userDAO;

	public NoticeDAO() {
		super(Notice.class);
	}

	/**
	 *
	 * @param noticeId
	 *            id of the specified `notice`
	 * @return list of comments of specified `notice`
	 */
	public List<Comment> findComments(final long noticeId) {
		return em.createNamedQuery("Notice.findComments", Comment.class)
				.setParameter("id", noticeId).getResultList();
	}

	/**
	 *
	 * @param categoryId
	 *            id of the specified `category`
	 * @return list of notices of specified `category`
	 */
	public List<Notice> findByCategory(final long categoryId) {
		return em.createNamedQuery("Notice.findByCategory", Notice.class)
				.setParameter("id", categoryId).getResultList();
	}

	/**
	 *
	 * @param categoryName
	 *            name of the specified `category`
	 * @return list of notices of specified `category`
	 */
	public List<Notice> findByCategoryName(String categoryName) {
		return em.createNamedQuery("Notice.findByCategoryName", Notice.class)
				.setParameter("name", categoryName).getResultList();
	}

	/**
	 *
	 * @param userId
	 *            id of the specified `user`
	 * @return list of notices of specified `user`
	 */
	public List<Notice> findByUser(final long userId) {
		return em.createNamedQuery("Notice.findByUser", Notice.class)
				.setParameter("id", userId).getResultList();
	}

	public List<Notice> getPagedObjects(int pageIndex, int pageSize,long cat, String street,double longitude,
			double latitude, double radius, boolean myloc){
		try{
		List<Notice> resultList= new LinkedList<Notice>();
		if(myloc){
		List<User> users = userDAO.getNBbyLoc(longitude, latitude, radius);
		if(!"".equals(street)|street!=null){
		for(User user: users){
			if(cat!=-1){
			resultList.addAll(
		em
		.createQuery(
				"SELECT n FROM Notice n WHERE n.user.id = :nid AND n.user.address LIKE :street and n.category.id= :cid",
				Notice.class).setParameter("nid", user.getId()).setParameter("street","%"+street+"%")
		.setParameter("cid", cat).getResultList());
			}else{
				resultList.addAll(
						em
						.createQuery(
								"SELECT n FROM Notice n WHERE n.user.id = :nid AND n.user.address LIKE :street",
								Notice.class).setParameter("nid", user.getId()).setParameter("street","%"+street+"%")
						.getResultList());
			}
		}
		}else {
			for(User user: users){
				if(cat!=-1){
			resultList.addAll(
		em
		.createQuery(
				"SELECT n FROM Notice n WHERE n.user.address = :nid and n.category.id= :cid",
				Notice.class).setParameter("cid", cat).setParameter("nid", user.getId())
		.getResultList());
				}else{
					resultList.addAll(
							em
							.createQuery(
									"SELECT n FROM Notice n WHERE n.user.address = :nid",
									Notice.class).setParameter("nid", user.getId())
							.getResultList());
				}
		}
		}
		}
		else{
			if(!"".equals(street)|street!=null){
				if(cat!=-1){
					resultList.addAll(em.createQuery(
						"SELECT n FROM Notice n WHERE n.user.address LIKE :street and n.category.id= :cid",
						Notice.class).setParameter("cid", cat).setParameter("street","%"+street+"%")
				.getResultList());
				}else{
					resultList.addAll(em.createQuery(
							"SELECT n FROM Notice n WHERE n.user.address LIKE :street",
							Notice.class).setParameter("street","%"+street+"%")
					.getResultList());
				}
				} else {
					if(cat!=-1){
				resultList.addAll(
				em
				.createQuery("SELECT n FROM Notice n where n.category.id= :cid",
						Notice.class)
				.setParameter("cid", cat).getResultList());
					}else{
						resultList.addAll(
								em
								.createQuery("SELECT n FROM Notice n ",
										Notice.class).getResultList());
					}
				}
		}
		if (pageSize*pageIndex<resultList.size()){
			if(pageSize*(pageIndex+1)<resultList.size())
		return resultList.subList(pageSize*pageIndex, pageSize*(pageIndex+1)) ;
			else{ return resultList.subList(pageSize*pageIndex,resultList.size()-1);}
		} else return null;
		}catch(Exception e){
			e.printStackTrace();
			return getAll();
		}
	}

	@Override
	public void delete(Long id) {
		List<Comment> list = findComments(id);

		if (list != null) {
			for (Comment c : list) {
				c.setDeleted(true);
				em.merge(c);
			}
		}
		super.delete(id);
	}

}


text:
package com.springcryptoutils.core.cipher.symmetric;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class Base64EncodedCiphererImplTest {

    @Autowired
    private Base64EncodedKeyGenerator generator;

    @Autowired
    private Base64EncodedCipherer encrypter;

    @Autowired
    private Base64EncodedCipherer decrypter;

    private static final String iv = "AQIDBAUGAQI=";

    private String key;

    @Before
    public void setup() {
        assertNotNull(generator);
        assertNotNull(encrypter);
        assertNotNull(decrypter);

        key = generator.generate();
        assertNotNull(key);
        assertTrue(key.length() > 0);
    }

    @Test
    public void testCipher() throws UnsupportedEncodingException {
        final String message = "this is a top-secret message";
        String encryptedMessage = encrypter.encrypt(key, iv, message);
        assertNotNull(encryptedMessage);
        String decryptedMessage = decrypter.encrypt(key, iv, encryptedMessage);
        assertNotNull(decryptedMessage);
        assertEquals(message, decryptedMessage);
    }

    @Test
    public void testCipherInALoop() throws UnsupportedEncodingException {
        for (int i = 0; i < 100; i++) {
            final String message = UUID.randomUUID().toString();
            String encryptedMessage = encrypter.encrypt(key, iv, message);
            assertNotNull(encryptedMessage);
            String decryptedMessage = decrypter.encrypt(key, iv, encryptedMessage);
            assertNotNull(decryptedMessage);
            assertEquals(message, decryptedMessage);
        }
    }

    @Test(expected = SymmetricEncryptionException.class)
    public void testCipherInDecryptionModeFailsWithValidBase64ButInvalidCipherInput() {
        // this is valid base64 but invalid cipher
        final String message = "Y2lwcGEK";
        decrypter.encrypt(key, iv, message);
    }

    @Test(expected = SymmetricEncryptionException.class)
    public void testCipherInDecryptionModeFailsWithInvalidBase64Input() {
        // this is invalid base64 and invalid cipher
        final String message = "this is not base64";
        decrypter.encrypt(key, iv, message);
    }

}


text:
// -----------------------------------------------------------------------
//   <copyright file="Remote.cs" company="Asynkron HB">
//       Copyright (C) 2015-2018 Asynkron HB All rights reserved
//   </copyright>
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.Extensions.Logging;

namespace Proto.Remote
{
    public static class Remote
    {
        private static readonly ILogger Logger = Log.CreateLogger(typeof(Remote).FullName);

        private static Server _server;
        private static readonly Dictionary<string, Props> Kinds = new Dictionary<string, Props>();
        public static RemoteConfig RemoteConfig { get; private set; }
        public static PID ActivatorPid { get; private set; }

        private static EndpointReader _endpointReader;

        public static string[] GetKnownKinds()
        {
            return Kinds.Keys.ToArray();
        }

        public static void RegisterKnownKind(string kind, Props props)
        {
            Kinds.Add(kind, props);
        }

        public static Props GetKnownKind(string kind)
        {
            if (Kinds.TryGetValue(kind, out var props)){
                return props;
            }
            throw new ArgumentException($"No Props found for kind '{kind}'");
        }

        public static void Start(string hostname, int port)
        {
            Start(hostname, port, new RemoteConfig());
        }

        public static void Start(string hostname, int port, RemoteConfig config)
        {
            RemoteConfig = config;

            ProcessRegistry.Instance.RegisterHostResolver(pid => new RemoteProcess(pid));

            EndpointManager.Start();
            _endpointReader = new EndpointReader();
            _server = new Server
            {
                Services = { Remoting.BindService(_endpointReader) },
                Ports = { new ServerPort(hostname, port, config.ServerCredentials) }
            };
            _server.Start();

            var boundPort = _server.Ports.Single().BoundPort;
            var boundAddr = $"{hostname}:{boundPort}";
            var addr = $"{config.AdvertisedHostname??hostname}:{config.AdvertisedPort?? boundPort}";
            ProcessRegistry.Instance.Address = addr;

            SpawnActivator();

            Logger.LogDebug($"Starting Proto.Actor server on {boundAddr} ({addr})");
        }

        public static void Shutdown(bool gracefull = true)
        {
            try
            {
                if (gracefull)
                {
                    EndpointManager.Stop();
                    _endpointReader.Suspend(true);
                    StopActivator();
                    _server.ShutdownAsync().Wait(10000);
                }
                else
                {
                    _server.KillAsync().Wait(10000);
                }

                Logger.LogDebug($"Proto.Actor server stopped on {ProcessRegistry.Instance.Address}. Graceful:{gracefull}");
            }
            catch(Exception ex)
            {
                _server.KillAsync().Wait(1000);
                Logger.LogError($"Proto.Actor server stopped on {ProcessRegistry.Instance.Address} with error:\n{ex.Message}");
            }
        }

        private static void SpawnActivator()
        {
            var props = Props.FromProducer(() => new Activator()).WithGuardianSupervisorStrategy(Supervision.AlwaysRestartStrategy);
            ActivatorPid = RootContext.Empty.SpawnNamed(props, "activator");
        }

        private static void StopActivator()
        {
            ActivatorPid.Stop();
        }

        public static PID ActivatorForAddress(string address)
        {
            return new PID(address, "activator");
        }

        public static Task<ActorPidResponse> SpawnAsync(string address, string kind, TimeSpan timeout)
        {
            return SpawnNamedAsync(address, "", kind, timeout);
        }

        public static async Task<ActorPidResponse> SpawnNamedAsync(string address, string name, string kind, TimeSpan timeout)
        {
            var activator = ActivatorForAddress(address);

            var res = await RootContext.Empty.RequestAsync<ActorPidResponse>(activator, new ActorPidRequest
            {
                Kind = kind,
                Name = name
            }, timeout);

            return res;
        }

        public static void SendMessage(PID pid, object msg, int serializerId)
        {
            var (message, sender, header) = Proto.MessageEnvelope.Unwrap(msg);

            var env = new RemoteDeliver(header, message, pid, sender, serializerId);
            EndpointManager.RemoteDeliver(env);
        }
    }
}


text:
* fix compatibility to feature node 0.9.x versions

##1.1.6

* remove compilation flags from binding.gyp that cause build failure with older gcc versions
* cleanups

##1.1.5

* remove old nodejs version support prior to 0.8.0
* fix building

## 1.1.4

* Cleaned all opened and not closed ScopeHandlers
* Added new node-gyp build file. Next release will not support node-waf and node version < 0.8.x

## 1.1.3

* Added node 0.7.x support

## 1.1.2

* Fix compiling on Darwin and Windows. Thanks to Vinay Pulim https://github.com/milewise

## 1.1.1

* Minor change to package to support 0.4 version

## 1.1.0

* Port to 0.5.7 Node version

## 1.0.2

* Fixed MAIL log facility
* Removed leaking Syslog underlying function object from top-level library.

## 1.0.1

* Added setMask (Jeremy Childs)

## 1.0.0

* Initial release version


text:
/*****************************************************************************/
/* POSIX Lab Session -- Exercise #2                                          */
/*****************************************************************************/

/* In this exercise, we revisit the termination pattern from the
 * previous exercise: the environment thread may wait for any thread,
 * and prints information about the terminated thread.
 */

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "debug.h"

#define MAXTHREADS 256 /* Maximum number of threads in the program           */

typedef struct {
  pthread_cond_t   cond_var;          /* signaled when a thread terminates   */
  pthread_mutex_t  mutex;             /* mutex for protecting this state     */
  pthread_t        thread_id;         /* id of the threads that terminates   */
  unsigned int     completed_threads; /* # of terminated threads             */
} shared_state_t;

shared_state_t shared_state;   /* shared state that controls the termination */
sem_t ack_semaphore;           /* semaphore to synchronize threads & env.    */

void *thread_job(void *no_argument);

/*****************************************************************************/
/* Simple job executed by a thread:                                          */
/* - prints some information on the running thread                           */
/* - do some useless iterations                                              */
/* - notify the environment thread that this job has completed its mission   */

void *thread_job(void *no_argument) {
  pthread_t my_task_id = pthread_self();
  int i = 0, iter = labs (random())/10;

  printf("Thread %p : Start processing, %d iterations\n", my_task_id, iter);
  while(i < iter) i++;

  /* Notify the environment thread that this thread is now completed         */
  sem_wait(&ack_semaphore);
  shared_state.thread_id = my_task_id;
  shared_state.completed_threads++;
  sem_post(&ack_semaphore);

  pthread_cond_signal(&shared_state.cond_var);

  printf("Thread %p : End of processing\n", my_task_id);
  pthread_exit(NULL);
}

/*****************************************************************************/
/* Main entrypoint for this program                                          */

int main(int argc, char *argv[]) {
  pthread_t thr_main = pthread_self();
  pthread_t Threads[MAXTHREADS];
  int i, ack_threads, nThreads;

   /* Check command-line parameters                                          */
  if (argc != 2){
    printf(" Usage : %s [number-of-threads]\n", argv[0]);
    exit(1);
  }

  nThreads = atoi(argv[1]);
  if (nThreads > MAXTHREADS){
    printf(" Too many threads, should be <= %d\n", MAXTHREADS);
    exit(2);
  }

  /* Initialize parameters                                                   */
  srandom(time(NULL));  /* Initialize generator of random numbers            */

  ack_threads = 0;
  shared_state.completed_threads = 0;
  pthread_cond_init(&shared_state.cond_var, NULL);
  pthread_mutex_init(&shared_state.mutex, NULL);
  sem_init(&ack_semaphore, 0, 0);

  /* Create threads */
  while (i < nThreads) {
    pthread_create(&Threads[i], NULL, &thread_job, NULL);
    i++;
  }

  /* Wait for completion of all threads */
  sem_post(&ack_semaphore);
  while (ack_threads != nThreads) {
    pthread_mutex_lock(&shared_state.mutex);

    pthread_cond_wait(&shared_state.cond_var, &shared_state.mutex);
    ack_threads++;

    pthread_mutex_unlock(&shared_state.mutex);
  }

  /* End of the program, we print some log and finish the program            */
  printf("environment thread (Tid %p) : end,  %d/%d/%d ",
         thr_main, ack_threads, shared_state.completed_threads, nThreads);

  /* The test is a success iff all created threads performed the notification*/
  if ((ack_threads == shared_state.completed_threads)
      && (ack_threads == nThreads)) {
    printf ("[SUCCESS]\n");
    return EXIT_SUCCESS;
  }
  else {
    printf ("[FAIL]\n");
    return EXIT_FAILURE;
  }
}


text:
using System;
using Ritter.Atlas;

namespace UsageConsole
{
  class Program
  {
    static void Main()
    {
      Action<string> Display = s => Console.WriteLine(s);
      var zipcode = new ZipCode { Id = "17011" };
      var zipcode2 = new ZipCode { Id = "90210" };
      var zipcode3 = new ZipCode { Id = "75017" };
      var zipcode4 = new ZipCode { Id = "75020" };
      var zipcode5 = new ZipCode { Id = "12345" };
      var zipcode6 = new ZipCode { Id = "12345" };
      Console.ReadKey();
    }
  }
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Hqub.MusicBrainz.API.Entities.Metadata;

namespace Hqub.MusicBrainz.API.Test
{
    // Resource: release-group-search.xml
    // ReleaseGroup.Search("artist:(bob dylan)", 10);
    //
    // http://musicbrainz.org/ws/2/release-group?query=artist:%28bob%20dylan%29&limit=10

    [TestClass]
    public class ReleaseGroupListTests
    {
        ReleaseGroupMetadata data;

        public ReleaseGroupListTests()
        {
            this.data = TestHelper.Get<ReleaseGroupMetadata>("releasegroup-search.xml", false);
        }

        [TestMethod]
        public void TestReleaseGroupListQueryCount()
        {
            var group = data.Collection;

            Assert.AreEqual(2787, group.QueryCount);
        }

        [TestMethod]
        public void TestReleaseGroupListCount()
        {
            var group = data.Collection.Items;

            Assert.AreEqual(10, group.Count);
        }

        [TestMethod]
        public void TestReleaseGroupListElements()
        {
            var group = data.Collection.Items[0];

            Assert.AreEqual("fc325dd3-73ed-36aa-9c77-6b65a958e3cf", group.Id);
            Assert.AreEqual("Album", group.Type);
            Assert.AreEqual(100, group.Score);

            Assert.AreEqual("Desire", group.Title);
            Assert.AreEqual("Album", group.PrimaryType);

            Assert.IsNotNull(group.Releases);
            Assert.IsNotNull(group.Credits);
            Assert.IsNotNull(group.Tags);
        }
    }
}


text:
<mongoChangeLog>
    <changeSet changeId="ChangeSet-1" author="maksym.khudiakov">
        <script>
            db.organization.insert({
                "Name" : "10Gen-Other", "Location" : "NYC", DateFounded : {"Year":2008, "Month":01, "day":01}
            });
        </script>
    </changeSet>
</mongoChangeLog>


text:
@interface PBDocumentArtboardManagerDelegate : NSObject

//添加成功之后上报埋点
- (void) addDocumentArtboardSuccessWithType:(NSString *)type;
@end


text:
* Presenter: [Daniel Pumpe](https://github.com/dpumpe)
* Duration: 90 min
* Time: Tuesday, 16:00 - 17:30
* Location: Central seminar room

## Abstract

In this tutorial I will briefly introduce D3PO, which addresses the inference
problem of denoising, deconvolving, and decomposing photon observations. Its
primary goal is thereby to simultaneously but individual reconstruct the diffuse
and point like photon flux given a photon count image.

D3PO is based on information field theory (IFT), which will be introduced as
well. IFT is a  Bayesian framework for signal processing and image
reconstruction. For practical calculations 'Numerical information field theory'-
NIFTy can be used. NIFTy is a versatile Python library to enable the development
of signal inference algorithms that operate regardless of the underlying spatial
grid and its resolution.

Within a first practical hands on session we will guide the audience thru some
examples (Wiener filter etc.) and thereby demonstrate NIFTy principle
capabilities. Then the usage of D3PO will be demonstrated.

## How to prepare

1. Install NIFTy by pip install ift_nifty
2. Install D3PO by pip install ift_d3po

Detailed instruction how to install [NIFTy](http://wwwmpa.mpa-garching.mpg.de/ift/nifty/install.html#download-label)
and [D3PO](http://wwwmpa.mpa-garching.mpg.de/ift/d3po/install.html#download-label)

First you should install all dependencies ([NUMPy](http://www.numpy.org), [SciPy](http://www.scipy.org), [matplotlib](http://matplotlib.org),and the optional ones: [GFFT](https://github.com/mrbell/gfft), [healpy](https://github.com/healpy/healpy), [libsharpwrapper](https://github.com/mselig/libsharp-wrapper)) needed for NIFTy, followed by the NIFTy installation itself. Last one may install D3PO as it depends on NIFTy.

After successfully installing everything we will go thru the [Wiener filter](https://github.com/gammapy/PyGamma15/blob/gh-pages/tutorials/d3po/Wiener_filter.ipynb) and D3PO demo.
Please note that NIFTy as well as D3PO only work with Python 2.7.

In case the installation does not work, please get in contact with me dpumpe@mpa-garching.mpg.de.

## Agenda

- Introduction to Information field theory
- Numerical information field theory, what are its capabilities?
  Hands so session (Wiener filter etc.)
- Introduction to D3PO - Denoising, Deconvolving, and Decomposing photon observations
- Hands on session with D3PO

## Going further

If you'd like to learn more, here's some useful references:

* D3PO [code](https://github.com/information-field-theory/d3po),
  [docs](http://wwwmpa.mpa-garching.mpg.de/ift/d3po/)
* Nifty [code](https://github.com/information-field-theory/nifty),
  [docs](http://wwwmpa.mpa-garching.mpg.de/ift/nifty/)
* [D3PO algorithm paper](http://labs.adsabs.harvard.edu/adsabsadsabs/abs/2015A%26A...574A..74S/)
* [D3PO application to Fermi-LAT data](http://labs.adsabs.harvard.edu/adsabsadsabs/abs/2015A%26A...581A.126S/)
* [Information Field Theory webpage](https://wwwmpa.mpa-garching.mpg.de/ift/)


text:
#region → Usings   .
using citPOINT.eNeg.Common;
using citPOINT.eNeg.ViewModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using citPOINT.eNeg.Common.eNegApps;
using citPOINT.eNeg.Apps.Common;
#endregion

#region → History  .
/* Date         User            Change
 *
 * 23.08.10     Dergham        creation
 * 24.08.10    Yousra Reda       MEF/Load Data
 */

# endregion

#region → ToDos    .

/*
 * Date         set by User     Description
 *
 *
*/

# endregion
namespace citPOINT.eNeg.Client
{
    /// <summary>
    /// Main Negotiation View
    /// </summary>
    public partial class MainNegotiationView : UserControl, ICleanup
    {
        #region → Constructors   .

        /// <summary>
        /// Default constructor
        /// </summary>
        public MainNegotiationView()
        {
            InitializeComponent();

            #region → Initialize the UserControl Width & Height            .

            var viewsAdjustSize = new ViewsAdjustSize(new UserControl());
            viewsAdjustSize.AfterResize += new EventHandler<EventArgsSize>(ViewsAdjustSizeAfterResize);
            viewsAdjustSize.ReSize();

            #endregion initialize the UserControl Width & Height

            #region → Registeration for needed messages in eNegMessenger   .

            eNegMessanger.NewPopUp.Register(this, OpenPopUp);

            AppConfigurations.ApplicationRegion = uxTabsArea;

            #endregion

            this.Loaded += new RoutedEventHandler(MainNegotiationViewLoaded);
        }

        #endregion Constructor

        #region → Event Handlers .

        /// <summary>
        /// Handles the Loaded event of the MainNegotiationView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void MainNegotiationViewLoaded(object sender, RoutedEventArgs e)
        {
            ViewsAdjustSizeAfterResize(sender, null);
        }

        /// <summary>
        /// For Resizing the Controls According to the New Size
        /// </summary>
        /// <param name="sender">Value of Sender</param>
        /// <param name="e">Value of EventArgs Size</param>
        private void ViewsAdjustSizeAfterResize(object sender, EventArgsSize e)
        {
            if (this.uxTabsArea.ActualHeight > 100 && this.uxNegotiationsSide.ActualWidth > 100)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MainPlatformInfo.Instance.HostRegionSizeDetails
                        = new ApplicationHostBounds()
                        {
                            Height = this.uxTabsArea.ActualHeight - 27,
                            Left = this.uxNegotiationsSide.ActualWidth + 20,
                            Top = 115,
                            Width = this.uxTabsArea.ActualWidth - 2
                        };
                });

            }
        }

        #endregion Event Handlers

        #region → Methods        .

        #region → Private        .

        /// <summary>
        /// Opens the pop up.
        /// </summary>
        /// <param name="windowName">Name of the window.</param>
        private void OpenPopUp(string windowName)
        {

            if (eNegMessanger.NewPopUp.PopUpType == eNegMessanger.PopUpType.SelectOrganizationToPublish.ToString())
            {
                #region Show PopUp window to choose identify select set of organizations want to publish for them
                PopUpWindow SelectOrgnaizatioConfirm = new PopUpWindow(windowName);
                SelectOrgnaizatioConfirm.DataContext = this.DataContext;
                SelectOrgnaizatioConfirm.Content = new PublishNegotiationPopUp();
                SelectOrgnaizatioConfirm.CenterWindow();
                SelectOrgnaizatioConfirm.ShowDialog();
                #endregion
            }
            if (eNegMessanger.NewPopUp.PopUpType == eNegMessanger.PopUpType.SavePDF.ToString())
            {
                #region Show PopUp window to Save just generated PDF for some messages or conversations
                PopUpWindow SavePDF = new PopUpWindow(windowName);
                SavePDF.DataContext = this.DataContext;
                SavePDF.Content = new SavePDFView();
                SavePDF.CenterWindow();
                SavePDF.ShowDialog();
                #endregion
            }
            if (eNegMessanger.NewPopUp.PopUpType == eNegMessanger.PopUpType.NewConversation.ToString())
            {
                #region Show PopUp window to add new conversation
                PopUpWindow addNewconverastion = new PopUpWindow(windowName);
                addNewconverastion.DataContext = this.DataContext;
                addNewconverastion.Content = new AddConversation();
                addNewconverastion.CenterWindow();
                addNewconverastion.ShowDialog();
                #endregion
            }
        }

        #endregion

        #region → Public         .

        /// <summary>
        /// ICleanup interface implementation
        /// </summary>
        public void Cleanup()
        {
            // call Cleanup on its ViewModel
            if (DataContext != null)
                ((ICleanup)this.DataContext).Cleanup();

            // Cleanup itself
            Messenger.Default.Unregister(this);
        }
        #endregion

        #endregion Methods
    }
}


text:
#pragma once

#include "wled.h"

/* This driver reads quaternion data from the MPU6060 and adds it to the JSON
   This example is adapted from:
   https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050/examples/MPU6050_DMP6_ESPWiFi

   Tested with a d1 mini esp-12f

  GY-521  NodeMCU
  MPU6050 devkit 1.0
  board   Lolin         Description
  ======= ==========    ====================================================
  VCC     VU (5V USB)   Not available on all boards so use 3.3V if needed.
  GND     G             Ground
  SCL     D1 (GPIO05)   I2C clock
  SDA     D2 (GPIO04)   I2C data
  XDA     not connected
  XCL     not connected
  AD0     not connected
  INT     D8 (GPIO15)   Interrupt pin

  Using usermod:
  1. Copy the usermod into the sketch folder (same folder as wled00.ino)
  2. Register the usermod by adding #include "usermod_filename.h" in the top and registerUsermod(new MyUsermodClass()) in the bottom of usermods_list.cpp
  3. I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h file
     for both classes must be in the include path of your project. To install the
     libraries add I2Cdevlib-MPU6050@fbde122cc5 to lib_deps in the platformio.ini file.
  4. You also need to change lib_compat_mode from strict to soft in platformio.ini (This ignores that I2Cdevlib-MPU6050 doesn't list platform compatibility)
  5. Wire up the MPU6050 as detailed above.
*/

#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void IRAM_ATTR dmpDataReady() {
    mpuInterrupt = true;
}

class MPU6050Driver : public Usermod {
  private:
    MPU6050 mpu;
    bool enabled = true;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    //NOTE: some of these can be removed to save memory, processing time
    //      if the measurement isn't needed
    Quaternion qat;         // [w, x, y, z]         quaternion container
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 gy;         // [x, y, z]            gyro sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector

    static const int INTERRUPT_PIN = 15; // use pin 15 on ESP8266

  public:
    //Functions called by WLED

    /*
     * setup() is called once at boot. WiFi is not yet connected at this point.
     */
    void setup() {
      PinManagerPinType pins[2] = { { i2c_scl, true }, { i2c_sda, true } };
      if (!pinManager.allocateMultiplePins(pins, 2, PinOwner::HW_I2C)) { enabled = false; return; }
      // join I2C bus (I2Cdev library doesn't do this automatically)
      #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
      #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
      #endif

      // initialize device
      DEBUG_PRINTLN(F("Initializing I2C devices..."));
      mpu.initialize();
      pinMode(INTERRUPT_PIN, INPUT);

      // verify connection
      DEBUG_PRINTLN(F("Testing device connections..."));
      DEBUG_PRINTLN(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

      // load and configure the DMP
      DEBUG_PRINTLN(F("Initializing DMP..."));
      devStatus = mpu.dmpInitialize();

      // supply your own gyro offsets here, scaled for min sensitivity
      mpu.setXGyroOffset(220);
      mpu.setYGyroOffset(76);
      mpu.setZGyroOffset(-85);
      mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

      // make sure it worked (returns 0 if so)
      if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        DEBUG_PRINTLN(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        DEBUG_PRINTLN(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        DEBUG_PRINTLN(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
      } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        DEBUG_PRINT(F("DMP Initialization failed (code "));
        DEBUG_PRINT(devStatus);
        DEBUG_PRINTLN(F(")"));
      }
    }

    /*
     * connected() is called every time the WiFi is (re)connected
     * Use it to initialize network interfaces
     */
    void connected() {
      //DEBUG_PRINTLN("Connected to WiFi!");
    }

    /*
     * loop() is called continuously. Here you can check for events, read sensors, etc.
     */
    void loop() {
      // if programming failed, don't try to do anything
      if (!enabled || !dmpReady || strip.isUpdating()) return;

      // wait for MPU interrupt or extra packet(s) available
      if (!mpuInterrupt && fifoCount < packetSize) return;

      // reset interrupt flag and get INT_STATUS byte
      mpuInterrupt = false;
      mpuIntStatus = mpu.getIntStatus();

      // get current FIFO count
      fifoCount = mpu.getFIFOCount();

      // check for overflow (this should never happen unless our code is too inefficient)
      if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        DEBUG_PRINTLN(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
      } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        //NOTE: some of these can be removed to save memory, processing time
        //      if the measurement isn't needed
        mpu.dmpGetQuaternion(&qat, fifoBuffer);
        mpu.dmpGetEuler(euler, &qat);
        mpu.dmpGetGravity(&gravity, &qat);
        mpu.dmpGetGyro(&gy, fifoBuffer);
        mpu.dmpGetAccel(&aa, fifoBuffer);
        mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
        mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &qat);
        mpu.dmpGetYawPitchRoll(ypr, &qat, &gravity);
      }
    }

    void addToJsonInfo(JsonObject& root)
    {
      int reading = 20;
      //this code adds "u":{"Light":[20," lux"]} to the info object
      JsonObject user = root["u"];
      if (user.isNull()) user = root.createNestedObject("u");

      JsonArray imu_meas = user.createNestedObject("IMU");
      JsonArray quat_json = imu_meas.createNestedArray("Quat");
      quat_json.add(qat.w);
      quat_json.add(qat.x);
      quat_json.add(qat.y);
      quat_json.add(qat.z);
      JsonArray euler_json = imu_meas.createNestedArray("Euler");
      euler_json.add(euler[0]);
      euler_json.add(euler[1]);
      euler_json.add(euler[2]);
      JsonArray accel_json = imu_meas.createNestedArray("Accel");
      accel_json.add(aa.x);
      accel_json.add(aa.y);
      accel_json.add(aa.z);
      JsonArray gyro_json = imu_meas.createNestedArray("Gyro");
      gyro_json.add(gy.x);
      gyro_json.add(gy.y);
      gyro_json.add(gy.z);
      JsonArray world_json = imu_meas.createNestedArray("WorldAccel");
      world_json.add(aaWorld.x);
      world_json.add(aaWorld.y);
      world_json.add(aaWorld.z);
      JsonArray real_json = imu_meas.createNestedArray("RealAccel");
      real_json.add(aaReal.x);
      real_json.add(aaReal.y);
      real_json.add(aaReal.z);
      JsonArray grav_json = imu_meas.createNestedArray("Gravity");
      grav_json.add(gravity.x);
      grav_json.add(gravity.y);
      grav_json.add(gravity.z);
      JsonArray orient_json = imu_meas.createNestedArray("Orientation");
      orient_json.add(ypr[0]);
      orient_json.add(ypr[1]);
      orient_json.add(ypr[2]);
    }

    /*
     * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
     * Values in the state object may be modified by connected clients
     */
    //void addToJsonState(JsonObject& root)
    //{
      //root["user0"] = userVar0;
    //}

    /*
     * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
     * Values in the state object may be modified by connected clients
     */
    //void readFromJsonState(JsonObject& root)
    //{
      //if (root["bri"] == 255) DEBUG_PRINTLN(F("Don't burn down your garage!"));
    //}

    /*
     * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object.
     * It will be called by WLED when settings are actually saved (for example, LED settings are saved)
     * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings!
     */
//    void addToConfig(JsonObject& root)
//    {
//      JsonObject top = root.createNestedObject("MPU6050_IMU");
//      JsonArray pins = top.createNestedArray("pin");
//      pins.add(HW_PIN_SCL);
//      pins.add(HW_PIN_SDA);
//    }

    /*
     * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
     */
    uint16_t getId()
    {
      return USERMOD_ID_IMU;
    }

};


text:
#include "pylothar.h"

/* creation and destruction */

typedef struct
{
  PyObject_HEAD
  lothar_scheduler_t *d_scheduler;
} scheduler_t;

static PyObject *scheduler_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  scheduler_t *self = (scheduler_t *)type->tp_alloc(type, 0);
  self->d_scheduler = NULL;

  return (PyObject *)self;
}

static int scheduler_init(scheduler_t *self, PyObject *args, PyObject *kwds)
{
  self->d_scheduler = lothar_scheduler_create();

  return 0;
}

static void scheduler_dealloc(scheduler_t *self)
{
  if(self->d_scheduler)
    lothar_scheduler_destroy(&self->d_scheduler);

  self->ob_type->tp_free((PyObject *)self);
}

typedef struct
{
  PyObject *scheduler;
  PyObject *callable;
  PyObject *args;
  PyObject *kwds;
} callback_t;

static void function_cb(callback_t *cb)
{
  PyObject *ret = PyObject_Call(cb->callable, cb->args, cb->kwds);

  if(ret)
  {
    Py_DECREF(ret);
  }

  if(PyErr_Occurred()) // explicitely break from the scheduler if an exception was raised
  {
    LOTHAR_DEBUG("exception raised in python code\n");
    lothar_scheduler_stop(((scheduler_t *)cb->scheduler)->d_scheduler);
  }
}

static void cleanup_cb(callback_t *cb)
{
  if(cb->scheduler)
  {
    Py_DECREF(cb->scheduler);
  }
  if(cb->callable)
  {
    Py_DECREF(cb->callable);
  }
  if(cb->args)
  {
    Py_DECREF(cb->args);
  }
  if(cb->kwds)
  {
    Py_DECREF(cb->kwds);
  }
  free(cb);
}

static callback_t *new_cb(PyObject *scheduler, PyObject *callable, PyObject *args, PyObject *kwds)
{
  callback_t *cb;

  if(!PyCallable_Check(callable))
  {
    PyErr_BadArgument();
    return NULL;
  }

  if(args && !PyTuple_Check(args))
  {
    PyErr_BadArgument();
    return NULL;
  }

  if(kwds && !PyDict_Check(kwds))
  {
    PyErr_BadArgument();
    return NULL;
  }

  cb = (callback_t *)lothar_malloc(sizeof(callback_t));
  cb->scheduler = scheduler;
  cb->callable = callable;
  cb->args = args;
  cb->kwds = kwds;

  Py_INCREF(cb->scheduler);
  Py_INCREF(cb->callable);

  if(cb->args)
    Py_INCREF(cb->args);
  else
    cb->args = PyTuple_New(0);

  if(cb->kwds)
    Py_INCREF(cb->kwds);

  return cb;
}

static PyObject *scheduler_add(scheduler_t *self, PyObject *args, PyObject *kwds)
{
  PyObject *function;
  unsigned arrival = 0;
  unsigned estimate = 0;
  unsigned nice = 10;
  PyObject *cb_args = NULL;
  PyObject *cb_kwds = NULL;
  callback_t *cb;

  static char *kwlist[] = {"function", "arrival_time", "estimate", "nice", "function_args", "function_kwds", NULL};

  if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|IIIOO", kwlist, &function, &arrival, &estimate, &nice, &cb_args, &cb_kwds))
    return NULL;

  if(!(cb = new_cb((PyObject *)self, function, cb_args, cb_kwds)))
    return NULL;

  return pylothar_check_return(lothar_scheduler_add(self->d_scheduler, (void (*)(void *))function_cb, (void (*)(void *))cleanup_cb, cb, arrival, estimate, nice));
}

static PyObject *scheduler_add_interval(scheduler_t *self, PyObject *args, PyObject *kwds)
{
  PyObject *function;
  unsigned interval;
  unsigned ntimes = 0;
  unsigned arrival = 0;
  unsigned estimate = 0;
  unsigned nice = 10;
  PyObject *cb_args = NULL;
  PyObject *cb_kwds = NULL;
  callback_t *cb;

  static char *kwlist[] = {"function", "interval", "ntimes", "arrival_time", "estimate", "nice", "function_args", "function_kwds", NULL};

  if(!PyArg_ParseTupleAndKeywords(args, kwds, "OI|IIIIOO", kwlist, &function, &interval, &ntimes, &arrival, &estimate, &nice, &cb_args, &cb_kwds))
    return NULL;

  if(!(cb = new_cb((PyObject *)self, function, cb_args, cb_kwds)))
    return NULL;

  return pylothar_check_return(lothar_scheduler_add_interval(self->d_scheduler, (void (*)(void *))function_cb, (void (*)(void *))cleanup_cb, cb, arrival, estimate, nice, interval, ntimes));
}

static PyObject *scheduler_empty(scheduler_t *self, PyObject *arg)
{
  int status, isempty;
  if((status = lothar_scheduler_empty(self->d_scheduler, &isempty)))
  {
    pylothar_raise_exception(status);
    return NULL;
  }

  return PyBool_FromLong(isempty);
}

static PyObject *scheduler_size(scheduler_t *self, PyObject *arg)
{
  int status;
  size_t size;
  if((status = lothar_scheduler_size(self->d_scheduler, &size)))
  {
    pylothar_raise_exception(status);
    return NULL;
  }

  return PyInt_FromLong(size);
}

static PyObject *scheduler_peek(scheduler_t *self, PyObject *arg)
{
  int status;
  lothar_time_t next;
  if((status = lothar_scheduler_peek(self->d_scheduler, &next)))
  {
    pylothar_raise_exception(status);
    return NULL;
  }

  return PyInt_FromLong((long)next);
}

static PyObject *scheduler_run_single(scheduler_t *self, PyObject *arg)
{
  return pylothar_check_return(lothar_scheduler_run_single(self->d_scheduler));
}

static PyObject *scheduler_run(scheduler_t *self, PyObject *arg)
{
  return pylothar_check_return(lothar_scheduler_run(self->d_scheduler));
}

static PyObject *scheduler_stop(scheduler_t *self, PyObject *arg)
{
  return pylothar_check_return(lothar_scheduler_stop(self->d_scheduler));
}

static PyObject *scheduler_done(scheduler_t *self, PyObject *arg)
{
  int status = lothar_scheduler_done(self->d_scheduler);

  if(status < 0)
  {
    pylothar_raise_exception(-status);
    return NULL;
  }

  return PyBool_FromLong(status);
}

static PyObject *scheduler_next(scheduler_t *self, PyObject *arg)
{
  lothar_time_t n;

  LOTHAR_ERROR(LOTHAR_ERROR_OKAY);
  n = lothar_scheduler_next(self->d_scheduler);

  if(lothar_errno != LOTHAR_ERROR_OKAY)
  {
    pylothar_raise_exception_global();
    return NULL;
  }

  return PyInt_FromLong((long)n);
}

static PyMethodDef scheduler_methods[] =
{
  {"add",          (PyCFunction)scheduler_add,          METH_VARARGS | METH_KEYWORDS, ""},
  {"add_interval", (PyCFunction)scheduler_add_interval, METH_VARARGS | METH_KEYWORDS, ""},
  {"empty",        (PyCFunction)scheduler_empty,        METH_NOARGS,                  ""},
  {"size",         (PyCFunction)scheduler_size,         METH_NOARGS,                  ""},
  {"peek",         (PyCFunction)scheduler_peek,         METH_NOARGS,                  ""},
  {"run",          (PyCFunction)scheduler_run,          METH_NOARGS,                  ""},
  {"run_single",   (PyCFunction)scheduler_run_single,   METH_NOARGS,                  ""},
  {"stop",         (PyCFunction)scheduler_stop,         METH_NOARGS,                  ""},
  {"done",         (PyCFunction)scheduler_done,         METH_NOARGS,                  ""},
  {"next",         (PyCFunction)scheduler_next,         METH_NOARGS,                  ""},

  {NULL, NULL, 0, NULL}
};

PyTypeObject pylothar_scheduler_type =
{
  PyObject_HEAD_INIT(NULL)
  0,                                        // ob_size
  "lothar.scheduler",                      // tp_name
  sizeof(scheduler_t),                     // tp_basicsize
  0,                                        // tp_itemsize
  (destructor)scheduler_dealloc,           // tp_dealloc
  0,                                        // tp_print
  0,                                        // tp_getattr
  0,                                        // tp_setattr
  0,                                        // tp_compare
  0,                                        // tp_repr
  0,                                        // tp_as_number
  0,                                        // tp_as_sequence
  0,                                        // tp_as_mapping
  0,                                        // tp_hash
  0,                                        // tp_call
  0,                                        // tp_str
  0,                                        // tp_getattro
  0,                                        // tp_setattro
  0,                                        // tp_as_buffer
  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
  "scheduler",   // tp_doc
  0,                                        // tp_traverse
  0,                                        // tp_clear
  0,                                        // tp_richcompare
  0,                                        // tp_weaklistoffset
  0,                                        // tp_iter
  0,                                        // tp_iternext
  scheduler_methods,                       // tp_methods
  0,                                        // tp_members
  0,                                        // tp_getseters
  0,                                        // tp_base
  0,                                        // tp_dict
  0,                                        // tp_descr_get
  0,                                        // tp_descr_set
  0,                                        // tp_dictoffset
  (initproc)scheduler_init,                // tp_init
  0,                                        // tp_alloc
  scheduler_new,                           // tp_new
};

PyMODINIT_FUNC pylothar_initscheduler(PyObject *module)
{
  if(PyType_Ready(&pylothar_scheduler_type) < 0)
    return;

  Py_INCREF(&pylothar_scheduler_type);
  PyModule_AddObject(module, "scheduler", (PyObject *)&pylothar_scheduler_type);
}


text:
<?php

namespace Behat\Symfony2Extension\Suite;

use Behat\Testwork\Suite\Exception\SuiteConfigurationException;
use Behat\Testwork\Suite\Generator\SuiteGenerator;
use InvalidArgumentException;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * @author Christophe Coevoet <stof@notk.org>
 */
final class SymfonySuiteGenerator implements SuiteGenerator
{
    private $kernel;
    private $pathSuffix;
    private $contextClassSuffix;

    public function __construct(KernelInterface $kernel, $pathSuffix = 'Features', $contextClassSuffix = 'Features\\Context\\FeatureContext')
    {
        $this->kernel = $kernel;
        $this->pathSuffix = '/' . ltrim($pathSuffix, '/' . DIRECTORY_SEPARATOR);
        $this->contextClassSuffix = '\\' . ltrim($contextClassSuffix, '\\');
    }

    /**
     * Checks if generator support provided suite type and settings.
     *
     * @param string $type
     * @param array  $settings
     *
     * @return Boolean
     */
    public function supportsTypeAndSettings($type, array $settings)
    {
        return 'symfony_bundle' === $type;
    }

    /**
     * {@inheritdoc}
     */
    public function generateSuite($suiteName, array $settings)
    {
        $bundleName = isset($settings['bundle']) ? $settings['bundle'] : $suiteName;

        try {
            $bundle = $this->kernel->getBundle($bundleName);
        } catch (InvalidArgumentException $e) {
            throw new SuiteConfigurationException(
                sprintf('The bundle "%s" does not exist in the project', $bundleName),
                $suiteName,
                $e
            );
        }

        $settings['bundle'] = $bundleName;

        return new SymfonyBundleSuite($suiteName, $bundle, $this->mergeDefaultSettings($bundle, $settings));
    }

    private function mergeDefaultSettings(BundleInterface $bundle, array $settings)
    {
        if (empty($settings['contexts'])) {
            $settings['contexts'] = array($bundle->getNamespace() . $this->contextClassSuffix);
        }

        if (empty($settings['paths'])) {
            $settings['paths'] = array($bundle->getPath() . $this->pathSuffix);
        }

        return $settings;
    }
}


text:
local THNN = require 'nn.THNN'
local SpatialDilatedConvolution, parent = torch.class('nn.SpatialDilatedConvolution', 'nn.SpatialConvolution')

function SpatialDilatedConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH, dilationH, dilationW)
   parent.__init(self, nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH)

   self.dilationH = dilationH or 1
   self.dilationW = dilationW or 1
end

local function makeContiguous(self, input, gradOutput)
   if not input:isContiguous() then
      self._input = self._input or input.new()
      self._input:resizeAs(input):copy(input)
      input = self._input
   end
   if gradOutput then
      if not gradOutput:isContiguous() then
	 self._gradOutput = self._gradOutput or gradOutput.new()
	 self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
	 gradOutput = self._gradOutput
      end
   end
   return input, gradOutput
end

function SpatialDilatedConvolution:updateOutput(input)
   self.finput = self.finput or self.weight.new()
   self.fgradInput = self.fgradInput or self.weight.new()
   input = makeContiguous(self, input)
   input.THNN.SpatialDilatedConvolution_updateOutput(
      input:cdata(),
      self.output:cdata(),
      self.weight:cdata(),
      THNN.optionalTensor(self.bias),
      self.finput:cdata(),
      self.fgradInput:cdata(),
      self.kW, self.kH,
      self.dW, self.dH,
      self.padW, self.padH,
      self.dilationH, self.dilationW
   )
   return self.output
end

function SpatialDilatedConvolution:updateGradInput(input, gradOutput)
   if self.gradInput then
      input, gradOutput = makeContiguous(self, input, gradOutput)
      self.fgradInput = self.fgradInput or self.weight.new()
      input.THNN.SpatialDilatedConvolution_updateGradInput(
         input:cdata(),
         gradOutput:cdata(),
         self.gradInput:cdata(),
         self.weight:cdata(),
         self.finput:cdata(),
         self.kW, self.kH,
         self.dW, self.dH,
         self.padW, self.padH,
         self.dilationH, self.dilationW
      )
      return self.gradInput
   end
end

function SpatialDilatedConvolution:accGradParameters(input, gradOutput, scale)
   scale = scale or 1
   input, gradOutput = makeContiguous(self, input, gradOutput)
   self.fgradInput = self.fgradInput or self.weight.new()
   input.THNN.SpatialDilatedConvolution_accGradParameters(
      input:cdata(),
      gradOutput:cdata(),
      self.gradWeight:cdata(),
      THNN.optionalTensor(self.gradBias),
      self.finput:cdata(),
      self.fgradInput:cdata(),
      self.kW, self.kH,
      self.dW, self.dH,
      self.padW, self.padH,
      self.dilationH, self.dilationW,
      scale
   )
end

function SpatialDilatedConvolution:__tostring__()
   local s = string.format('%s(%d -> %d, %dx%d', torch.type(self),
         self.nInputPlane, self.nOutputPlane, self.kW, self.kH)
   if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then
     s = s .. string.format(', %d,%d', self.dW, self.dH)
   end
   if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then
     s = s .. ', ' .. self.padW .. ',' .. self.padH
   end
   s = s .. ', ' .. self.dilationW .. ',' .. self.dilationH
   if self.bias then
      return s .. ')'
   else
      return s .. ') without bias'
   end
end