text:
package me.shkschneider.skeleton.helper;

import android.annotation.TargetApi;
import android.os.PowerManager;
import android.support.annotation.FloatRange;
import android.support.annotation.NonNull;
import android.util.TypedValue;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

import me.shkschneider.skeleton.R;

public class ScreenHelper {

    protected ScreenHelper() {
        // Empty
    }

    public static final int DENSITY_LDPI = 120;
    public static final int DENSITY_MDPI = 160;
    public static final int DENSITY_TVDPI = 213; // MDPI * 1.33
    public static final int DENSITY_HDPI = 240;
    public static final int DENSITY_XHDPI = 320;
    public static final int DENSITY_XXHDPI = 480;
    public static final int DENSITY_XXXHDPI = 640;

    public static final float BRIGHTNESS_RESET = -1.0F;
    public static final float BRIGHTNESS_MIN = 0.0F;
    public static final float BRIGHTNESS_MAX = 1.0F;

    public static final int ROTATION_0 = 0;
    public static final int ROTATION_90 = 1; // 90 counter-clockwise
    public static final int ROTATION_180 = 2; // upside-down
    public static final int ROTATION_240 = 3; // 90 clockwise

    // Does NOT @RequiresPermission(Manifest.permission.WAKE_LOCK)
    public static boolean wakeLock(@NonNull final Window window) {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        return true;
    }

    public static boolean on() {
        final PowerManager powerManager = SystemServices.powerManager();
        if (powerManager == null) {
            LogHelper.warning("PowerManager was NULL");
            return true;
        }
        if (AndroidHelper.api() >= AndroidHelper.API_20) {
            return on20(powerManager);
        }
        else {
            return on7(powerManager);
        }
    }

    @TargetApi(AndroidHelper.API_20)
    private static boolean on20(@NonNull final PowerManager powerManager) {
        return powerManager.isInteractive();
    }

    @SuppressWarnings("deprecation")
    private static boolean on7(@NonNull final PowerManager powerManager) {
        return powerManager.isScreenOn();
    }

    public static float brightness(@NonNull final Window window) {
        return window.getAttributes().screenBrightness;
    }

    public static boolean brightness(@NonNull final Window window, @FloatRange(from=BRIGHTNESS_RESET, to=BRIGHTNESS_MAX) final float brightness) {
        final WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.screenBrightness = ((brightness < BRIGHTNESS_MIN) ? BRIGHTNESS_RESET : brightness);
        window.setAttributes(layoutParams);
        return true;
    }

    public static float density() {
        return ApplicationHelper.resources().getDisplayMetrics().density;
    }

    public static int dpi() {
        return ApplicationHelper.resources().getDisplayMetrics().densityDpi;
    }

    public static int height() {
        return ApplicationHelper.resources().getDisplayMetrics().heightPixels;
    }

    public static int width() {
        return ApplicationHelper.resources().getDisplayMetrics().widthPixels;
    }

    @Deprecated
    public static int statusBarHeight() {
        return (int) ApplicationHelper.resources().getDimension(R.dimen.statusBar);
    }

    public static int rotation() {
        final WindowManager windowManager = SystemServices.windowManager();
        if (windowManager == null) {
            LogHelper.warning("WindowManager was NULL");
            return 0;
        }
        final Display display = windowManager.getDefaultDisplay();
        if (display == null) {
            LogHelper.warning("Display was NULL");
            return 0;
        }

        return display.getRotation();
    }

    @Deprecated
    public static int orientation() {
        return rotation();
    }

