text:
const gulp = require('gulp');
const browserify = require('browserify');
const sourcemaps = require('gulp-sourcemaps');
const imagemin = require('gulp-imagemin');
const sequence = require('gulp-sequence').use(gulp);
const del = require('del');
const browserSync = require('browser-sync');
const uglifyjs = require('uglify-es');
const buffer = require('vinyl-buffer');
const source = require('vinyl-source-stream');
const pump = require('pump');
const sass = require('gulp-sass');
const fs = require('fs');
const composer = require('gulp-uglify/composer');
const glob = require('glob-promise');
const path = require('path');
const cleanCSS = require('gulp-clean-css');
const stringify = require('stringify');

const minify = composer(uglifyjs, console);

gulp.task('clean', () => {
  return del('./dist');
});

gulp.task('html', () => {
  return pump([gulp.src('./src/*.html'), gulp.dest('./dist/')]);
});

let vendors = [];

// Bundle all the vendor libraries into a vendor.js file.
gulp.task('scripts:vendor', () => {
  vendors = Object.keys(JSON.parse(fs.readFileSync('package.json')).dependencies);
  const b = browserify({ debug: true });
  vendors.forEach(lib => b.require(lib));
  return pump([
    b.bundle(),
    source('vendor.js'),
    buffer(),
    sourcemaps.init({ loadMaps: true }),
    minify({}),
    sourcemaps.write('.'),
    gulp.dest('./dist/scripts/'),
  ]);
});

// Build tasks for each script entry point, and then tasks which run all of those.
(function buildScriptTasks() {
  const entries = glob.sync('./src/apps/**.js');
  const entryNames = entries.map(entry => path.parse(entry).name);
  const devTaskNames = entryNames.map(name => `scripts:apps:${name}:dev`);
  const releaseTaskNames = entryNames.map(name => `scripts:apps:${name}:release`);

  entries.forEach((entry, i) => {
    // Browserify the entry point, with source maps.
    gulp.task(devTaskNames[i], () => {
      return pump([
        browserify({
          entries: [entry],
          debug: true,
        })
          .transform(stringify)
          .external(vendors)
          .bundle(),
        source(path.parse(entry).base),
        buffer(),
        sourcemaps.init({ loadMaps: true }),
        sourcemaps.write('.'),
        gulp.dest('./dist/scripts/'),
      ]);
    });

    // Release is the same as dev, except for the minify() bit.
    gulp.task(releaseTaskNames[i], () => {
      return pump([
        browserify({
          entries: [entry],
          debug: true,
        })
          .transform(stringify)
          .external(vendors)
          .bundle(),
        source(path.parse(entry).base),
        buffer(),
        sourcemaps.init({ loadMaps: true }),
        minify({}),
        sourcemaps.write('.'),
        gulp.dest('./dist/scripts/'),
      ]);
    });
  });

  // Run all the entry point tasks.
  gulp.task('scripts:apps:dev', devTaskNames);
  gulp.task('scripts:apps:release', releaseTaskNames);
}());

// Compile Stylus files.
gulp.task('sass', () => {
  return pump([
    gulp.src('./src/sass/**/*.scss'),
    sourcemaps.init(),
    sass({ outputStyle: 'compressed' }),
    sourcemaps.write('.'),
    gulp.dest('./dist/styles/'),
  ]);
});

// Orinary CSS files, like the leaflet one.
gulp.task('css', () => {
  return pump([
    gulp.src(['./src/css/**/*.css', './node_modules/leaflet/dist/leaflet.css']),
    sourcemaps.init(),
    cleanCSS(),
    sourcemaps.write('.'),
    gulp.dest('./dist/styles/'),
  ]);
});

// Copy/compress images.
gulp.task('images', () => {
  return pump([
    gulp.src(['./src/images/**/*', './node_modules/leaflet/dist/images/*']),
    imagemin({ progressive: true }),
    gulp.dest('./dist/images/'),
  ]);
});

// Maps are special SVG fiels, we don't want to treat them as images, because imagemin takes out stuff we need.
gulp.task('maps', () => {
  return pump([gulp.src('./src/maps/**/*'), gulp.dest('./dist/maps')]);
});

gulp.task('default', ['build:release']);

gulp.task(
  'build:release',
  sequence('clean', 'scripts:vendor', [
    'html',
    'maps',
    'scripts:apps:release',
    'sass',
    'css',
    'images',
  ]));

gulp.task(
  'build:dev',
  sequence('clean', 'scripts:vendor', [
    'html',
    'maps',
    'scripts:apps:dev',
    'sass',
    'css',
    'images',
  ]));

// Watch/sync drama below.

// Set up Browser Sync. Don't do ghost mode, it is crazy.
gulp.task('browser-sync', () => {
  browserSync.init({
    proxy: 'localhost:8080',
    open: false,
    ghostMode: false,
  });
});

// Define tasks which do the reload after a task. It adds ':watch' to the task name.
// Per: https://browsersync.io/docs/gulp#gulp-reload
// Revise when Gulp 4 happens? https://github.com/gulpjs/gulp/blob/4.0/docs/recipes/minimal-browsersync-setup-with-gulp4.md
function watchTask(...names) {
  names.forEach((name) => {
    gulp.task(`${name}:watch`, [name], (done) => {
      browserSync.reload();
      done();
    });
  });
}

watchTask('html', 'scripts:vendor', 'scripts:apps:dev', 'sass', 'css', 'maps', 'images');

gulp.task('dev', ['build:dev', 'browser-sync'], () => {
  gulp.watch('./src/**/*.html', ['html:watch']);
  gulp.watch('./src/**/*.js', ['scripts:apps:dev:watch']);
  gulp.watch('./src/**/*.scss', ['sass:watch']);
  gulp.watch('./src/**/*.css', ['css:watch']);
  gulp.watch('./src/images/**/*', ['images:watch']);
  gulp.watch('./src/maps/**/*', ['maps:watch']);
  gulp.watch('./package.json', ['scripts:vendor:watch', 'scripts:apps:dev:watch']);
});


text:
require 'time'

module MKV
  class Movie
    @@timeout = 200

    attr_reader :path
    attr_reader :tracks

    def initialize(path)
      raise Errno::ENOENT, "the file '#{path}' does not exist" unless File.exists?(path)

      @path = path

      # mkvinfo will output to stdout
      command = "#{MKV.mkvinfo_binary} #{Shellwords.escape(path)}"
      MKV.logger.info(command)
      output = Open3.popen3(command) { |stdin, stdout, stderr| stdout.read}

      match = output.gsub(/\n/, '$$').match /\|\+\ssegment tracks(.*?)\|\+\s(?:chapters|cluster)/i
      tracks = match[1].gsub(/\$\$/, "\n")
      match_tracks = tracks.gsub(/\n/, '$$').scan(/a track(.*?)(?:\|\s\+|$)/i)
      match_tracks = match_tracks.map { |x| x.first.gsub(/\$\$/, "\n") }

      @tracks = match_tracks.map do |track_data|
        MKV::Track.new track_data
      end

      @invalid = true unless @tracks.any?
      @invalid = true if output.include?("is not supported")
      @invalid = true if output.include?("could not find codec parameters")
    end

    def valid?
      not @invalid
    end

    def has_video? ; tracks.select { |t| t.type == 'video' }.any? ; end
    def has_audio? ; tracks.select { |t| t.type == 'audio' }.any? ; end

    def has_subtitles?(language = nil)
      language = [language].flatten if language
      tracks.any? { |t| t.type == 'subtitles' && (language.nil? || language.empty? || language.include?(t.language)) }
    end

    def extract_subtitles(options={})
      # Compatibility with legacy method accepting a String for destination_dir (deprecated)
      if options.class == String
        options = { :destination_dir => options }
      end

      options[:language] ||= []
      options[:language] = [options[:language]].flatten.map(&:to_sym) if options[:language]
      options[:language] << :und if options[:language].any?

      track_filter = lambda { |t| t.type == 'subtitles' && (options[:language].include?(t.language.to_sym) || options[:language].empty?) }

      tracks.select(&track_filter).each do |track|
        destination_fileextension = (options[:language].count == 1 ? "" : ".#{track.mkv_info_id}.#{track.language}") + ".srt"
        destination_filename = File.basename(@path).gsub(/\.mkv$/i, destination_fileextension)
        destination_dir = options[:destination_dir] || File.dirname(@path)

        command = %Q[#{MKV.mkvextract_binary} tracks "#{@path}" #{track.mkv_info_id}:"#{File.join(destination_dir, destination_filename)}"]
        MKV.logger.info(command)

        output = ""
        start_time = Time.now.to_i
        Open3.popen3(command) do |stdin, stdout, stderr, wait_thr|
          begin
            yield(0.0, 0, destination_filename) if block_given?
            next_line = Proc.new do |line|
              output << line
              if line =~ /(\d+)%/
                progress = $1.to_i

                yield(progress, Time.now.to_i - start_time, destination_filename) if block_given?
              end

              if line =~ /Unsupported codec/
                MKV.logger.error "Failed encoding...\nCommand\n#{command}\nOutput\n#{output}\n"
                raise "Failed encoding: #{line}"
              end
            end

            if @@timeout
              stdout.each_with_timeout(wait_thr.pid, @@timeout, "r", &next_line)
            else
              stdout.each("r", &next_line)
            end

          rescue Timeout::Error => e
            MKV.logger.error "Process hung...\nCommand\n#{command}\nOutput\n#{output}\n"
            raise MKV::Error, "Process hung. Full output: #{output}"
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
"""Send the results of a query to the configured music player as a playlist.
"""
from __future__ import division, absolute_import, print_function

from beets.plugins import BeetsPlugin
from beets.ui import Subcommand
from beets import config
from beets import ui
from beets import util
from os.path import relpath
from tempfile import NamedTemporaryFile

# Indicate where arguments should be inserted into the command string.
# If this is missing, they're placed at the end.
ARGS_MARKER = '$args'

class PlayPlugin(BeetsPlugin):

    def __init__(self):
        super(PlayPlugin, self).__init__()

        config['play'].add({
            'command': None,
            'use_folders': False,
            'relative_to': None,
            'raw': False,
            # Backwards compatibility. See #1803 and line 74
            'warning_threshold': -2,
            'warning_treshold': 100,
        })

    def commands(self):
        play_command = Subcommand(
            'play',
            help=u'send music to a player as a playlist'
        )
        play_command.parser.add_album_option()
        play_command.parser.add_option(
            u'-A', u'--args',
            action='store',
            help=u'add additional arguments to the command',
        )
        play_command.func = self.play_music
        return [play_command]

    def play_music(self, lib, opts, args):
        """Execute query, create temporary playlist and execute player
        command passing that playlist, at request insert optional arguments.
        """
        command_str = config['play']['command'].get()
        if not command_str:
            command_str = util.open_anything()
        use_folders = config['play']['use_folders'].get(bool)
        relative_to = config['play']['relative_to'].get()
        raw = config['play']['raw'].get(bool)
        warning_threshold = config['play']['warning_threshold'].get(int)
        # We use -2 as a default value for warning_threshold to detect if it is
        # set or not. We can't use a falsey value because it would have an
        # actual meaning in the configuration of this plugin, and we do not use
        # -1 because some people might use it as a value to obtain no warning,
        # which wouldn't be that bad of a practice.
        if warning_threshold == -2:
            # if warning_threshold has not been set by user, look for
            # warning_treshold, to preserve backwards compatibility. See #1803.
            # warning_treshold has the correct default value of 100.
            warning_threshold = config['play']['warning_treshold'].get(int)

        if relative_to:
            relative_to = util.normpath(relative_to)

        # Add optional arguments to the player command.
        if opts.args:
            if ARGS_MARKER in command_str:
                command_str = command_str.replace(ARGS_MARKER, opts.args)
            else:
                command_str = u"{} {}".format(command_str, opts.args)
        else:
            # Don't include the marker in the command.
            command_str = command_str.replace(" " + ARGS_MARKER, "")

        # Perform search by album and add folders rather than tracks to
        # playlist.
        if opts.album:
            selection = lib.albums(ui.decargs(args))
            paths = []

            sort = lib.get_default_album_sort()
            for album in selection:
                if use_folders:
                    paths.append(album.item_dir())
                else:
                    paths.extend(item.path
                                 for item in sort.sort(album.items()))
            item_type = 'album'

        # Perform item query and add tracks to playlist.
        else:
            selection = lib.items(ui.decargs(args))
            paths = [item.path for item in selection]
            if relative_to:
                paths = [relpath(path, relative_to) for path in paths]
            item_type = 'track'

        item_type += 's' if len(selection) > 1 else ''

        if not selection:
            ui.print_(ui.colorize('text_warning',
                                  u'No {0} to play.'.format(item_type)))
            return

        # Warn user before playing any huge playlists.
        if warning_threshold and len(selection) > warning_threshold:
            ui.print_(ui.colorize(
                'text_warning',
                u'You are about to queue {0} {1}.'.format(
                    len(selection), item_type)))

            if ui.input_options((u'Continue', u'Abort')) == 'a':
                return

        ui.print_(u'Playing {0} {1}.'.format(len(selection), item_type))
        if raw:
            open_args = paths
        else:
            open_args = [self._create_tmp_playlist(paths)]

        self._log.debug(u'executing command: {} {!r}', command_str, open_args)
        try:
            util.interactive_open(open_args, command_str)
        except OSError as exc:
            raise ui.UserError(
                "Could not play the query: {0}".format(exc))

    def _create_tmp_playlist(self, paths_list):
        """Create a temporary .m3u file. Return the filename.
        """
        m3u = NamedTemporaryFile('wb', suffix='.m3u', delete=False)
        for item in paths_list:
            m3u.write(item + b'\n')
        m3u.close()
        return m3u.name


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="VSMOffline">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>de.dimm.vsm.records.DeltaNode</class>
    <class>de.dimm.vsm.records.FileSystemElemNode</class>
    <class>de.dimm.vsm.records.FileSystemElemAttributes</class>
    <class>de.dimm.vsm.records.PoolNodeFileLink</class>
    <class>de.dimm.vsm.records.StoragePool</class>
    <class>de.dimm.vsm.records.AbstractStorageNode</class>
    <class>de.dimm.vsm.records.ClientInfo</class>
    <class>de.dimm.vsm.records.ClientVolume</class>
    <class>de.dimm.vsm.records.Job</class>
    <class>de.dimm.vsm.records.Schedule</class>
    <class>de.dimm.vsm.records.DedupHashBlock</class>
    <class>de.dimm.vsm.records.HashBlock</class>
    <class>de.dimm.vsm.records.Excludes</class>
    <class>de.dimm.vsm.records.XANode</class>
    <class>de.dimm.vsm.records.HotFolder</class>
    <properties>
      <property name="eclipselink.logging.level" value="ALL"/>
      <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.PostgreSQLPlatform"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/VSMParamDB"/>
      <property name="javax.persistence.jdbc.password" value="12345"/>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.user" value="mw"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
  <persistence-unit name="VSM">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>de.dimm.vsm.records.ArchiveJob</class>
    <class>de.dimm.vsm.records.ArchiveJobFileLink</class>
    <class>de.dimm.vsm.records.DeltaNode</class>
    <class>de.dimm.vsm.records.FileSystemElemNode</class>
    <class>de.dimm.vsm.records.FileSystemElemAttributes</class>
    <class>de.dimm.vsm.records.PoolNodeFileLink</class>
    <class>de.dimm.vsm.records.StoragePool</class>
    <class>de.dimm.vsm.records.AbstractStorageNode</class>
    <class>de.dimm.vsm.records.ClientInfo</class>
    <class>de.dimm.vsm.records.ClientVolume</class>
    <class>de.dimm.vsm.records.Job</class>
    <class>de.dimm.vsm.records.Schedule</class>
    <class>de.dimm.vsm.records.DedupHashBlock</class>
    <class>de.dimm.vsm.records.HashBlock</class>
    <class>de.dimm.vsm.records.Excludes</class>
    <class>de.dimm.vsm.records.XANode</class>
    <class>de.dimm.vsm.records.Retention</class>
    <class>de.dimm.vsm.records.RetentionJob</class>
    <class>de.dimm.vsm.records.RetentionWindow</class>
    <class>de.dimm.vsm.records.Snapshot</class>
    <class>de.dimm.vsm.records.BackupJobResult</class>
    <class>de.dimm.vsm.records.BackupVolumeResult</class>
    <class>de.dimm.vsm.records.MountEntry</class>
    <properties>
      <!-- <property name="eclipselink.logging.level" value="ALL"/> -->
      <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.DerbyPlatform"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:db/VSMParams;create=true"/>
      <property name="javax.persistence.jdbc.password" value="12345"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="javax.persistence.jdbc.user" value="mw"/>
      <property name="vsm.persistence.jdbc.pooldatasource" value="org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
  <persistence-unit name="VSMBase">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>de.dimm.vsm.records.StoragePoolNub</class>
    <class>de.dimm.vsm.records.HotFolder</class>
    <class>de.dimm.vsm.records.HotFolderError</class>
    <class>de.dimm.vsm.records.Role</class>
    <class>de.dimm.vsm.records.RoleOption</class>
    <class>de.dimm.vsm.records.AccountConnector</class>
    <class>de.dimm.vsm.records.MailNotifications</class>
    <class>de.dimm.vsm.records.MailGroup</class>
    <class>de.dimm.vsm.records.SmtpLoginData</class>
    <properties>
      <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.DerbyPlatform"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:db/VSMBase;create=true"/>
      <property name="javax.persistence.jdbc.password" value="12345"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="javax.persistence.jdbc.user" value="mw"/>
      <property name="vsm.persistence.jdbc.pooldatasource" value="org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
  <persistence-unit name="VSMLog">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>de.dimm.vsm.records.MessageLog</class>
    <properties>
      <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.DerbyPlatform"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:db/VSMLog;create=true"/>
      <property name="javax.persistence.jdbc.password" value="12345"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="javax.persistence.jdbc.user" value="mw"/>
      <property name="vsm.persistence.jdbc.pooldatasource" value="org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
  <persistence-unit name="VSMText">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>de.dimm.vsm.records.TextBase</class>
    <properties>
      <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.DerbyPlatform"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:db/VSMText;create=true"/>
      <property name="javax.persistence.jdbc.password" value="12345"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="javax.persistence.jdbc.user" value="mw"/>
      <property name="vsm.persistence.jdbc.pooldatasource" value="org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>


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

namespace UITests
{
    public class TestGroupAttribute : Attribute
    {
        public TestGroupAttribute()
        {
        }

        public TestGroupAttribute(string name)
        {
            Name = name;
        }

        public TestGroupAttribute(string name, bool exclusive)
            : this(name)
        {
            Exclusive = exclusive;
        }

        public string Name { get; set; }

        public bool Exclusive { get; set; }
    }
}


text:
package firmament

import (
	"fmt"

	"github.com/golang/glog"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
)

func Schedule(client FirmamentSchedulerClient) *SchedulingDeltas {
	scheduleResp, err := client.Schedule(context.Background(), &ScheduleRequest{})
	if err != nil {
		grpclog.Fatalf("%v.Schedule(_) = _, %v: ", client, err)
	}
	return scheduleResp
}

func TaskCompleted(client FirmamentSchedulerClient, tuid *TaskUID) {
	tCompletedResp, err := client.TaskCompleted(context.Background(), tuid)
	if err != nil {
		grpclog.Fatalf("%v.TaskCompleted(_) = _, %v: ", client, err)
	}
	switch tCompletedResp.Type {
	case TaskReplyType_TASK_NOT_FOUND:
		glog.Fatalf("Task %d not found", tuid.TaskUid)
	case TaskReplyType_TASK_JOB_NOT_FOUND:
		glog.Fatalf("Task's %d job not found", tuid.TaskUid)
	case TaskReplyType_TASK_COMPLETED_OK:
	default:
		panic(fmt.Sprintf("Unexpected TaskCompleted response %v for task %v", tCompletedResp, tuid.TaskUid))
	}
}

func TaskFailed(client FirmamentSchedulerClient, tuid *TaskUID) {
	tFailedResp, err := client.TaskFailed(context.Background(), tuid)
	if err != nil {
		grpclog.Fatalf("%v.TaskFailed(_) = _, %v: ", client, err)
	}
	switch tFailedResp.Type {
	case TaskReplyType_TASK_NOT_FOUND:
		glog.Fatalf("Task %d not found", tuid.TaskUid)
	case TaskReplyType_TASK_JOB_NOT_FOUND:
		glog.Fatalf("Task's %d job not found", tuid.TaskUid)
	case TaskReplyType_TASK_FAILED_OK:
	default:
		panic(fmt.Sprintf("Unexpected TaskFailed response %v for task %v", tFailedResp, tuid.TaskUid))
	}
}

func TaskRemoved(client FirmamentSchedulerClient, tuid *TaskUID) {
	tRemovedResp, err := client.TaskRemoved(context.Background(), tuid)
	if err != nil {
		grpclog.Fatalf("%v.TaskRemoved(_) = _, %v: ", client, err)
	}
	switch tRemovedResp.Type {
	case TaskReplyType_TASK_NOT_FOUND:
		glog.Fatalf("Task %d not found", tuid.TaskUid)
	case TaskReplyType_TASK_JOB_NOT_FOUND:
		glog.Fatalf("Task's %d job not found", tuid.TaskUid)
	case TaskReplyType_TASK_REMOVED_OK:
	default:
		panic(fmt.Sprintf("Unexpected TaskRemoved response %v for task %v", tRemovedResp, tuid.TaskUid))
	}
}

func TaskSubmitted(client FirmamentSchedulerClient, td *TaskDescription) {
	tSubmittedResp, err := client.TaskSubmitted(context.Background(), td)
	if err != nil {
		grpclog.Fatalf("%v.TaskSubmitted(_) = _, %v: ", client, err)
	}
	switch tSubmittedResp.Type {
	case TaskReplyType_TASK_ALREADY_SUBMITTED:
		glog.Fatalf("Task (%s,%d) already submitted", td.JobDescriptor.Uuid, td.TaskDescriptor.Uid)
	case TaskReplyType_TASK_STATE_NOT_CREATED:
		glog.Fatalf("Task (%s,%d) not in created state", td.JobDescriptor.Uuid, td.TaskDescriptor.Uid)
	case TaskReplyType_TASK_SUBMITTED_OK:
	default:
		panic(fmt.Sprintf("Unexpected TaskSubmitted response %v for task (%v,%v)", tSubmittedResp, td.JobDescriptor.Uuid, td.TaskDescriptor.Uid))
	}
}

func NodeAdded(client FirmamentSchedulerClient, rtnd *ResourceTopologyNodeDescriptor) {
	nAddedResp, err := client.NodeAdded(context.Background(), rtnd)
	if err != nil {
		grpclog.Fatalf("%v.NodeAdded(_) = _, %v: ", client, err)
	}
	switch nAddedResp.Type {
	case NodeReplyType_NODE_ALREADY_EXISTS:
		glog.Fatalf("Tried to add existing node %s", rtnd.ResourceDesc.Uuid)
	case NodeReplyType_NODE_ADDED_OK:
	default:
		panic(fmt.Sprintf("Unexpected NodeAdded response %v for node %v", nAddedResp, rtnd.ResourceDesc.Uuid))
	}
}

func NodeFailed(client FirmamentSchedulerClient, ruid *ResourceUID) {
	nFailedResp, err := client.NodeFailed(context.Background(), ruid)
	if err != nil {
		grpclog.Fatalf("%v.NodeFailed(_) = _, %v: ", client, err)
	}
	switch nFailedResp.Type {
	case NodeReplyType_NODE_NOT_FOUND:
		glog.Fatalf("Tried to fail non-existing node %s", ruid.ResourceUid)
	case NodeReplyType_NODE_FAILED_OK:
	default:
		panic(fmt.Sprintf("Unexpected NodeFailed response %v for node %v", nFailedResp, ruid.ResourceUid))
	}
}

func NodeRemoved(client FirmamentSchedulerClient, ruid *ResourceUID) {
	nRemovedResp, err := client.NodeRemoved(context.Background(), ruid)
	if err != nil {
		grpclog.Fatalf("%v.NodeRemoved(_) = _, %v: ", client, err)
	}
	switch nRemovedResp.Type {
	case NodeReplyType_NODE_NOT_FOUND:
		glog.Fatalf("Tried to remove non-existing node %s", ruid.ResourceUid)
	case NodeReplyType_NODE_REMOVED_OK:
	default:
		panic(fmt.Sprintf("Unexpected NodeRemoved response %v for node %v", nRemovedResp, ruid.ResourceUid))
	}
}

func AddTaskStats(client FirmamentSchedulerClient, ts *TaskStats) {
	_, err := client.AddTaskStats(context.Background(), ts)
	if err != nil {
		grpclog.Fatalf("%v.AddTaskStats(_) = _, %v: ", client, err)
	}
}

func AddNodeStats(client FirmamentSchedulerClient, rs *ResourceStats) {
	_, err := client.AddNodeStats(context.Background(), rs)
	if err != nil {
		grpclog.Fatalf("%v.AddNodeStats(_) = _, %v: ", client, err)
	}
}

func New(address string) (FirmamentSchedulerClient, *grpc.ClientConn, error) {
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithInsecure())
	conn, err := grpc.Dial(address, opts...)
	if err != nil {
		glog.Errorf("Did not connect to Firmament scheduler: %v", err)
		return nil, nil, err
	}
	fc := NewFirmamentSchedulerClient(conn)
	return fc, conn, nil
}