    public static int pixelsFromDp(@FloatRange(from=0.0) final float dp) {
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, ApplicationHelper.resources().getDisplayMetrics()));
    }

}


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

    <parent>
        <artifactId>coolfs</artifactId>
        <groupId>com.sfl.coolmonkey.coolfs</groupId>
        <version>0.1.0</version>
    </parent>

    <groupId>com.sfl.coolmonkey.coolfs.api</groupId>
    <artifactId>api</artifactId>
    <packaging>pom</packaging>

    <properties>
        <orica.core.version>1.4.6</orica.core.version>
        <commons.io.version>2.4</commons.io.version>
    </properties>

    <modules>
        <module>api-client</module>
        <module>api-facade</module>
        <module>api-model</module>
        <module>api-rest</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>com.sfl.coolmonkey.commons.api</groupId>
            <artifactId>api-model</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.sfl.coolmonkey.coolfs.service</groupId>
                <artifactId>service-impl</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>com.sfl.coolmonkey.coolfs.api</groupId>
                <artifactId>api-model</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>ma.glasnost.orika</groupId>
                <artifactId>orika-core</artifactId>
                <version>${orica.core.version}</version>
            </dependency>
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>${commons.io.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>coolmonkey-release</id>
            <url>http://maven.sflpro.com/content/repositories/coolmonkey-release/</url>
        </repository>
        <repository>
            <id>maven-central</id>
            <url>https://repo.maven.apache.org/maven2/</url>
        </repository>
    </repositories>

</project>

redpajama_set_name: RedPajamaGithub


text:
module GoTransverseTractApi

  module BillingAccount

    class InvoiceItemCharge < InvoiceItem

      class << self

        #
        # @param {Long} invoice_item_eid
        # @param {Hash} options
        #
        def find_by_invoice_item_eid invoice_item_eid, options={}
          return nil unless invoice_item_eid.present?

          params ||= GoTransverseTractApi::ApiData.new.get_query_params({invoice_item_eid: invoice_item_eid}, options)
          GoTransverseTractApi.get_response_for(self, params)
        end

      end

    end

  end

end


text:
using OpenStardriveServer.Domain.Systems.Standard;

namespace OpenStardriveServer.UnitTests.Domain.Systems;

public class SystemBaseStateTests
{
    [TestCase(0, true)]
    [TestCase(1, false)]
    [TestCase(2, false)]
    public void When_checking_for_insufficient_power(int power, bool insufficient)
    {
        var state = new StandardSystemBaseState
        {
            RequiredPower = 1,
            CurrentPower = power
        };

        var result = state.HasInsufficientPower();

        Assert.That(result.HasValue, Is.EqualTo(insufficient));
        result.IfSome(x => Assert.That(x, Is.EqualTo("insufficient power")));
    }

    [TestCase(true)]
    [TestCase(false)]
    public void When_checking_if_disabled(bool disabled)
    {
        var state = new StandardSystemBaseState
        {
            Disabled = disabled
        };

        var result = state.IsDisabled();

        Assert.That(result.HasValue, Is.EqualTo(disabled));
        result.IfSome(x => Assert.That(x, Is.EqualTo("system disabled")));
    }

    [TestCase(true)]
    [TestCase(false)]
    public void When_checking_if_damaged(bool damaged)
    {
        var state = new StandardSystemBaseState
        {
            Damaged = damaged
        };

        var result = state.IsDamaged();

        Assert.That(result.HasValue, Is.EqualTo(damaged));
        result.IfSome(x => Assert.That(x, Is.EqualTo("system damaged")));
    }
}


text:
/**
 *
 */
package org.jlcf.example.advancedhelloworld;

import org.jlcf.core.util.GenericProcessorRequest;

/**
 * Sample Message Type for component A
 *
 * @author Petros Pissias
 *
 */
public class ComponentAMessageB extends
		GenericProcessorRequest<ComponentAMessageType> {

	private final String data;

	public ComponentAMessageB(String data) {
		super(ComponentAMessageType.MESSAGE_TYPE_B);
		this.data = data;
	}

	public String getData() {
		return data;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
  <context-root>studio</context-root>
</jboss-web>


text:
layout:     post
title:      self portrait 60
date:       2019-05-14 00:04:24
summary:
categories: drawing
---
![self portrait 60](/images/diary/self-portrait-60.png ".")


text:
Serendip.Core = (function (ajax, history) {
    var my = {};

    my.fieldConfig = [];
    my.fields = [];
    my.facets = [];
    my.highlightFields = [];

    var _queryParams = [];
    var _enableAllFields = false;

    var solrUrl = "";

    Serendip.Utils.setupEvents(my);

    my.init = function () {
        initFacets();

        my.trigger("views.init");

        my.fieldConfig.sort(fieldSort);
        updateFieldsQueryString();

        my.trigger("views.init.done");

        initHistory();
    };

    my.addFacet = function(facet){
        my.facets.push(facet);
    };

    my.addFieldConfig = function(config) {
        my.fieldConfig.push(config);
        my.fields.push(config.name);
    };

    my.getFieldConfigForField = function(field) {
        for (var i = 0; i < my.fieldConfig.length; i++) {
            var config = my.fieldConfig[i];
            if (config.name == field) {
                return config;
            }
        }

        return null;
    };

    my.enableAllFields = function(enable) {
        _enableAllFields = enable;
        if(enable){
            my.addQueryParam("fl", "*");
        }else{
            my.removeQueryParam("fl");
        }

        updateFieldsQueryString();
    };

    my.setHighlightFields = function(fields) {
        addQueryParam("hl.fl", fields.join(" "));
        my.highlightFields = fields;
    };

    my.removeQueryParam = function(key){
        delete _queryParams[key];
    };

    my.addQueryParam = function(name, value) {
        var param = name + "=" + value;

        var found = false;
        for (var key in _queryParams) {
            var p = _queryParams[key];
            if (p.indexOf(name) != -1) {
                _queryParams[key] = param;
                found = true;
            }
        }

        if (!found) {
            _queryParams.push(name + "=" + value);
        }

    };

    my.setSolrUrl = function(url) {
        solrUrl = url;

        var currentUrlParsed = Serendip.Utils.parseUri(document.URL);
        var solrUrlParsed = Serendip.Utils.parseUri(url);

        if (currentUrlParsed.host != solrUrlParsed.host || currentUrlParsed.port != solrUrlParsed.port) {
            console.warn("The hostname and port of the solr url does not match the hostname and port of the page url. " +
                "This is likely a bug since you will (likely) experience crossite scripting errors when " +
                "making ajax requests to Solr.");
            console.warn("Solr host/port: " + solrUrlParsed.host + ":" + solrUrlParsed.port
                + " Page host/port: " + currentUrlParsed.host + ":" + currentUrlParsed.port);
        }
    };

    my.saveHistoryItem = function() {
        var hash = "";

        var params = [];

        my.trigger("saveInQueryStr", function(id, value, sortIndex){
                var item = {id: id, value: value, sortIndex: sortIndex};
                params.push(item);
            }
        );

        params = params.sort(sortQueryParam);

        for(var i = 0; i < params.length; i++){
            var param = params[i];

            hash = hash + "/" + param.id + "/" + param.value;
        }

        history.load("!" + hash);
    };

    my.getIdForFieldName = function(field) {
        var config = my.getFieldConfigForField(field);
        if(config != null){
            return config.id;
        }

        return null;
    };

    my.getFieldNameForId = function(id) {
        for (var i = 0; i < my.fieldConfig.length; i++) {
            var config = my.fieldConfig[i];
            if (config.id == id) {
                return config.name;
            }
        }

        return "";
    };

    my.search = function () {
        my.trigger("search");
        doRequest(true);
    };

    function initFacets() {
        for (var i = 0; i < my.facets.length; i++) {
            var facet = my.facets[i];

            if (facet.facets.length > 0) {
                for (var k = 0; k < facet.facets.length; k++) {
                    var subFacet = facet.facets[k];
                    my.addFacet(subFacet);
                }
            }
        }
    };

    function initHistory(){
        history.on("history.change", function(queryParams){
             initFromQueryStr(queryParams);
        });

        history.init();
    };

    function initFromQueryStr(queryStr) {

        queryStr = decodeURIComponent(queryStr);

        // Add postfix to map ids to avoid using "reserved" javascript words
        // ex paramsMap["sort"] will not work (sort is already funksjon on array)
        var paramsMap = parseQueryToMap(queryStr, "");
        my.trigger("initFromQueryStr", queryStr, paramsMap);

        doRequest(false);
    };

    function updateFieldsQueryString() {
        if (_enableAllFields == false) {
            var enabledFields = [];
            for(var i = 0; i < my.fieldConfig.length; i++){
                var config = my.fieldConfig[i];
                if(config.isEnabled){
                    enabledFields.push(config.name);
                }
            }

            my.removeQueryParam("fl");
            my.addQueryParam("fl", enabledFields.join(","));
        }
    };

    function fieldSort(a, b) {
        var x = a.header.toLowerCase();
        var y = b.header.toLowerCase();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    };

    function sortQueryParam(a, b) {
        var x = a.sortIndex;
        var y = b.sortIndex;
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }

    function doRequest(saveHistoryItem) {
        my.trigger("wait");

        if(saveHistoryItem){
            my.saveHistoryItem();
        }else{
            continueRequest();
        }
    };

    function getFullQuery() {
        var request = "";

        my.trigger("buildRequest", function(data){
            request = request + data;
        });

        var params = getParamsAsQueryString(_queryParams);

        var reqString = solrUrl + "?" + params;
        reqString += request + "&wt=json";

        return reqString;
    };

    function continueRequest() {

        var url = getFullQuery();
        ajax.get(url, handleResponse, handleError);
    };

    function handleError(statusCode, msg) {
        my.trigger("error.request", statusCode, msg);
    };

    function handleResponse(data) {
        my.trigger("renderStart");
        my.trigger("render", data);
        my.trigger("renderFinished");
    };

   function getParamsAsQueryString(params) {
        var query = "";

        for (var i = 0; i < params.length; i++) {
            query = query + params[i];
            if (i < params.length - 1)
                query = query + "&";
        }

        return query;
    };

    function parseQueryToMap(queryStr) {
        var split = queryStr.split("&");

        var queryParams = {};

        for (var i = 0; i < split.length; i++) {
            var params = split[i].split("=");
            queryParams[params[0]] = params[1];
        }

        split = queryStr.replace("!/", "").split("/");

        for (i = 0; i < split.length-1; i+=2) {
            var key = split[i];
            var value = split[i+1];
            queryParams["" + key + ""] = value;
        }

        return queryParams;
    }

    return my;
}(Serendip.Ajax, Serendip.History));

var serendip = Serendip.Core;


text:
<!DOCTYPE html>

        <title>DEQ Interactive Map User Admin</title>

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <link rel="stylesheet" href="app/resources/UserAdmin.css">


text:
import asyncio
import sys
import unittest

from edb.common import devmode
from . import server

exec(sys.argv[1], globals(), locals())

class ProcTest(server.TestCase):
    def notify_parent(self, mark):
        print(str(mark), flush=True)

    async def wait_for_parent(self, mark):
        self.assertEqual(
            (await self.stdin.readline()).strip(),
            str(mark).encode(),
        )

    @classmethod
    def setUpClass(cls):
        super().setUpClass()

        async def _setup():
            cls.stdin = asyncio.StreamReader()
            await cls.loop.connect_read_pipe(
                lambda: asyncio.StreamReaderProtocol(cls.stdin),
                sys.stdin.buffer,
            )
        cls.loop.run_until_complete(_setup())

    exec(sys.argv[2], globals(), locals())

def main():
    cov_config = devmode.CoverageConfig.from_environ()
    if cov_config:
        cov = cov_config.new_coverage_object()
        cov.start()
        try:
            unittest.main(argv=sys.argv[:1], verbosity=2)
        finally:
            cov.stop()
            cov.save()
    else:
        unittest.main(argv=sys.argv[:1], verbosity=2)

if __name__ == "__main__":
    main()


text:
require_relative "jquery-timepicker-addon/version"
require_relative "jquery-timepicker-addon/engine"

module JqueryTimepickerAddon
end


text:
'use strict';

var path = require('path');
var red = require('ansi-red');
var templates = require('./');

templates.on('templates.preInit', function(app) {
  // console.log(app);
});

templates.on('templates.postInit', function(app) {
  // console.log(app);
});

/**
 * Create our `app`
 */

var app = templates();

/**
 * Listen for errors
 */

app.use(function(app) {
  app.on('error', function(err) {
    console.log('app:', red(err));
  });
  return function(collection) {
    collection.on('error', function(err) {
      console.log('collection:', red(err));
    });
    return function(view) {
      view.on('error', function(err) {
        console.log('view:', red(err));
      });
    };
  };
});

/**
 * Engine
 */

app.engine('*', require('engine-base'));
app.engine('html', require('engine-base'));
app.option('engine', '*');

/**
 * Collections and rendering
 */

app.preRender(/./, function(file, next) {
  file.data.title = 'foo';
  next();
});

app.data({title: 'Home'});
app.create('pages')
  .engine('*', require('engine-base'))
  .addView('home', {content: 'The <%= title %> page'})
  .set('locals.title', 'HOOMMMME!')
  .render(function(err, res) {
    if (err) throw err;
    console.log(res.content);
  });

/**
 * Plugins
 */

app.use(function(app) {
  app.section = app.create;
  return function(views) {
    views.on('addView', function() {
      // console.log(views._callbacks)
    });

    // create a custom `.foo()` method on the collection
    views.define('foo', views.addView);
    return function(view) {

      // also add `.foo()` to the view instance for chaining
      view.define('foo', views.foo.bind(views));
    };
  };
});

app.section('articles')
  // this first `.foo` is from the collection instance
  .foo('one.html', {content: 'The <%= title %> page'})
  .set('locals.title', 'One')
  .render(function(err, res) {
    if (err) throw err;
  })

  // this `.foo` is from a `view` instance
  .foo('two.html', {content: 'The <%= title %> page'})
  .set('locals.title', 'Two')
  .render(function(err, res) {
    if (err) throw err;
    // console.log(res.content);
  });

/**
 * Events
 */

var posts = app.create('posts');
posts.engine('html', require('engine-base'));
posts.option('engine', 'html');

var view = posts.addView('home.html', {content: 'The <%= title %> page'})
  .render({title: 'Home'}, function(err, res) {
    if (err) throw err;
    // console.log(res.content);
  });

var collection = app.collection();
collection
  .option('renameKey', function(key) {
    return path.basename(key);
  })
  .addView('foo/bar/baz/a.md', {content: '...'})
  .addView('foo/bar/baz/b.md', {content: '...'})
  .addView('foo/bar/baz/c.md', {content: '...'});

var list = app.list(collection)
// console.log(list)

// console.log(collection.views);


text:
require 'spec_helper'

describe "Users" do
  describe "GET /baker_server_users" do
    let!(:user) { Factory(:user) }
    before(:each) do
      visit users_path
    end

    it "should be successful" do
      page.should have_content("Listing users")
    end

    it "should have a link to create new user" do
      click_link("New User")
      page.should have_content("New user")
    end

    it "should show created user" do
      page.should have_content(user.email_address)
    end

    it "should have link for editing user" do
      click_link "Edit"
      page.should have_content("Editing user")
    end

  end
end


text:
package org.apache.hadoop.yarn.server.nodemanager;

import static org.junit.Assert.fail;

import java.io.IOException;

import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.junit.Test;

public class TestNodeManager {

  public static final class InvalidContainerExecutor extends
      DefaultContainerExecutor {
    @Override
    public void init() throws IOException {
      throw new IOException("dummy executor init called");
    }
  }

  @Test
  public void testContainerExecutorInitCall() {
    NodeManager nm = new NodeManager();
    YarnConfiguration conf = new YarnConfiguration();
    conf.setClass(YarnConfiguration.NM_CONTAINER_EXECUTOR,
        InvalidContainerExecutor.class,
        ContainerExecutor.class);
    try {
      nm.init(conf);
      fail("Init should fail");
    } catch (YarnRuntimeException e) {
      //PASS
      assert(e.getCause().getMessage().contains("dummy executor init called"));
    } finally {
      nm.stop();
    }
  }

}


text:
require 'active_support'
require File.expand_path(File.join(File.dirname(__FILE__), 'internal_navigation_store'))

module ProtesteGenerateApplication
  module Controller
    extend ActiveSupport::Concern

    included do
      before_filter :build_breadcrumbs, :set_user_language, :check_user_status
      helper_method :current_application, :proteste_applications, :internal_navigation,
      :current_language, :proteste_languages

      unless Rails.application.config.consider_all_requests_local
        rescue_from Exception, with: lambda { |exception| catch_exception 500, exception }
        rescue_from ActionController::UnknownController,
          ActionController::UnknownAction,
          ActionController::RoutingError,
          ActiveRecord::RecordNotFound,
          with: lambda { |exception| catch_exception 404, exception }
      end

      rescue_from ActiveRecord::StatementInvalid, with: lambda { |exception| catch_exception 500, exception }
    end

    def check_user_status
      return unless current_user
      if current_user.blocked?
        I18n.locale = 'en'
        flash[:error] = t('devise.failure.blocked')
        sign_out(:user)
        redirect_to new_user_session_path
      elsif current_user.access_locked?
        I18n.locale = 'en'
        flash[:error] = t('devise.failure.locked')
        sign_out(:user)
        redirect_to new_user_session_path
      end
    end

    def catch_exception(status, exception)
      # show exception in log of server
      Rails.logger.info "Exception caught by customizing of PAF Framework:"
      Rails.logger.error exception.message
      Rails.logger.error exception.backtrace.inspect

      @exception = exception
      message = @exception.message

      if statement_invalid_on_delete?(exception)
        message = t('general.messages.delete_error_with_associations')
        flash[:error] = message
      else
        flash[:error] = t('general.messages.modal_ajax_error')
      end

      ErrorReportMailer.report(exception).deliver rescue flash[:error] += ".<br />Contact your sistem administrator and report the error."

      if !request.env["HTTP_REFERER"].blank? and
        request.env["HTTP_REFERER"] != request.env["REQUEST_URI"]
        if statement_invalid_on_delete?(exception)
          render template: 'shared/batch_destroy.js.erb'
        else
          redirect_to :back
        end
      elsif request.env["REQUEST_URI"] != root_path
        if statement_invalid_on_delete?(exception)
          render template: 'shared/batch_destroy.js.erb'
        else
          redirect_to root_path
        end
      else
        respond_to do |format|
          format.html { redirect_to eval("proteste_generate_application_error_#{status}_url(message: message)") }
          format.js   {
            if statement_invalid_on_delete?(exception)
              render template: 'shared/batch_destroy.js.erb'
            else
              render template('proteste_generate_application/errors/error_in_javascript.js.erb'), layout: nil, status: status
            end
          }
          format.json { render nothing: true, status: status }
          format.all  { render nothing: true, status: status }
        end
      end
    end

    def statement_invalid_on_delete?(exception)
      exception.is_a?(ActiveRecord::StatementInvalid) and ["destroy","batch_destroy"].include?(self.action_name)
    end

    def set_user_language
      return unless current_user
      I18n.locale = current_language['code']
    end

    def current_language
      return session[:current_language] unless session[:current_language].nil?
      language                    = ProtesteGenerateApplication::Consumers.current_language(current_user.login,params[:locale])
      I18n.locale                 = language['code']
      session[:current_language]  = language
    end

    def proteste_languages
      session[:proteste_languages] ||= ProtesteGenerateApplication::Consumers.languages
    end

    def current_application
      session[:current_application] ||= ProtesteGenerateApplication::Consumers.current_application(APP_ID)
    end

    def proteste_applications
      session[:proteste_applications] ||= ProtesteGenerateApplication::Consumers.applications(current_user.login, APP_ID)
    end

    def internal_navigation
      ProtesteGenerateApplication::InternalNavigationStore.load_internal_navigation(view_context, APP_ID)
    end

    def build_breadcrumbs
      actions = ["index", "show", "new", "edit", "create", "update"]

      if (self.action_methods.to_a & actions) == actions
        add_breadcrumb(:index, url_for(action: :index, only_path: true))
        add_breadcrumb(t('general.actions.list'), url_for(action: :index, only_path: true))
        return true
      end
      false
    end

    def set_layout
      'application_proteste'
    end
  end
end


text:
package ${package}.client;

import ${package}.client.config.AppGinjector;
import org.orgama.client.OrgEntryPoint;
import org.orgama.client.config.OrgGinjector;
import com.google.gwt.core.client.GWT;

/**
 * Entry point classes define
 * onModuleLoad().
 */
public class AppMain extends OrgEntryPoint {

    /**
     * The applications entrypoint should provide a reference to the class
     * representing the application's injector
     * @return
     */
    @Override
    protected OrgGinjector getInjector() {
        return GWT.create(AppGinjector.class);
    }

    /**
     * called before the injector is initialized.
     */
    @Override
    protected void beforeInjection() {

    }

    /**
     * called after the injector is initialized.
     */
    @Override
    protected void afterInjection() {

    }

}


text:
namespace System.ServiceModel.Channels
{
    using System.Globalization;
    using System.Runtime;

    struct SequenceRange
    {
        // fields
        Int64 lower;
        Int64 upper;

        // constructors
        public SequenceRange(Int64 number)
            : this(number, number)
        {
        }

        public SequenceRange(Int64 lower, Int64 upper)
        {
            if (lower < 0)
            {
                throw Fx.AssertAndThrow("Argument lower cannot be negative.");
            }

            if (lower > upper)
            {
                throw Fx.AssertAndThrow("Argument upper cannot be less than argument lower.");
            }

            this.lower = lower;
            this.upper = upper;
        }

        // properties
        public Int64 Lower
        {
            get { return this.lower; }
        }

        public Int64 Upper
        {
            get { return this.upper; }
        }

        public static bool operator ==(SequenceRange a, SequenceRange b)
        {
            return (a.lower == b.lower) && (a.upper == b.upper);
        }

        public static bool operator !=(SequenceRange a, SequenceRange b)
        {
            return !(a == b);
        }

        public bool Contains(Int64 number)
        {
            return (number >= this.lower && number <= this.upper);
        }

        public bool Contains(SequenceRange range)
        {
            return (range.Lower >= this.lower && range.Upper <= this.upper);
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            else if (obj is SequenceRange)
            {
                return this == (SequenceRange)obj;
            }
            else
            {
                return false;
            }
        }

        public override int GetHashCode()
        {
            Int64 hashCode = (this.upper ^ (this.upper - this.lower));
            return (int)((hashCode << 32) ^ (hashCode >> 32));
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}-{1}", this.lower, this.upper);
        }
    }
}


text:
INSERT INTO oskari_maplayer(type, name, groupId,
                            minscale, maxscale,
                            url, locale)
  VALUES('wfslayer', 'elf_gn_ign_es', 901,
         100000, 1,
         'wfs', '{fi:{name:"GN Geographical Names - ign.es", subtitle:""},sv:{name:"GN Geographical Names - ign.es", subtitle:""},en:{name:"GN Geographical Names - ign.es", subtitle:""}}');

-- link to inspire theme;
INSERT INTO oskari_maplayer_themes(maplayerid,
                                   themeid)
  VALUES((SELECT MAX(id) FROM oskari_maplayer),
         (SELECT id FROM portti_inspiretheme WHERE locale LIKE '%Geographical names%'));

-- add template model stuff;
INSERT INTO portti_wfs_template_model(name, description, type, request_template, response_template)
VALUES (
	'ELF GN', 'ELF GN PoC', 'mah taip',
	'/fi/nls/oskari/fe/input/format/gml/inspire/gn/ign_es_wfs_template.xml',
	'/fi/nls/oskari/fe/input/format/gml/gn/INSPIRE_generic_GN.groovy');

-- add wfs specific layer data;
INSERT INTO portti_wfs_layer (
    maplayer_id,
    layer_name,
    url, username, password,
    gml_geometry_property, gml_version, gml2_separator,
    wfs_version, max_features,
    feature_namespace,
    properties,
    feature_type,
    selected_feature_params,
    feature_params_locales,
    geometry_type,
    selection_sld_style_id, get_map_tiles, get_feature_info, tile_request, wms_layer_id,
    srs_name,
    feature_element, feature_namespace_uri,
    geometry_namespace_uri,
    get_highlight_image,
    wps_params,
    tile_buffer,
    job_type,
    wfs_template_model_id)
    VALUES ( (select max(id) from oskari_maplayer),
      'ELF_GN_ign_es',
       'http://www.ign.es/wfs-inspire/ngbe', null, null,
       'geom', '3.2.1', false,
       '2.0.0', 5000,
       'elf-lod1gn',
       '',
       '{"default" : "*geometry:Geometry,text:String,script:String,sourceOfName:String,nameStatus:String,nativeness:String,language:String,beginLifespanVersion:String,endLifespanVersion:String,localType:String"}',
       '{}',
       '{}',
       '2d',
       NULL, true, true, false, NULL,
	'urn:ogc:def:crs:EPSG::3857',
	'NamedPlace', 'urn:x-inspire:specification:gmlas:GeographicalNames:3.0',
	'',
	true, '{}', '{ "default" : 1, "oskari_custom" : 1}',
	'oskari-feature-engine', (select max(id) from portti_wfs_template_model));

-- add wfs layer styles;
INSERT INTO portti_wfs_layer_style (name,sld_style) VALUES(
	'oskari-feature-engine',
	'/fi/nls/oskari/fe/output/style/inspire/gn/ign_es.xml'
);

-- link wfs layer styles;
INSERT INTO portti_wfs_layers_styles (wfs_layer_id,wfs_layer_style_id) VALUES(
	(select max(id) from portti_wfs_layer),
	(select max(id) from portti_wfs_layer_style));

-- setup permissions for guest user;
INSERT INTO oskari_resource(resource_type, resource_mapping) values ('maplayer', 'wfs+elf_gn_ign_es');

-- permissions;
-- adding permissions to roles with id 10110, 2, and 3;

-- give view_layer permission for the resource to ROLE 10110 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_LAYER', '10110');

-- give view_layer permission for the resource to ROLE 1 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_LAYER', '1');

-- give view_layer permission for the resource to ROLE 2 (user);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_LAYER', '2');

-- give publish permission for the resource to ROLE 2 (user);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'PUBLISH', '2');

-- give publish permission for the resource to ROLE 3 (admin);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'PUBLISH', '3');