text:
#pragma once

#include <stdbool.h>
#include <stdint.h>

#include "AppEvent.h"
#include "ContactSensorManager.h"
#include "K32W0FactoryDataProvider.h"

#include <app/clusters/identify-server/identify-server.h>
#include <platform/CHIPDeviceLayer.h>

#include "FreeRTOS.h"
#include "timers.h"

// Application-defined error codes in the CHIP_ERROR space.
#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01)
#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02)
#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03)
#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04)
#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05)
#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06)

class AppTask
{
public:
    CHIP_ERROR StartAppTask();
    static void AppTaskMain(void * pvParameter);

    void PostContactActionRequest(ContactSensorManager::Action aAction);
    void PostEvent(const AppEvent * event);

    void UpdateClusterState(void);
    void UpdateDeviceState(void);

    bool IsSyncClusterToButtonAction();
    void SetSyncClusterToButtonAction(bool value);
    // Identify cluster callbacks.
    static void OnIdentifyStart(Identify * identify);
    static void OnIdentifyStop(Identify * identify);

private:
    friend AppTask & GetAppTask(void);

    CHIP_ERROR Init();

    static void OnStateChanged(ContactSensorManager::State aState);

    void CancelTimer(void);

    void DispatchEvent(AppEvent * event);

    static void FunctionTimerEventHandler(void * aGenericEvent);
    static void KBD_Callback(uint8_t events);
    static void HandleKeyboard(void);
    static void OTAHandler(void * aGenericEvent);
    static void BleHandler(void * aGenericEvent);
    static void BleStartAdvertising(intptr_t arg);
    static void ContactActionEventHandler(void * aGenericEvent);
    static void OTAResumeEventHandler(void * aGenericEvent);
    static void ResetActionEventHandler(void * aGenericEvent);
    static void InstallEventHandler(void * aGenericEvent);

    static void ButtonEventHandler(uint8_t pin_no, uint8_t button_action);
    static void TimerEventHandler(TimerHandle_t xTimer);

    static void MatterEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg);
    void StartTimer(uint32_t aTimeoutInMs);

#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR
    static void InitOTA(intptr_t arg);
    static void StartOTAQuery(intptr_t arg);
    static void PostOTAResume();
    static void OnScheduleInitOTA(chip::System::Layer * systemLayer, void * appState);
#endif

    static void UpdateClusterStateInternal(intptr_t arg);
    static void UpdateDeviceStateInternal(intptr_t arg);
    static void InitServer(intptr_t arg);

    enum class Function : uint8_t
    {
        kNoneSelected   = 0,
        kSoftwareUpdate = 0,
        kFactoryReset,
        kContact,
        kIdentify,
        kInvalid
    };

    Function mFunction              = Function::kNoneSelected;
    bool mResetTimerActive          = false;
    bool mSyncClusterToButtonAction = false;

    static AppTask sAppTask;

    chip::DeviceLayer::K32W0FactoryDataProvider mK32W0FactoryDataProvider;
};

inline AppTask & GetAppTask(void)
{
    return AppTask::sAppTask;
}

inline bool AppTask::IsSyncClusterToButtonAction()
{
    return mSyncClusterToButtonAction;
}