-- give view_published_layer permission for the resource to ROLE 10110 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_PUBLISHED', '10110');

-- give view_published_layer permission for the resource to ROLE 2 (user);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_PUBLISHED', '2');

-- give view_published_layer permission for the resource to ROLE 10110 (guest);
INSERT INTO oskari_permission(oskari_resource_id, external_type, permission, external_id) values
((SELECT MAX(id) FROM oskari_resource), 'ROLE', 'VIEW_PUBLISHED', '1');


text:
'use strict';

var mergeArray = require('../../lib').mergeArray;

// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {
    mergeArray(trace.text, cd, 'tx');
    mergeArray(trace.hovertext, cd, 'htx');

    var marker = trace.marker;
    if(marker) {
        mergeArray(marker.opacity, cd, 'mo');
        mergeArray(marker.color, cd, 'mc');

        var markerLine = marker.line;
        if(markerLine) {
            mergeArray(markerLine.color, cd, 'mlc');
            mergeArray(markerLine.width, cd, 'mlw');
        }
    }
};


text:
<?php

namespace Scrumator\Bundle\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class Page1Controller extends Controller
{
    /**
     * @Route("/page1/{name}", name="page1")
     * @Template()
     */
    public function indexAction($name)
    {
        return array(
            'name'=>$name
        );
    }

}