inline void AppTask::SetSyncClusterToButtonAction(bool value)
{
    mSyncClusterToButtonAction = value;
}


text:
layout: post
title: Kubespray
tags: kubernetes kubespray deploy
---

### Tips for kubespray deployment (7 nodes)

0. On all nodes
``apt install python-minimal
echo '127.0.0.1 hostname' >> /etc/hosts``
1. On kubespray machine
``apt-get update
apt-get install software-properties-common
apt-add-repository ppa:ansible/ansible
apt-get update
apt-get install ansible
apt install  python-netaddr
git clone https://github.com/kubernetes-incubator/kubespray.git ``
2. ``cd kubespray; cp -rfp inventory/sample inventory/mycluster``
3. ``declare -a IPS=(IP1_master IP2_master2 IP3_compute1 IP4_compute2 IP5_etcd1 IP6_etcd2 IP7_etcd3)``
4. CONFIG_FILE=inventory/mycluster/hosts.ini python3 contrib/inventory_builder/inventory.py ${IPS[@]}
5. Reconfigure inventory/mycluster/hosts.ini file if needed
6. configure inventory/mycluster/group_vars/* if needed
[all.yaml]({{ "/listings/2018-03-22-kubespray/all.yaml" }})
[k8s-cluster.yaml]({{ "/listings/2018-03-22-kubespray/k8s-cluster.yaml" }})
Also, I recommend before deployment to look on these vars:
cat inventory/mycluster/group_vars/k8s-cluster.yml
    docker_dns_servers_strict: false
cat roles/kubernetes/node/defaults/main.yml
    kube_cadvisor_port: 4194
    kubelet_bind_address: 0.0.0.0
If you are planning to use Calioco on virtual environment with host mtu < 1500 do not forget to correct this one too:
cat roles/network_plugin/calico/defaults/main.yml
   calico_mtu: 1400
7. ``ansible-playbook -i inventory/mycluster/hosts.ini cluster.yml``
8. If you are experiencing timeouts, you should check that in /etc/hosts on every host exists correct localhost line. It happens cause sudo cant resolve localhost.
``for i in IP1 IP2 IP3 IP4 IP5 IP6 IP7; do ssh -x $i 'echo 127.0.0.1 hostname >> /etc/hosts'``
9. If you are planning to use nfs pv, then you should to install nfs-common package on all computes/masters
``for i in IP1 IP2 IP3 IP4; do ssh -x $i 'apt update; apt -y install nfs-common'``
10. After deploy you can find your credentials in inventory/mycluster/credentials/kube_user, and kube/config on all masters
11. If you want to change stuff in kubelets after deploying, go to /etc/kubernetes/kubelet.env and restart kubelet service
If you want to use prometheus / grafana do stuff that mentioned in Cheats


text:
<?php

use yii\helpers\Html;
use kartik\detail\DetailView;
use yii\helpers\Url;
use yii\helpers\ArrayHelper;
use kartik\markdown\Markdown;
use kartik\markdown\MarkdownEditor;
use kartik\widgets\FileInput;
use kartik\grid\GridView;
use yii\widgets\Pjax;

use common\models\PropComp;

/* @var $this yii\web\View */
/* @var $model common\models\Company */