text:
<?php
header("Access-Control-Allow-Origin: *");

$curdir = dirname(__FILE__);
include_once ($curdir."/../api.lib/api.base.php");
include_once ($curdir."/../../config/config.php");

FHQHelpers::checkAuth();

$result = array(
	'result' => 'fail',
	'data' => array(),
);

$conn = FHQHelpers::createConnection($config);

if (!FHQSecurity::isAdmin())
	FHQHelpers::showerror(912, 'only for admin');

if (!FHQHelpers::issetParam('userid'))
  FHQHelpers::showerror(889, 'Error 889: not found parameter "userid"');

$userid = FHQHelpers::getParam('userid', 0);

if (!is_numeric($userid))
  FHQHelpers::showerror(885, 'userid must be numeric');

try {
	$params = array($userid);
 	$conn->prepare('DELETE FROM user WHERE iduser = ?')->execute($params);
 	$conn->prepare('DELETE FROM users_games WHERE userid = ?')->execute($params);
 	$result['result'] = 'ok';
} catch(PDOException $e) {
 	FHQHelpers::showerror(882, $e->getMessage());
}

echo json_encode($result);


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Bot. , London 12: 356 (1874)

#### Original name
Ryparobius woolhopensis Renny, 1873

### Remarks
null


text:
"""
test_motome_notemodel
----------------------------------

Tests for `Motome.Models.NoteModel`
"""

import glob
import os
import shutil
import unittest

from Motome.Models.NoteModel import NoteModel
from Motome.config import NOTE_EXTENSION, HISTORY_FOLDER, END_OF_TEXT

TESTS_DIR = os.path.join(os.getcwd(), 'tests')
TESTER_NOTES_PATH = os.path.join(os.getcwd(), 'tests', 'notes_for_testing')

ZEN_TEXT_FILE = os.path.join(os.getcwd(), 'tests', 'zen.txt')

class TestNoteModel(unittest.TestCase):

    def setUp(self):
        self.notepaths = set(glob.glob(TESTER_NOTES_PATH + '/*' + NOTE_EXTENSION))
        self.db_notes = dict()
        for filepath in self.notepaths:
            filename = os.path.basename(filepath)
            if filename not in self.db_notes.keys():
                note = NoteModel(filepath)
                self.db_notes[note.filename] = note

    def test_add_remove(self):
        filepath = os.path.join(TESTER_NOTES_PATH, 'zen' + NOTE_EXTENSION)
        zen_note = NoteModel(filepath)

        # file doesn't exist yet
        self.assertFalse(os.path.exists(filepath))
        self.assertEqual(zen_note.content, '')
        self.assertEqual(zen_note.timestamp, -1)
        self.assertEqual(zen_note.metadata, dict())
        self.assertEqual(zen_note.history, list())
        self.assertEqual(zen_note.wordset, '')
        self.assertFalse(zen_note.recorded)
        self.assertFalse(zen_note.pinned)

        # add content
        content = NoteModel.enc_read(ZEN_TEXT_FILE)
        zen_note.content = content
        self.assertTrue(os.path.exists(filepath))
        self.assertNotEqual(zen_note.metadata, dict())
        self.assertNotEqual(zen_note.timestamp, -1)

        # remove note
        zen_note.remove()
        self.assertFalse(os.path.exists(filepath))
        self.assertEqual(zen_note.content, '')
        self.assertEqual(zen_note.timestamp, -1)
        self.assertEqual(zen_note.metadata, dict())
        self.assertEqual(zen_note.history, list())
        self.assertEqual(zen_note.wordset, '')
        self.assertFalse(zen_note.recorded)
        self.assertFalse(zen_note.pinned)

    def test_add_rename(self):
        filepath = os.path.join(TESTER_NOTES_PATH, 'zen' + NOTE_EXTENSION)
        zen_note = NoteModel(filepath)

        # add content
        content = NoteModel.enc_read(ZEN_TEXT_FILE)
        zen_note.content = content
        self.assertTrue(os.path.exists(filepath))
        self.assertNotEqual(zen_note.metadata, dict())
        self.assertNotEqual(zen_note.timestamp, -1)

        # rename
        filepath2 = os.path.join(TESTER_NOTES_PATH, 'zen2' + NOTE_EXTENSION)
        zen_note.notename = 'zen2'
        self.assertTrue(os.path.exists(filepath2))
        self.assertEqual(zen_note.notename, 'zen2')

    def test_add_record(self):
        filepath = os.path.join(TESTER_NOTES_PATH, 'zen' + NOTE_EXTENSION)
        zen_note = NoteModel(filepath)

        # add content
        content = NoteModel.enc_read(ZEN_TEXT_FILE)
        zen_note.content = content

        # record
        self.assertFalse(os.path.exists(zen_note.historypath))
        self.assertEqual(zen_note.load_old_note(0), (None, None))
        zen_note.record(TESTER_NOTES_PATH)
        self.assertTrue(os.path.exists(zen_note.historypath))
        self.assertNotEqual(zen_note.history, list())
        self.assertNotEqual(zen_note.load_old_note(0), (None, None))

    def test_get_changed_content(self):
        notename = self.db_notes.keys()[0]
        note = self.db_notes[notename]
        filepath = note.filepath

        # Read data from file, not using NoteModel
        raw_data = NoteModel.enc_read(filepath)
        content, metadata = NoteModel.parse_note_content(raw_data)
        timestamp = os.stat(filepath).st_mtime

        self.assertEqual(note.content, content)
        self.assertEqual(note.timestamp, timestamp)

        # Make a change
        new_content = content + '\nNew line\n'
        self.assertNotEqual(note.content, new_content)

        # Write changed data not from NoteModel
        filedata = new_content + END_OF_TEXT + '\n'
        for key, value in metadata.items():
            filedata = filedata + '{0}:{1}\n'.format(key, value)
        NoteModel.enc_write(filepath, filedata)

        # Change happened?
        self.assertNotEqual(note.timestamp, timestamp)

        # And the content automatically updates when accessed
        self.assertEqual(note.content, new_content)

        # Reset file
        filedata = content + END_OF_TEXT + '\n'
        for key, value in metadata.items():
            filedata = filedata + '{0}:{1}\n'.format(key, value)
        NoteModel.enc_write(filepath, filedata)

    def tearDown(self):
        # Clear out any vestiges of the zen files
        zenpaths = glob.glob(TESTER_NOTES_PATH + '/zen*' + NOTE_EXTENSION)
        for zen in zenpaths:
            os.remove(zen)
        # Remove the archive folder
        if os.path.exists(os.path.join(TESTER_NOTES_PATH, HISTORY_FOLDER)):
            shutil.rmtree(os.path.join(TESTER_NOTES_PATH, HISTORY_FOLDER))