$this->title = $model->title;
$this->params['breadcrumbs'][] = ['label' => 'Companys', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

$attributes = [
    [
        'group'=>true,
        'label'=>'Company Info',
        'rowOptions'=>['class'=>'info'],
    ],
    [
        'attribute'=>'id',
        'label'=>'Company #',
        'displayOnly'=>true,
    ],
    [
        'attribute'=>'title',
        'value'=>$model->title
    ],
    [
        'attribute'=>'website_url',
        'value'=>$model->website_url
    ],
    [
        'attribute'=>'bonus_as_value',
        'value'=>$model->bonus_as_value
    ],
    [
        'attribute'=>'bonus_offer',
        'value'=>$model->bonus_offer
    ],
    [
        'label' => 'Bonus Offer Small',
        'attribute'=>'bonus_offer_desc',
        'value'=>$model->bonus_offer_desc
    ],
    [
        'attribute'=>'short_description',
        'value'=>$model->short_description
    ],
    [
        'attribute'=>'description',
        'format'=>'raw',
        'value'=>Markdown::convert($model->description),
        'type'=>DetailView::INPUT_WIDGET,
        'widgetOptions'=>[
            'class' => MarkdownEditor::classname()
        ]
    ],
    [
        'attribute'=>'telephone',
        'value'=>$model->telephone
    ],
    [
        'attribute'=>'established',
        'value'=>$model->established
    ],
    [
        'attribute'=>'regulation',
        'value'=>$model->regulation
    ],
    [
        'attribute'=>'max_leverage',
        'value'=>$model->max_leverage
    ],
    [
        'attribute'=>'min_deposit',
        'value'=>$model->min_deposit
    ],
    [
        'attribute'=>'spreads_from',
        'value'=>$model->spreads_from
    ],
    [
        'attribute'=>'pairs_offered',
        'value'=>$model->pairs_offered
    ],
    [
        'attribute'=>'extra_secure',
        'label' => 'Extra Secure Black',
        'format'=>'raw',
        'value'=>$model->extra_secure ? 'Yes' : 'No',
        'type'=>DetailView::INPUT_SWITCH,
        'widgetOptions' => [
            'pluginOptions' => [
                'onText' => 'Yes',
                'offText' => 'No',
            ]
        ],
    ],
    [
        'attribute'=>'user_favorite',
        'label' => 'Extra Secure Blue',
        'format'=>'raw',
        'value'=>$model->user_favorite ? 'Yes' : 'No',
        'type'=>DetailView::INPUT_SWITCH,
        'widgetOptions' => [
            'pluginOptions' => [
                'onText' => 'Yes',
                'offText' => 'No',
            ]
        ],
    ],
    [
        'attribute'=>'status',
        'format'=>'raw',
        'value'=>$model->status ? 'Yes' : 'No',
        'type'=>DetailView::INPUT_SWITCH,
        'widgetOptions' => [
            'pluginOptions' => [
                'onText' => 'Yes',
                'offText' => 'No',
            ]
        ],
    ],
    [
        'attribute'=>'us_allowed',
        'format'=>'raw',
        'value'=>$model->us_allowed ? 'Yes' : 'No',
        'type'=>DetailView::INPUT_SWITCH,
        'widgetOptions' => [
            'pluginOptions' => [
                'onText' => 'Yes',
                'offText' => 'No',
            ]
        ],
    ],
    [
        'group'=>true,
        'label'=>'Editor\'s Review',
        'rowOptions'=>['class'=>'info'],
    ],
    [
        'attribute'=>'rating',
        'value'=>$model->rating
    ],
    [
        'attribute'=>'review',
        'format'=>'raw',
        'value'=>Markdown::convert($model->review),
        'type'=>DetailView::INPUT_WIDGET,
        'widgetOptions'=>[
            'class' => MarkdownEditor::classname()
        ]
    ],
    [
        'group'=>true,
        'label'=>'Table Information',
        'rowOptions'=>['class'=>'info']
    ],
    [
        'attribute'=>'button_text',
        'value'=>$model->button_text
    ],
    [
        'attribute'=>'link_text',
        'value'=>$model->link_text
    ],
    [
        'attribute'=>'bonus_link_heading',
        'value'=>$model->bonus_link_heading,
        'label' => 'Bonus Link Heading( #bonus# indicates bonus offer)',
    ],
    [
        'group'=>true,
        'label'=>'Table Information',
        'rowOptions'=>['class'=>'info']
    ],
    [
        'attribute'=>'slider_text',
        'value'=>$model->slider_text,
        'type'=>DetailView::INPUT_TEXTAREA
    ],
    [
        'group'=>true,
        'label'=>'SEO Information',
        'rowOptions'=>['class'=>'info']
    ],
    [
        'attribute'=>'slug',
        'value'=>$model->slug
    ],
    [
        'attribute'=>'meta_keywords',
        'value'=>$model->meta_keywords
    ],
    [
        'attribute'=>'meta_description',
        'value'=>$model->meta_description
    ]
];

//images
$allImages = [];
$allImageConfig = [];

if ($model->image_url) {
    $allImages[] = 'image_url, array("width" => 250, "height" => 190, "crop" => "fill")) .'" class="file-preview-image">';

    $allImageConfig[] =[
            'caption' => 'Current Image',
            'frameAttr'=> [
                'style' => 'height:150px; width:100px;',
            ],
            'url' => Url::toRoute(['detach', 'id'=>$model->id])
    ];
}

$allLogos = [];
$allLogosConfig = [];

if ($model->logo_url) {
    $allLogos[] = 'logo_url, array("width" => 247, "height" => 78, "crop" => "fill")) .'" class="file-preview-image">';

    $allLogosConfig[] =[
            'caption' => 'Current Logo',
            'frameAttr'=> [
                'style' => 'height:150px; width:100px;',
            ],
            'url' => Url::toRoute(['delogo', 'id'=>$model->id])
    ];
}

//field additional information
//
//
$deleteMsg = 'Delete field information';

$gridColumns = [
    ['class' => 'kartik\grid\SerialColumn'],
    [
        'attribute' => 'value',
        'vAlign'=>'middle'
    ],
    [
        'class' => 'kartik\grid\ActionColumn',
        'dropdown' => false,
        'vAlign'=>'middle',
        'template' => '{delete}',
        'urlCreator' => function($action, $model, $key, $index) {
            if ($action == 'delete') {
                return Url::toRoute(['deleteinfo', 'id'=>$model->company_id, 'infoId'=>$model->id]);
            } else {
                return '';
            }
        },
        'deleteOptions'=>['title'=>$deleteMsg, 'data-toggle'=>'tooltip'],
    ],
];

$deleteRegMsg = 'Delete Regulation';

$regulationGridColumns = [
    ['class' => 'kartik\grid\SerialColumn'],
    [
        'attribute' => 'regulation_id',
        'label' => 'Regulation',
        'vAlign'=>'middle',
        'width' => '30%',
        'value'=>function ($model, $key, $index, $widget) {
             return $model->regulation->title;
        },
    ],
    [
        'attribute' => 'value',
    ],
    [
        'class' => 'kartik\grid\ActionColumn',
        'dropdown' => false,
        'vAlign'=>'middle',
        'template' => '{delete}',
        'urlCreator' => function($action, $model, $key, $index) {
            if ($action == 'delete') {
                return Url::toRoute(['deleteregulation', 'id'=>$model->company_id, 'regId'=>$model->id]);
            } else {
                return '';
            }
        },
        'deleteOptions'=>['title'=>$deleteRegMsg, 'data-toggle'=>'tooltip'],
    ],
];

?>

    <?= DetailView::widget([
        'model'=>$model,
        'condensed'=>true,
        'hover'=>true,
        'mode'=>DetailView::MODE_VIEW,
        'deleteOptions'=>[ // your ajax delete parameters
            'params' => ['id' => $model->id, 'kvdelete'=>true],
        ],
        'panel'=>[
            'heading'=>'Company Details',
            'type'=>DetailView::TYPE_INFO,
        ],
        'attributes' => $attributes,
        'formOptions' => ['action' => Url::toRoute(['view', 'id'=>$model->id])]
    ]);?>

Features

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => $gridColumns,
        'toolbar'=> false,
        'export' => false,
        'containerOptions'=>['style'=>'overflow: auto'], // only set when $responsive = false
        'headerRowOptions'=>['class'=>'kartik-sheet-style'],
        'containerOptions' => ['style'=>'overflow: auto'], // only set when $responsive = false
        'pjax' => true,
        'bordered' => true,
        'striped' => false,
        'condensed' => false,
        'responsive' => true,
        'showFooter' => false,
        'hover' => true,
        'showPageSummary' => false,
        'panel' => [
            'type' => GridView::TYPE_PRIMARY,
            'heading' => false,
        ],
        'toolbar'=> [
            ['content'=>
                Html::button('', ['type'=>'button', 'title'=>'Add', 'id'=>'add_fieldinfos', 'class'=>'showModalButton btn btn-success', 'value'=>Url::toRoute(['addinfo', 'id'=>$model->id])])
            ],
        ],
        'pjaxSettings' => [
            'neverTimeout' => true,
            'options' => [
                'id' => 'fieldinfos'
            ]
        ]
    ]);?>