if __name__ == '__main__':
    unittest.main()


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:left="-2dp" android:top="-2dp" android:right="-2dp" android:bottom="-4dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/transparent" />
            <stroke android:width="2dp" android:color="@color/news_image_corner_bl" />
            <padding android:left="-2dp" android:top="-2dp" android:right="-2dp" android:bottom="-4dp" />
            <corners android:radius="3dp" />
        </shape>
    </item>
</layer-list>


text:
using System;
using System.IO;
using System.Linq;
using System.Threading;
using Rhino.DistributedHashTable.Client;
using Rhino.DistributedHashTable.Hosting;
using Xunit;

namespace Rhino.DistributedHashTable.ClusterTests
{
	public class DistributedHashTableMasterHostTest
	{
		public class AfterRestart : FullIntegrationTest , IDisposable
		{
			readonly DistributedHashTableMasterHost host;
			private readonly Uri masterUri = new Uri("rhino.dht://" + Environment.MachineName + ":2200/master");

			public AfterRestart()
			{
				host = new DistributedHashTableMasterHost();

				host.Start();

				using (var storageHost = new DistributedHashTableStorageHost(masterUri))
				{
					storageHost.Start();

					var masterProxy = new DistributedHashTableMasterClient(masterUri);
					while(true)
					{
						var topology = masterProxy.GetTopology();
						if (topology.Segments.All(x => x.AssignedEndpoint != null))
							break;
						Thread.Sleep(100);
					}
				}

				//restart
				host.Dispose();
				host = new DistributedHashTableMasterHost();
				host.Start();
			}

			[Fact]
			public void ShouldRetainPreviousTopology()
			{
				var masterProxy = new DistributedHashTableMasterClient(masterUri);
				var topology = masterProxy.GetTopology();
				Assert.True(topology.Segments.All(x => x.AssignedEndpoint != null));
			}

			public void Dispose()
			{
				host.Dispose();
			}
		}
	}
}


text:
<?php

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Construction\UnserializeObjectConstructor;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\VisitorInterface;

class InitializedBlogPostConstructor extends UnserializeObjectConstructor
{
    public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
    {
        if ($type['name'] !== 'JMS\Serializer\Tests\Fixtures\BlogPost') {
            return parent::construct($visitor, $metadata, $data, $type);
        }

        return new BlogPost('This is a nice title.', new Author('Foo Bar'), new \DateTime('2011-07-30 00:00', new \DateTimeZone('UTC')), new Publisher('Bar Foo'));
    }
}


text:
var _               = require('lodash');
var express         = require('express');
var i18next         = require('i18next');
var ejs             = require('ejs');

module.exports = function ServerSetup( caminio, app ){

  caminio.hooks.invoke('before-setup');

  app.use( express.cookieParser(caminio.config.session.secret) );

  app.use( express.json() );
  app.use( express.urlencoded() );

  app.use( i18next.handle );
  i18next.registerAppHelper( app );

  require('./session')( caminio, app );
  require('./flash')( caminio, app );

  // use jsonp callbacks
  app.set('jsonp callback', true);

  // default view engine to interpret html files
  app.engine( 'html', ejs.__express );

  // disable express powered-by in response headers
  app.disable('x-powered-by');

  // set up all viewEngines defined in
  // config/view_engines.js
  _.each( caminio.config.viewEngines, function( engineConfig, name ){
    caminio.logger.debug('registering view engine', name);
    _.each( engineConfig.ext, function( ext ){
      if( engineConfig.engine )
        app.engine( ext, engineConfig.engine );
      if( engineConfig.default && _.contains(engineConfig.ext, engineConfig.default) )
        app.set('view engine', engineConfig.default);
    });
  });

  //app.use( express.favicon() );

  if( caminio.env === 'production' )
    app.use( express.static( caminio.config.root+'/public' ) );
  else{
    caminio.views.publicPaths.forEach( function( publicPath ){
      // console.log('setting up public path', publicPath);
      app.use( express.static( publicPath ) );
    });
  }

  //app.use( express.static( caminio.config.root+'/public' ) );

  // method override for
  // delete/put methods
  app.use( express.methodOverride() );

  caminio.hooks.invoke('before-router');

  app.use( app.router );

  setupErrorPages();

  if( caminio.env === 'development' ){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
    app.use(express.logger('dev'));
    app.locals.pretty = true;
  }

  function setupErrorPages(){
    if( caminio.config.errors[404] )
      app.use( caminio.config.errors[404] );
  }

};


text:
package org.mockitousage.bugs;

import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import org.junit.Test;
import org.mockitoutil.TestBase;

public class ActualInvocationHasNullArgumentNPEBugTest extends TestBase {

    public interface Fun {
        String doFun(String something);
    }

    @Test
    public void shouldAllowPassingNullArgument() {
        //given
        Fun mockFun = mock(Fun.class);
        when(mockFun.doFun((String) anyObject())).thenReturn("value");

        //when
        mockFun.doFun(null);

        //then
        try {
            verify(mockFun).doFun("hello");
            fail();
        } catch(AssertionError r) {
            //it's ok, we just want to reproduce the bug
        }
    }
}


text:
<?php

$dir = '/';

if (isset($_GET['dir'])) {
	$dir = $_GET['dir'];
}

OCP\JSON::checkLoggedIn();
\OC::$session->close();

// send back json
OCP\JSON::success(array('data' => \OCA\Files\Helper::buildFileStorageStatistics($dir)));


text:
xmlparser
=========

Yet Another XML Parser. (just for "fun". ahem)


text:
<?php
namespace CassandraPHP\Response;

class Exception extends \CassandraPHP\Exception {}


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ElaporanPelaksanaanKekurangan;

/**
 * ElaporanPelaksanaanKekuranganSearch represents the model behind the search form about `app\models\ElaporanPelaksanaanKekurangan`.
 */
class ElaporanPelaksanaanKekuranganSearch extends ElaporanPelaksanaanKekurangan
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['elaporan_pelaksanaan_kekurangan_id', 'elaporan_pelaksaan_id', 'created_by', 'updated_by'], 'integer'],
            [['kekurangan', 'session_id', 'created', 'updated'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ElaporanPelaksanaanKekurangan::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'elaporan_pelaksanaan_kekurangan_id' => $this->elaporan_pelaksanaan_kekurangan_id,
            'elaporan_pelaksaan_id' => $this->elaporan_pelaksaan_id,
            'created_by' => $this->created_by,
            'updated_by' => $this->updated_by,
            'created' => $this->created,
            'updated' => $this->updated,
        ]);

        $query->andFilterWhere(['like', 'kekurangan', $this->kekurangan])
            ->andFilterWhere(['like', 'session_id', $this->session_id]);

        return $dataProvider;
    }
}


text:
/*
	Known Issues & Limitations:
		- Custom non-standard (non-CU & non-SP) versions are not targeted yet
*/

declare @SQLServerVersion nvarchar(128) = cast(SERVERPROPERTY('ProductVersion') as NVARCHAR(128)),
		@SQLServerEdition nvarchar(128) = cast(SERVERPROPERTY('Edition') as NVARCHAR(128));
declare @errorMessage nvarchar(512);

 --Ensure that we are running SQL Server 2016
if substring(@SQLServerVersion,1,CHARINDEX('.',@SQLServerVersion)-1) <> N'13'
begin
	set @errorMessage = (N'You are not running a SQL Server 2016. Your SQL Server version is ' + @SQLServerVersion);
	Throw 51000, @errorMessage, 1;
end

if SERVERPROPERTY('EngineEdition') <> 3
begin
	set @errorMessage = (N'Your SQL Server 2016 Edition is not an Enterprise or a Developer Edition: Your are running a ' + @SQLServerEdition);
	Throw 51000, @errorMessage, 1;
end

--------------------------------------------------------------------------------------------------------------------
if NOT EXISTS (select * from sys.objects where type = 'p' and name = 'memopt_GetSQLInfo' and schema_id = SCHEMA_ID('dbo') )
	exec ('create procedure dbo.memopt_GetSQLInfo as select 1');
GO