Regulations

    <?= GridView::widget([
        'dataProvider' => $regulationDataProvider,
        'columns' => $regulationGridColumns,
        'toolbar'=> false,
        'export' => false,
        'containerOptions'=>['style'=>'overflow: auto'], // only set when $responsive = false
        'headerRowOptions'=>['class'=>'kartik-sheet-style'],
        'containerOptions' => ['style'=>'overflow: auto'], // only set when $responsive = false
        'pjax' => true,
        'bordered' => true,
        'striped' => false,
        'condensed' => false,
        'responsive' => true,
        'showFooter' => false,
        'hover' => true,
        'showPageSummary' => false,
        'panel' => [
            'type' => GridView::TYPE_PRIMARY,
            'heading' => false,
        ],
        'toolbar'=> [
            ['content'=>
                Html::button('', ['type'=>'button', 'title'=>'Add', 'id'=>'add_regulationinfos', 'class'=>'showModalButton btn btn-success', 'value'=>Url::toRoute(['addregulation', 'id'=>$model->id])])
            ],
        ],
        'pjaxSettings' => [
            'neverTimeout' => true,
            'options' => [
                'id' => 'regulationinfos'
            ]
        ]
    ]);?>

Company Logo

        <?= FileInput::widget([
            'name'=>'new_company_logo',
            'options' => [
                'id' => 'input-888'
            ],
            'pluginOptions' => [
                'uploadAsync' =>  false,
                'maxFileCount' =>  1,
                'initialPreview' => $allLogos,
                'initialPreviewConfig' => $allLogos,
                'initialPreviewAsData' => false,
                'overwriteInitial' => true,
                'autoReplace' => true,
                'showClose' => false,
                'showBrowse' => true,
                'showRemove' => false,
                'showUpload' => false,
                'previewFileType' => 'image',
                'uploadUrl' => Url::toRoute(['uplogo', 'id'=>$model->id]),
            ]
        ]) ?>

Main Image

        <?= FileInput::widget([
            'name'=>'new_company_image',
            'options' => [
                'id' => 'input-810'
            ],
            'pluginOptions' => [
                'uploadAsync' =>  false,
                'maxFileCount' =>  1,
                'initialPreview' => $allImages,
                'initialPreviewConfig' => $allImageConfig,
                'initialPreviewAsData' => false,
                'overwriteInitial' => true,
                'autoReplace' => true,
                'showClose' => false,
                'showBrowse' => true,
                'showRemove' => false,
                'showUpload' => false,
                'previewFileType' => 'image',
                'uploadUrl' => Url::toRoute(['upload', 'id'=>$model->id]),
            ]
        ]) ?>

<?php
    yii\bootstrap\Modal::begin([
        'header' => 'Add Field Info',
        'id'=>'addFieldInfoModal',
        'class' =>'modal',
        'size' => 'modal-md',
    ]);
        echo "

";
    yii\bootstrap\Modal::end();

        //js code:
    $this->registerJs('

        $(document).ready(function(){
            $(document).on("click", "#add_fieldinfos", function() {
                $("#addFieldInfoModal").modal("show")
                    .find("#modalContent")
                    .load($(this).attr("value"));
            });
        });
    ');
?>

<?php
    yii\bootstrap\Modal::begin([
        'header' => 'Add Regulation Info',
        'id'=>'addRegulationModal',
        'class' =>'modal',
        'size' => 'modal-md',
    ]);
        echo "

";
    yii\bootstrap\Modal::end();

        //js code:
    $this->registerJs('

        $(document).ready(function(){
            $(document).on("click", "#add_regulationinfos", function() {
                $("#addRegulationModal").modal("show")
                    .find("#regulationModalContent")
                    .load($(this).attr("value"));
            });
        });
    ');
?>


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: jan.schumann
 * Date: 20.01.15
 * Time: 10:25
 */

namespace Drupal\ModuleComposer\Bundle\ModuleComposerBundle;

use Drupal\ModuleComposer\Bundle\ModuleComposerBundle\DependencyInjection\RegisterProjectsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class ModuleComposerBundle extends Bundle {

  public function build(ContainerBuilder $container)
  {
    parent::build($container);

    $container->addCompilerPass(new RegisterProjectsPass());
  }
}


text:
{-# LANGUAGE CPP             #-}
{-# LANGUAGE GADTs           #-}
{-# LANGUAGE RecursiveDo     #-}
{-# LANGUAGE TemplateHaskell #-}

module Widgets.Dialog.Location where

import           Control.Monad.IO.Class (liftIO)
import           Control.Monad.Ref
import           Data.Dependent.Map     (DSum (..))
import           Data.Maybe             (fromMaybe, isJust)
import           Data.Monoid            ((<>))
import           Data.Text              (unpack)
import           GHCJS.DOM.Element
import           GHCJS.Foreign
import           GHCJS.Types
import           Network.URI            (isAbsoluteURI)
import           Reflex
import           Reflex.Dom
import           Reflex.Dynamic.TH
import           Reflex.Host.Class
import           Safe                   (tailSafe)
import           System.FilePath.Posix  (takeExtension, takeFileName)

import           LocalStorage           (setPref)
import           Widgets.Misc           (icon, iconLinkClass)
import           Widgets.Setting

#ifdef __GHCJS__
#define JS(name, js, type) foreign import javascript unsafe js name :: type
#else
#define JS(name, js, type) name :: type ; name = undefined
#endif

JS(dropboxOpen,"dropboxOpen($1, $2)", Element -> JSFun (JSString -> IO ()) -> IO ())
JS(hideModal,"jQuery('.modal.active')['modal']('hide')",IO ())

locationDialog :: MonadWidget t m => m (El t, (Event t String, Event t String))
locationDialog =
  elAttr' "div" ("class" =: "ui small modal") $
  do divClass "header" (text "Open Location")
     rec urlBox <-
           divClass "ui form" $
           divClass "field" $
           textInput $
             TextInputConfig "url"
                             ""
                             (fmap (const "") result)
                             (constDyn ("placeholder" =: "http://"))
         (events, result) <- divClass "actions" $
          do cors <- setting "CORS Proxy" True
             divClass "ui button" (text "Cancel")
             openButton <-
               iconLinkClass "checkmark" "Open" "ui positive right labeled icon button"
             url <-
               $(qDyn [|let url = $(unqDyn [|(_textInput_value urlBox)|]) in
                          if $(unqDyn [|_setting_value cors|])
                             then "http://cors.maxogden.com/" ++ url
                             else url|])

             result <-
               getURL $
               ffilter isAbsoluteURI $
               tag (current url) $
               leftmost [openButton,textInputGetEnter urlBox]
             performEvent_ $ fmap (const . liftIO $ hideModal) result

             return (ffilter (isJust . snd) result, result)
     return (fmap (fromMaybe "" . snd) events, fmap fst events)

getDropbox :: (MonadWidget t m) => m (Event t String, Event t String)
getDropbox =
  do (linkEl, _) <-
       buildElement "a" ("class" =: "item") $
       do icon "dropbox"
          text "Dropbox"
     postGui <- askPostGui
     runWithActions <- askRunWithActions
     (eRecv,eRecvTriggerRef) <- newEventWithTriggerRef
     callback <-
       liftIO $
       syncCallback1
         AlwaysRetain
         True
         (\jsUrl ->
            do let val = fromJSString jsUrl
               maybe (return ())
                     (\t ->
                        postGui $
                        runWithActions
                          [t :=>
                           Just val]) =<<
                 readRef eRecvTriggerRef)
     result <-
       getURL $
       fmapMaybe id eRecv
     liftIO $ dropboxOpen linkEl callback
     let events = ffilter (isJust . snd) result
     return (fmap (fromMaybe "" .
                   snd)
                  events
            ,fmap fst events)

getURL :: (MonadWidget t m) => Event t String -> m (Event t (String, Maybe String))
getURL url =
  do r <-
       performRequestAsync $
       fmap (\x -> XhrRequest "GET" x def) url
     let resp = fmap decodeXhrResponse r
     ext <-
       holdDyn "md" $
       fmap (tailSafe . takeExtension) url
     performEvent_ $
       fmap (liftIO .
             setPref "Last File" .
             show .
             takeFileName)
            url
     return $
       attachDyn ext resp
  where decodeXhrResponse = processXhrResponse . fmap unpack . _xhrResponse_body

processXhrResponse :: Maybe String -> Maybe String
processXhrResponse (Just "") = Nothing
processXhrResponse (Just ('C':'a':'n':'n':'o':'t':' ':'G':'E':'T':_)) = Nothing
processXhrResponse (Just r) = Just r
processXhrResponse Nothing = Nothing

mapSnd :: (a -> b) -> (c,a) -> (c,b)
mapSnd f (x,y) = (x,f y)


text:
from injector import singleton, inject

from .. import DataBuilder
from ..measurement import Measurements

try:
    import configparser
except ImportError:
    import configparser as configparser

from sht1x.Sht1x import Sht1x as SHT1x

@singleton
class Sensor:
    name = "SHT1x"
    priority = 1

    @inject
    def __init__(self, config_parser: configparser.ConfigParser):
        data_pin = int(config_parser.get('sht1x_sensor', 'data_pin'))
        sck_pin = int(config_parser.get('sht1x_sensor', 'sck_pin'))

        self.sht1x = SHT1x(dataPin=data_pin, sckPin=sck_pin, gpioMode=SHT1x.GPIO_BCM)

    def measure(self, data_builder: DataBuilder, measurements: Measurements) -> None:
        (temperature, humidity) = self.sht1x.read_temperature_C_and_humidity()

        if temperature > -40.0:
            try:
                dew_point = self.sht1x.calculate_dew_point(temperature, humidity)
                dew_point = round(dew_point, 2)
            except ValueError:
                dew_point = None

            temperature = round(temperature, 2)
            humidity = round(humidity, 2)
        else:
            temperature = None
            humidity = None
            dew_point = None

        if temperature and humidity and dew_point and -30 < temperature < 80 and 5 < humidity <= 100:
            measurements.temperature = temperature
            measurements.relative_humidity = humidity

            data_builder.add(self.name, "temperature", "°C", temperature)
            if dew_point:
                data_builder.add(self.name, "dew point", "°C", dew_point, True)
            data_builder.add(self.name, "relative humidity", "%", humidity)


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

package org.openspaces.admin.transport;

/**
 * An aggregated view of all {@link org.openspaces.admin.transport.TransportDetails}.
 *
 * @author kimchy
 */
public interface TransportsDetails {

    /**
     * Returns the total number of minimum threads defined within all current
     * discovered {@link org.openspaces.admin.transport.Transport}s.
     */
    int getMinThreads();

    /**
     * Returns the total number of maximum threads defined within all current
     * discovered {@link org.openspaces.admin.transport.Transport}s.
     */
    int getMaxThreads();
}


text:
struct Matrix44;
struct Vector3
{
	float x,y,z;

	Vector3() : x(0), y(0), z(0) {}
	Vector3(float x0, float y0, float z0) : x(x0), y(y0), z(z0) {}

	float Length() const;
	Vector3 Normal() const;
	void Normalize();
	float	DotProduct( const Vector3& v ) const;
	Vector3 CrossProduct( const Vector3& v ) const;

	Vector3 operator + () const;
	Vector3 operator - () const;
	Vector3 operator + ( const Vector3& rhs ) const;
	Vector3 operator - ( const Vector3& rhs ) const;
	Vector3& operator += ( const Vector3& rhs );
	Vector3& operator -= ( const Vector3& rhs );
	Vector3& operator *= ( const Vector3& rhs );
	Vector3& operator /= ( const Vector3& rhs );

	Vector3 operator * ( const Matrix44& rhs ) const;
	Vector3& operator *= ( Matrix44& rhs );

	template <class T>
	Vector3 operator * ( T t ) const {
		return Vector3(x*t, y*t, z*t);
	}

	template <class T>
	Vector3 operator / ( T t ) const {
		return Vector3(x/t, y/t, z/t);
	}

	template <class T>
	Vector3& operator *= ( T t ) {
		*this = Vector3(x*t, y*t, z*t);
		return *this;
	}

	template <class T>
	Vector3& operator /= ( T t ) {
		*this = Vector3(x/t, y/t, z/t);
		return *this;
	}

};


text:
package erepnikov.map;

import java.util.Calendar;

/**
 * Class User
 *
 * @author Egor Repnikov
 * @version 0.0.1
 * @since 27.07.2017
 */
public class User {

    /**
     * User's name
     */
    private String name;

    /**
     * Count of user's children
     */
    private int children;

    /**
     * User's birthday
     */
    private Calendar birthday;

    /**
     * Set all fields
     * @param name
     * @param chidren
     * @param birthday
     */
    public User(String name, int chidren, Calendar birthday) {
        this.name = name;
        this.children = chidren;
        this.birthday = birthday;
    }

    /**
     * @return User's name
     */
    public String getName() {
        return this.name;
    }

    /**
     * @return Count of user's children
     */
    public int getChildren() {
        return this.children;
    }

    /**
     * @return User's birthday
     */
    public Calendar getBirthday() {
        return this.birthday;
    }
}