/*
	Memory Optimised Scripts Library for SQL Server 2016:
	SQL Server Instance Information - Provides with the list of the known SQL Server versions that have bugfixes or improvements over your current version + lists currently enabled trace flags on the instance & session
	Version: 0.2.0, November 2016
*/
alter procedure dbo.memopt_GetSQLInfo(
-- Params --
	@showUnrecognizedTraceFlags bit = 1,		-- Enables showing active trace flags, even if they are not columnstore indexes related
	@identifyCurrentVersion bit = 1,			-- Enables identification of the currently used SQL Server Instance version
	@showNewerVersions bit = 0					-- Enables showing the SQL Server versions that are posterior the current version
-- end of --
) as
begin
	set nocount on;

	--------------------------------------------------------------------------------------------------------------------
	declare @SQLServerVersion nvarchar(128) = cast(SERVERPROPERTY('ProductVersion') as NVARCHAR(128)),
			@SQLServerEdition nvarchar(128) = cast(SERVERPROPERTY('Edition') as NVARCHAR(128)),
			@SQLServerBuild smallint = NULL;
	declare @errorMessage nvarchar(512);

	--------------------------------------------------------------------------------------------------------------------
	set @SQLServerBuild = substring(@SQLServerVersion,CHARINDEX('.',@SQLServerVersion,5)+1,CHARINDEX('.',@SQLServerVersion,8)-CHARINDEX('.',@SQLServerVersion,5)-1);

	if OBJECT_ID('tempdb..#SQLMemOptImprovements', 'U') IS NOT NULL
		drop table #SQLMemOptImprovements;
	if OBJECT_ID('tempdb..#SQLBranches', 'U') IS NOT NULL
		drop table #SQLBranches;
	if OBJECT_ID('tempdb..#SQLVersions', 'U') IS NOT NULL
		drop table #SQLVersions;

	-- Returns tables suggested for using Columnstore Indexes for the DataWarehouse environments
	create table #SQLMemOptImprovements(
		BuildVersion smallint not null,
		SQLBranch char(3) not null,
		Description nvarchar(500) not null,
		URL nvarchar(1000)
	);

	create table #SQLBranches(
		SQLBranch char(3) not null Primary Key,
		MinVersion smallint not null );

	create table #SQLVersions(
		SQLBranch char(3) not null,
		SQLVersion smallint not null Primary Key,
		ReleaseDate datetime not null,
		SQLVersionDescription nvarchar(100) );

	insert into #SQLBranches (SQLBranch, MinVersion)
		values ('CTP', 200 ), ( 'RC0', 1100 ), ( 'RC1', 1200 ), ( 'RC2', 1300 ), ( 'RC3', 1400 ), ( 'RTM', 1601 );

	insert #SQLVersions( SQLBranch, SQLVersion, ReleaseDate, SQLVersionDescription )
		values
		( 'CTP', 200, convert(datetime,'27-05-2015',105), 'CTP 2 for SQL Server 2016' ),
		( 'CTP', 300, convert(datetime,'24-06-2015',105), 'CTP 2.1 for SQL Server 2016' ),
		( 'CTP', 400, convert(datetime,'23-07-2015',105), 'CTP 2.2 for SQL Server 2016' ),
		( 'CTP', 500, convert(datetime,'28-08-2015',105), 'CTP 2.3 for SQL Server 2016' ),
		( 'CTP', 600, convert(datetime,'30-09-2015',105), 'CTP 2.4 for SQL Server 2016' ),
		( 'CTP', 700, convert(datetime,'28-10-2015',105), 'CTP 3 for SQL Server 2016' ),
		( 'CTP', 800, convert(datetime,'30-11-2015',105), 'CTP 3.1 for SQL Server 2016' ),
		( 'CTP', 900, convert(datetime,'16-12-2015',105), 'CTP 3.2 for SQL Server 2016' ),
		( 'CTP', 1000, convert(datetime,'03-02-2016',105), 'CTP 3.3 for SQL Server 2016' ),
		( 'RC0', 1100, convert(datetime,'07-03-2016',105), 'RC 0 for SQL Server 2016' ),
		( 'RC1', 1200, convert(datetime,'16-03-2016',105), 'RC 1 for SQL Server 2016' ),
		( 'RC2', 1300, convert(datetime,'01-04-2016',105), 'RC 2 for SQL Server 2016' ),
		( 'RC3', 1400, convert(datetime,'15-04-2016',105), 'RC 3 for SQL Server 2016' ),
		( 'RTM', 1601, convert(datetime,'01-06-2016',105), 'RTM for SQL Server 2016' ),
		( 'RTM', 2149, convert(datetime,'25-07-2016',105), 'CU 1 for SQL Server 2016' ),
		( 'RTM', 2164, convert(datetime,'22-09-2016',105), 'CU 2 for SQL Server 2016' ),
		( 'RTM', 2169, convert(datetime,'26-10-2016',105), 'On-Demand fix for CU 2 for SQL Server 2016' ),
		( 'RTM', 2170, convert(datetime,'01-11-2016',105), 'On-Demand fix for CU 2 for SQL Server 2016' );

	insert into #SQLMemOptImprovements (BuildVersion, SQLBranch, Description, URL )
		values
		( 2149, 'RTM', 'Creating or updating statistics takes a long time on a large memory-optimized table in SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3170996' ),
		( 2149, 'RTM', 'A deadlock condition occurs when you make updates on a memory-optimized temporal table and you run the SWITCH PARTITION statement on a history table in SQL Server 2016 ', 'https://support.microsoft.com/en-us/kb/3174712' ),
		( 2149, 'RTM', 'FIX: Secondary replica in "not healthy" state after you upgrade the primary database in SQL Server 2016 ', 'https://support.microsoft.com/en-us/kb/31718630' ),
		( 2149, 'RTM', 'FIX: Checkpoint files are missing from sys.dm_db_xtp_checkpoint_files on SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3173975' ),
		( 2149, 'RTM', 'SQL Server 2016 database log restore fails with the "Hk Recovery LSN is not NullLSN" error message', 'https://support.microsoft.com/en-us/kb/3171002' ),
		( 2149, 'RTM', 'FIX: Data loss when you alter column operation on a large memory-optimized table in SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3174963' ),
		( 2149, 'RTM', 'FIX: Large disk checkpoint usage occurs for an In-Memory optimized filegroup during heavy non-In-Memory workloads', 'https://support.microsoft.com/en-us/kb/3147012' ),
		( 2149, 'RTM', 'FIX: Slow database recovery in SQL Server 2016 due to large log when you use In-Memory OLTP on a high-end computer', 'https://support.microsoft.com/en-us/kb/3171001' ),
		( 2149, 'RTM', 'Data Flush Tasks of a memory-optimized temporal table may consume 100-percent CPU usage in SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3174713' ),
		( 2149, 'RTM', 'FIX: Error 5120 when you create or use a FILESTREAM-enabled database on a dynamic disk in an instance of SQL Server 2014 or 2016', 'https://support.microsoft.com/en-us/kb/3152377' ),
		( 2149, 'RTM', 'FIX: Fatal Error when you run a query against the sys.sysindexes view in SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3173976' ),
		( 2149, 'RTM', 'Data loss or incorrect results occur when you use the sp_settriggerorder stored procedure in SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3173004' ),
		( 2149, 'RTM', 'A data flush task may cause a deadlock condition when queries are executed on a memory-optimized table in SQL Server 2016', 'https://support.microsoft.com/en-us/kb/3173004' );

	if @identifyCurrentVersion = 1
	begin
		if OBJECT_ID('tempdb..#TempVersionResults') IS NOT NULL
			drop table #TempVersionResults;

		create table #TempVersionResults(
			MessageText nvarchar(512) NOT NULL,
			SQLVersionDescription nvarchar(200) NOT NULL,
			SQLBranch char(3) not null,
			SQLVersion smallint NULL );

		-- Identify the number of days that has passed since the installed release
		declare @daysSinceLastRelease int = NULL;
		select @daysSinceLastRelease = datediff(dd,max(ReleaseDate),getdate())
			from #SQLVersions
			where SQLBranch = ServerProperty('ProductLevel')
				and SQLVersion = cast(@SQLServerBuild as int);

		-- Display the current information about this SQL Server
		if( exists (select 1
						from #SQLVersions
						where SQLVersion = cast(@SQLServerBuild as int) ) )
			select 'You are Running:' as MessageText, SQLVersionDescription, SQLBranch, SQLVersion as BuildVersion, 'Your version is ' + cast(@daysSinceLastRelease as varchar(3)) + ' days old' as DaysSinceRelease
				from #SQLVersions
				where SQLVersion = cast(@SQLServerBuild as int);
		else
			select 'You are Running a Non RTM/SP/CU standard version:' as MessageText, '-' as SQLVersionDescription,
				ServerProperty('ProductLevel') as SQLBranch, @SQLServerBuild as SQLVersion, 'Your version is ' + cast(@daysSinceLastRelease as varchar(3)) + ' days old' as DaysSinceRelease;

		-- Select information about all newer SQL Server versions that are known
		if @showNewerVersions = 1
		begin
			insert into #TempVersionResults
				select 'Available Newer Versions:' as MessageText, '' as SQLVersionDescription,
					'' as SQLBranch, NULL as BuildVersion
				UNION ALL
				select '' as MessageText, SQLVersionDescription as SQLVersionDescription,
						SQLBranch as SQLVersionDescription, SQLVersion as BuildVersion
						from #SQLVersions
						where  @SQLServerBuild <  SQLVersion;

			select *
				from #TempVersionResults;
		end

		drop table #TempVersionResults;
	end

	select min(imps.BuildVersion) as BuildVersion, min(vers.SQLVersionDescription) as SQLVersionDescription, imps.Description, imps.URL
		from #SQLMemOptImprovements imps
			inner join #SQLBranches branch
				on imps.SQLBranch = branch.SQLBranch
			inner join #SQLVersions vers
				on imps.BuildVersion = vers.SQLVersion
		where BuildVersion > @SQLServerBuild
			and branch.SQLBranch >= ServerProperty('ProductLevel')
			and branch.MinVersion < BuildVersion
		group by Description, URL, SQLVersionDescription
		having min(imps.BuildVersion) = (select min(imps2.BuildVersion)	from #SQLMemOptImprovements imps2 where imps.Description = imps2.Description and imps2.BuildVersion > @SQLServerBuild group by imps2.Description)
		order by BuildVersion;

	drop table if exists #SQLMemOptImprovements;
	drop table if exists #SQLBranches;
	drop table if exists #SQLVersions;
	drop table if exists #ActiveTraceFlags;
	drop table if exists #ColumnstoreTraceFlags;

	--------------------------------------------------------------------------------------------------------------------
	-- Trace Flags part
	create table #ActiveTraceFlags(
		TraceFlag nvarchar(20) not null,
		Status bit not null,
		Global bit not null,
		Session bit not null );

	insert into #ActiveTraceFlags
		exec sp_executesql N'DBCC TRACESTATUS()';

	create table #ColumnstoreTraceFlags(
		TraceFlag int not null,
		Description nvarchar(500) not null,
		URL nvarchar(600),
		SupportedStatus bit not null
	);

	insert into #ColumnstoreTraceFlags (TraceFlag, Description, URL, SupportedStatus )
		values
		( 1851, 'Disables automerge for CFP', '', 0 ),
		( 9989, 'Enables Reading In-Memory Tables on the secondary replicas of AlwaysOn Availability Groups', 'https://connect.microsoft.com/SQLServer/feedback/details/795360/secondary-db-gets-suspect-when-i-add-in-memory-table-to-db-which-is-part-of-alwayson-availability-group', 0 ),
		( 9851, 'Disables automated merge process', '', 0 ),
		( 9837, 'Enables extra-tracing informations for the checkpoint files', '', 0 ),
		( 9926, 'Removes the limit on the number of transactions that can depend on a given transaction', '', 0 ),
		( 9912, 'Disables large checkpoints', 'https://beanalytics.wordpress.com/2016/05/20/logging-and-checkpoint-process-for-memory-optimized-tables-in-sql-2016/', 0 );

	select tf.TraceFlag, isnull(conf.Description,'Unrecognized') as Description, isnull(conf.URL,'-') as URL, SupportedStatus
		from #ActiveTraceFlags tf
			left join #ColumnstoreTraceFlags conf
				on conf.TraceFlag = tf.TraceFlag
		where @showUnrecognizedTraceFlags = 1 or (@showUnrecognizedTraceFlags = 0 AND Description is not null);

	drop table if exists #ColumnstoreTraceFlags;
	drop table if exists #ActiveTraceFlags;

END

GO


text:
<template name="Footer">

        Made By Dan Li

        For ICS 314 Final Project Mockup

</template>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.analytics.synapse.artifacts.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.List;

/** Trigger that runs every time the selected Blob container changes. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonTypeName("BlobTrigger")
@JsonFlatten
@Fluent
public class BlobTrigger extends MultiplePipelineTrigger {
    /*
     * The path of the container/folder that will trigger the pipeline.
     */
    @JsonProperty(value = "typeProperties.folderPath", required = true)
    private String folderPath;

    /*
     * The max number of parallel files to handle when it is triggered.
     */
    @JsonProperty(value = "typeProperties.maxConcurrency", required = true)
    private int maxConcurrency;

    /*
     * The Azure Storage linked service reference.
     */
    @JsonProperty(value = "typeProperties.linkedService", required = true)
    private LinkedServiceReference linkedService;

    /**
     * Get the folderPath property: The path of the container/folder that will trigger the pipeline.
     *
     * @return the folderPath value.
     */
    public String getFolderPath() {
        return this.folderPath;
    }

    /**
     * Set the folderPath property: The path of the container/folder that will trigger the pipeline.
     *
     * @param folderPath the folderPath value to set.
     * @return the BlobTrigger object itself.
     */
    public BlobTrigger setFolderPath(String folderPath) {
        this.folderPath = folderPath;
        return this;
    }

    /**
     * Get the maxConcurrency property: The max number of parallel files to handle when it is triggered.
     *
     * @return the maxConcurrency value.
     */
    public int getMaxConcurrency() {
        return this.maxConcurrency;
    }

    /**
     * Set the maxConcurrency property: The max number of parallel files to handle when it is triggered.
     *
     * @param maxConcurrency the maxConcurrency value to set.
     * @return the BlobTrigger object itself.
     */
    public BlobTrigger setMaxConcurrency(int maxConcurrency) {
        this.maxConcurrency = maxConcurrency;
        return this;
    }

    /**
     * Get the linkedService property: The Azure Storage linked service reference.
     *
     * @return the linkedService value.
     */
    public LinkedServiceReference getLinkedService() {
        return this.linkedService;
    }

    /**
     * Set the linkedService property: The Azure Storage linked service reference.
     *
     * @param linkedService the linkedService value to set.
     * @return the BlobTrigger object itself.
     */
    public BlobTrigger setLinkedService(LinkedServiceReference linkedService) {
        this.linkedService = linkedService;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public BlobTrigger setPipelines(List<TriggerPipelineReference> pipelines) {
        super.setPipelines(pipelines);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public BlobTrigger setDescription(String description) {
        super.setDescription(description);
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public BlobTrigger setAnnotations(List<Object> annotations) {
        super.setAnnotations(annotations);
        return this;
    }
}


text:
const ko = require('knockout')
const htmlencode = require('htmlencode')
const ListingBaseViewModel = require('../ListingBaseViewModel')

const Model = function () {
  const self = this
  self.nameToFilterOn = ko.observable()

  self.mapItems = (i) => {
    return {
      id: ko.observable(i.id),
      editUrl: ko.observable(`edit?id=${i.id}`),
      name: ko.observable(htmlencode.htmlDecode(i.name)),
      tags: ko.observable(i.tags)
    }
  }
  self.filters = [
    { key: 'searchTerm', setValue: (vm, value) => vm.nameToFilterOn(value), getValue: (vm) => { return vm.nameToFilterOn() ? vm.nameToFilterOn().trim() : vm.nameToFilterOn() }, isSet: (val) => val !== undefined && val.length > 0 }
  ]
  self.baseUrl = self.endpointBuilder.parentScenarios().build() + '/list'

  self.init(self)
}

Model.prototype = new ListingBaseViewModel()

module.exports = Model


text:
using boost::asio::ip::tcp;

// Compiler warning can be ignored: ('this' : used in base member initializer list).
MazeServer::MazeServer(boost::asio::io_service & io_service, const tcp::endpoint & endpoint) :
	io_service_(io_service), acceptor_(io_service, endpoint), maze_mgr_(*this)
{
	startAccept();
}

void MazeServer::startAccept()
{
	int pos = findFreeSessionPos();
	size_t id = static_cast<size_t>(pos + 1);
	if (pos < 0)
		id = sessions_.size() + 1;

	maze_session_ptr newSession(new MazeSession(io_service_, static_cast<uint32_t>(id), maze_mgr_));
	if (pos < 0)
		sessions_.push_back(newSession);
	else
		sessions_[pos] = newSession;

	acceptor_.async_accept(newSession->socket(),
		boost::bind(&MazeServer::handleAccept, this, newSession,
			boost::asio::placeholders::error));
}

void MazeServer::handleAccept(maze_session_ptr session, const boost::system::error_code & error)
{
	if (!error)
	{
		session->start();
		std::cout << "Session established for Player " << session->getPlayerId() << "." << std::endl;
	}
	else
	{
		std::cerr << "ERROR: MazeServer::handleAccept [" << error.value() << ": " << error.message() << "]" << std::endl;
	}

	startAccept();
}

void MazeServer::broadcast(const GameMessage & msg)
{
	for (maze_session_weak_vec::iterator it = sessions_.begin(); it != sessions_.end(); ++it)
	{
		try
        {
            if (auto p = (*it).lock())
			{
				if (p->isStarted())
					p->write(msg);
			}
			else
			{
				std::cerr << "WARNING: MazeServer::broadcast [Weak pointer lock failure]" << std::endl;
			}
        }
        catch (const std::bad_weak_ptr &)
        {
            std::cerr << "WARNING: MazeServer::broadcast [Ignoring bad weak pointer]" << std::endl;
        }
	}
}

int MazeServer::findFreeSessionPos() const
{
	for (size_t i = 0; i < sessions_.size(); ++i)
	{
		if (sessions_[i].expired())
			return static_cast<int>(i);
	}
	return -1;
}

int main(int argc, char * argv[])
{
	try
	{
		if (argc != 2)
		{
			std::cerr << "Usage: MazeServer <port>" << std::endl;
			return 1;
		}

		boost::asio::io_service io_service;
		tcp::endpoint endpoint(tcp::v4(), atoi(argv[1]));
		MazeServer server(io_service, endpoint);
		io_service.run();
	}
	catch (std::runtime_error & e)
	{
		std::cerr << "Exception: " << e.what() << std::endl;
		return 1;
	}

	return 0;
}


text:
.class public Landroid/net/wifi/WifiScanner$ScanSettings;
.super Ljava/lang/Object;
.source "WifiScanner.java"

# interfaces
.implements Landroid/os/Parcelable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/net/wifi/WifiScanner;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "ScanSettings"
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/net/wifi/WifiScanner$ScanSettings;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field public band:I

.field public channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

.field public numBssidsPerScan:I

.field public periodInMs:I

.field public reportEvents:I

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 188
    new-instance v0, Landroid/net/wifi/WifiScanner$ScanSettings$1;

    invoke-direct {v0}, Landroid/net/wifi/WifiScanner$ScanSettings$1;-><init>()V

    sput-object v0, Landroid/net/wifi/WifiScanner$ScanSettings;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method public constructor <init>()V
    .locals 0

    .prologue
    .line 149
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public describeContents()I
    .locals 1

    .prologue
    .line 164
    const/4 v0, 0x0

    return v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 3
    .param p1, "dest"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    const/4 v2, 0x0

    .line 169
    iget v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->band:I

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 170
    iget v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->periodInMs:I

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 171
    iget v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->reportEvents:I

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 172
    iget v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->numBssidsPerScan:I

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 174
    iget-object v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

    if-eqz v1, :cond_1

    .line 175
    iget-object v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

    array-length v1, v1

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 177
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget-object v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

    array-length v1, v1

    if-ge v0, v1, :cond_2

    .line 178
    iget-object v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

    aget-object v1, v1, v0

    iget v1, v1, Landroid/net/wifi/WifiScanner$ChannelSpec;->frequency:I

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 179
    iget-object v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

    aget-object v1, v1, v0

    iget v1, v1, Landroid/net/wifi/WifiScanner$ChannelSpec;->dwellTimeMS:I

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 180
    iget-object v1, p0, Landroid/net/wifi/WifiScanner$ScanSettings;->channels:[Landroid/net/wifi/WifiScanner$ChannelSpec;

    aget-object v1, v1, v0

    iget-boolean v1, v1, Landroid/net/wifi/WifiScanner$ChannelSpec;->passive:Z

    if-eqz v1, :cond_0

    const/4 v1, 0x1

    :goto_1
    invoke-virtual {p1, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 177
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    :cond_0
    move v1, v2

    .line 180
    goto :goto_1

    .line 183
    .end local v0    # "i":I
    :cond_1
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    .line 185
    :cond_2
    return-void
.end method


text:
<?php
// Heading
$_['heading_title']      = 'Mal\'s e-commerce';

// Text
$_['text_payment']       = 'Payment';
$_['text_success']       = 'Success: You have modified Mal\'s e-commerce account details!';

// Entry
$_['entry_account']      = 'Account No.:';
$_['entry_domain']       = 'Server Domain:';
$_['entry_order_status'] = 'Order Status:';
$_['entry_geo_zone']     = 'Geo Zone:';
$_['entry_status']       = 'Status:';
$_['entry_sort_order']   = 'Sort Order:';

// Error
$_['error_permission']   = 'Warning: You do not have permission to modify payment Mal\'s e-commerce!';
$_['error_account']      = 'Account No. Required!';
$_['error_domain']       = 'Server Domain Required!';
?>


text:
/* eslint-disable max-len */
import {BitsUtil} from '../util/BitsUtil';
import {FixSizedTypesCodec} from './builtin/FixSizedTypesCodec';
import {ClientMessage, Frame, RESPONSE_BACKUP_ACKS_OFFSET, PARTITION_ID_OFFSET} from '../protocol/ClientMessage';
import {StringCodec} from './builtin/StringCodec';
import {Data} from '../serialization/Data';
import {ListMultiFrameCodec} from './builtin/ListMultiFrameCodec';
import {DataCodec} from './builtin/DataCodec';

// hex: 0x050600
const REQUEST_MESSAGE_TYPE = 329216;
// hex: 0x050601
// RESPONSE_MESSAGE_TYPE = 329217

const REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_OFFSET + BitsUtil.INT_SIZE_IN_BYTES;
const RESPONSE_RESPONSE_OFFSET = RESPONSE_BACKUP_ACKS_OFFSET + BitsUtil.BYTE_SIZE_IN_BYTES;

/** @internal */
export class ListAddAllCodec {
    static encodeRequest(name: string, valueList: Data[]): ClientMessage {
        const clientMessage = ClientMessage.createForEncode();
        clientMessage.setRetryable(false);

        const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE);
        clientMessage.addFrame(initialFrame);
        clientMessage.setMessageType(REQUEST_MESSAGE_TYPE);
        clientMessage.setPartitionId(-1);

        StringCodec.encode(clientMessage, name);
        ListMultiFrameCodec.encode(clientMessage, valueList, DataCodec.encode);
        return clientMessage;
    }

    static decodeResponse(clientMessage: ClientMessage): boolean {
        const initialFrame = clientMessage.nextFrame();

        return FixSizedTypesCodec.decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_OFFSET);
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Perso</title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<link href="https://fonts.googleapis.com/css?family=Share+Tech+Mono" rel="stylesheet">

			<button type="button" class="btn navlink" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">

			</button>

		<select class="form-control lang-select">
			<option>English</option>
			<option>French</option>
		</select>

POULAIN Kévin

Aspiring Developper

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

[Skills]

[Programmation Language]

C

C++

C#

Java

Haskell

MySQL++

PHP

[Tools]

Window 7-10

Debian

ArchLinux

Blender

Unity

Visual Studio

Vim

Git

			a


text:
'use strict';

var config = require('config');
var jwt = require('jsonwebtoken');
var ms = require('ms');

const BASE_URL = config.get('base_url');
const JWT_CONFIG = config.get('jwt');

/**
 * Abstract Store, should use subclass
 */
class Store {

    /**
     * Register store
     *
     * @param {String} name, name of the store
     * @param {Store} store, class of the store
     */
    static registerStore(name, store){
        this.stores[name] = store;
    }

    /**
     * Get registered store by name
     * @param {String} name
     * @param {Object} options, optional
     * @returns {Store} instance of store
     */
    static getStore(name, options) {
        return new this.stores[name](options);
    }

    /**
     * Save object
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @param {Stream} stream
     * @returns {Promise}
     */
    put(user, repo, oid, stream) {
        throw new Error('Can not use put from Store class');
    }

    /**
     * Download object
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @returns {Promise<Stream>}
     */
    get(user, repo, oid) {
        throw new Error('Can not use get from Store class');
    }

    /**
     * Download object
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @returns {Promise<Number>}
     */
    getSize(user, repo, oid) {
        throw new Error('Can not use getSize from Store class');
    }

    /**
     * Check object exist or not
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @returns {Promise<Boolean>}
     */
    exist(user, repo, oid) {
        return this.getSize(user, repo, oid).then(function (size) {
            return size > 0;
        });
    }

    /**
     * LFS Batch API upload action
     *
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @param {Number} size
     * @returns upload action
     */
    getUploadAction(user, repo, oid, size) {
        return {
            href: `${BASE_URL}${user}/${repo}/objects/${oid}`,
            expires_at: Store._getJWTExpireTime(),
            header: {
                'Authorization': 'JWT ' + Store._generateJWTToken('upload', user, repo, oid)
            }
        };
    }

    /**
     * LFS Batch API download action
     *
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @param {Number} size
     * @returns download action
     */
    getDownloadAction(user, repo, oid, size) {
        return {
            href: `${BASE_URL}${user}/${repo}/objects/${oid}`,
            expires_at: Store._getJWTExpireTime(),
            header: {
                'Authorization': 'JWT ' + Store._generateJWTToken('download', user, repo, oid)
            }
        };
    }

    /**
     * LFS Batch API verify action
     *
     * @param {String} user
     * @param {String} repo
     * @param {String} oid
     * @param {Number} size
     * @returns verify action
     */
    getVerifyAction(user, repo, oid, size) {
        return {
            href: `${BASE_URL}${user}/${repo}/objects/verify`,
            expires_at: Store._getJWTExpireTime(),
            header: {
                'Authorization': 'JWT ' + Store._generateJWTToken('verify', user, repo)
            }
        };
    }

    /**
     * Create JWT token
     *
     * @param {String} action, can be 'download', 'upload' or 'verify'
     * @param {String} user
     * @param {String} repo
     * @param {String} [oid], empty for verify request
     */
    static _generateJWTToken(action, user, repo, oid) {
        var signObject = {
            user: user,
            repo: repo,
            action: action
        };
        if (oid) {
            signObject.oid = oid;
        }
        return jwt.sign(signObject, JWT_CONFIG.secret, {
            algorithm: JWT_CONFIG.algorithm,
            expiresIn: JWT_CONFIG.expiresIn,
            issuer: JWT_CONFIG.issuer
        });
    }

    static _getJWTExpireTime() {
        return new Date(new Date().getTime() + ms(JWT_CONFIG.expiresIn)).toISOString();
    }
}

Store.stores = {};

module.exports = Store;

Store.registerStore('s3', require('./s3_store'));
Store.registerStore('s3_direct', require('./s3_direct_store'));
Store.registerStore('grid', require('./grid_store'));


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using work.bacome.trace;

namespace testharness2
{
    public partial class frmStart : Form
    {
        private static cTrace kTrace = new cTrace("testharness2");

        private cTrace.cContext mRootContext = kTrace.NewRoot(nameof(frmStart), true);
        private int mTimer = 7;
        private int mInstanceNumber = 7;

        public frmStart()
        {
            InitializeComponent();
        }

        private void tmrProofOfASync_Tick(object sender, EventArgs e)
        {
            mTimer++;
            lblProofOfASync.Text = mTimer.ToString();
        }

        private void cmdCreate_Click(object sender, EventArgs e)
        {
            string lInstanceName = txtInstanceName.Text.Trim();
            if (lInstanceName.Length == 0) lInstanceName = "Client_" + (++mInstanceNumber).ToString();
            var lClient = new frmClient(lInstanceName);
            Program.Centre(lClient, this);
            lClient.Show();
        }

        private void cmdTests_Click(object sender, EventArgs e)
        {
            var lContext = mRootContext.NewMethod(nameof(frmStart), nameof(cmdTests_Click));

            try
            {
                gbxTests.Enabled = false;
                cTests.Tests(false, lContext);
                MessageBox.Show(this, "all tests passed");
            }
            catch (Exception ex) { MessageBox.Show(this, ex.ToString()); }
            finally
            {
                gbxTests.Enabled = true;
            }
        }

        private void cmdQuickTests_Click(object sender, EventArgs e)
        {
            var lContext = mRootContext.NewMethod(nameof(frmStart), nameof(cmdQuickTests_Click));

            try
            {
                gbxTests.Enabled = false;
                cTests.Tests(true, lContext);
                MessageBox.Show(this, "quick tests passed");
            }
            catch (Exception ex) { MessageBox.Show(this, ex.ToString()); }
            finally
            {
                gbxTests.Enabled = true;
            }
        }

        private void cmdCurrentTest_Click(object sender, EventArgs e)
        {
            var lContext = mRootContext.NewMethod(nameof(frmStart), nameof(cmdCurrentTest_Click));

            try
            {
                gbxTests.Enabled = false;
                cTests.CurrentTest(lContext);
                MessageBox.Show(this, "current test passed");

            }
            catch (Exception ex) { MessageBox.Show(this, ex.ToString()); }
            finally
            {
                gbxTests.Enabled = true;
            }
        }
    }
}