text:
		function BuildMainView()
		{
			/*
			Create a new View - LILO View is an entire screen and all it contains,
			they can be switched between, animated and transitioned
			*/
			var view = Lilo.Engine.CreateView("MainView");

			/*
			A panel can be used purely as a design element or as a container for other controls.
			A panel can allow other controls to overlap it, be clipped by it and allows for relative or absolute positioning.
			*/
		    var panel = new Lilo.Panel("centerPanel", {
				x: 0, y: 0, z: 1, position: Lilo.POSITION_ABSOLUTE, radius: 15, opacity: 1.0, isVisible: true, background: "rgba(78,85,91,1.0)", clipped: true, hideoverflow: true,
				stroke: true, strokecolor: "rgba(125,124,13,1.0)", strokewidth: 12.5,
				style: function () {
					this.x = (Lilo.SCREEN_WIDTH/2) - (this.width/2);
					this.y = (Lilo.SCREEN_HEIGHT/2) - (this.height/2);
					this.width  = Lilo.SCREEN_WIDTH * 0.7;
					this.height = Lilo.SCREEN_HEIGHT * 0.7;
				},
				animate : function() {
					this.x = Math.sin( Lilo.Engine.frameNumber/150 ) * Lilo.SCREEN_WIDTH*0.25 + (Lilo.SCREEN_WIDTH/2) - (this.width/2);
				}
			});

			/*
			An animated image control.
			*/
			var logo = new Lilo.Image("logo", "texture.png", {
				opacity: 1.0, radius: 0.0, position: Lilo.POSITION_ABSOLUTE, z: 2,
				style: function () {
					x = 0;
					y = 0;
					this.width = Lilo.SCREEN_WIDTH/2;
					this.height = Lilo.SCREEN_HEIGHT/2; // this.width * this.aspect; If you want aspect correct images.
				},
				animate : function () {
					this.rotation += 0.1;
				},
				drag : function () {
					var pointer = Lilo.Engine.GetPointer();
					this.x = pointer.x - (this.width*0.5);
					this.y = pointer.y - (this.height*0.5);
				},
				wheel : function(d) {
					if(d>0)
						this.scale += 0.1;
					else
						this.scale -= 0.1;

					this.scale = Math.max( this.scale, 1 );

				}
			});

			/*
			A simple button
			*/
			var btn = new Lilo.Button("btn1", "Click Me", {
				x: 0, y: 0, z: 2, radius: 10, position: Lilo.POSITION_ABSOLUTE, background: "rgba(50,80,60,1.0)", foreground: "rgba(255,255,255,1.0)",
				fontFace: "Arial", fontSize: 28,
				style : function () {
					var pnl = Lilo.Engine.FindControlById("centerPanel");
					this.width  = Math.max( pnl.width * 0.15, 120 );
					this.height = 45;
					this.x = pnl.x + (pnl.width/2) - (this.width/2);
					this.y = pnl.y - 60;
				},
				onclick : function () {
					Lilo.Engine.DismissKeyboard();
					var userCtl = Lilo.Engine.FindControlById("usrname");
					user = userCtl.text;
				}
			});

			/*
			A label control. Labels render using standard text output, but have the option to use a hashtable based image cache which can massively
			accelerate the render of large quantities of text on mobile devices.
			*/
			var lbl1 = new Lilo.Label("lbl1", "Value : ", {
				x: 0, y: 0, z: 3, position: Lilo.POSITION_RELATIVE, radius: 0, opacity: 1.0,
				foreground: "rgba(255,255,255,1.0)", fontFace: "Arial", fontSize: 28, textAlign: 'center',
				style: function () {
					this.height = 30;
					var pnl = Lilo.Engine.FindControlById("centerPanel");
					this.width = pnl.width * 0.25;
					this.y = pnl.height/2 - 15;
					this.x = pnl.width/2 - this.width/2;
					this.fontSize = Lilo.Engine.GetResolutionFontSize(28, 2048);
					this.text = "Value : " + globalValue.toFixed(2) + " -> " + user;
				}
			});

			/*
			A value +/- control.
			*/
			var value1 = new Lilo.ValueChange("valueCtrl", {
				x: 0, y: 0, width: 180, height: 50, z: 4, position: Lilo.POSITION_RELATIVE, radius: 5, foreground: "rgba(248,151,29,1.0)",
				fontFace: "Verdana", fontSize: "20", fontWeight: "bold",
				style: function () {
					var lbl = Lilo.Engine.FindControlById("lbl1");
					this.height = 30;
					this.width = 100;
					this.y = lbl.y + lbl.height + 10;
					this.x = lbl.x + lbl.width/2 - (this.width/2);
				},
				onValueDown: function () {
					globalValue -= 0.1;
				},
				onValueUp: function () {
					globalValue += 0.1;
				}
			});

			/*
			A standard, styled text input. All form style inputs support tabindex.
			*/
			var UserText = new Lilo.TextBox("usrname", "Username", {
				x: 0, y: 0, z: 7, width: 500, height: 60, position: Lilo.POSITION_RELATIVE,
				foreground: "rgba(50,50,50,1.0)", background: "rgba(255,255,255,1.0)", radius: 10, opacity: 1.0,
				fontFace: "Verdana", fontSize: 30, tabindex: 1, maxlength: 100,
				style: function () {
					this.width = Lilo.SCREEN_WIDTH * 0.30;
					this.height = Lilo.SCREEN_HEIGHT * 0.05;
					this.x = (this.container.width / 2) - (this.width / 2);		// All controls can reference their own properties via this, it's container via this.container, or any other control via FindControlById.
					this.y = (this.container.height / 3) + (this.height / 2);
					if (this.text == "Username") {
						this.foreground = "rgba(153,153,153,1.0)";
						this.fontWeight = 'bold';
					} else {
						this.foreground = "rgba(50,50,50,1.0)";
						this.fontWeight = '';
					}
				}
			});

			panel.Add( logo );
			panel.Add( lbl1 );
			panel.Add( value1 );
			panel.Add( UserText );
			view.Add( panel );
			view.Add( btn );
			return( view );
		}


text:
<?php

namespace Raml\SecurityScheme\SecuritySettingsParser;

use Raml\SecurityScheme\SecuritySettings\OAuth2SecuritySettings;
use Raml\SecurityScheme\SecuritySettingsParserInterface;

class OAuth2SecuritySettingsParser implements SecuritySettingsParserInterface
{

    // ---
    // SecuritySettingsParserInterface

    /**
     * Create a new OAuth2 Security Settings Object from array data
     *
     * @param array $data
     * [
     *  authorizationUri:       ?string
     *  accessTokenUri:         ?string
     *  authorizationGrants:    ?string[]
     *  scopes:                 ?string[]
     * ]
     *
     * @return OAuth2SecuritySettings
     */
    public function createSecuritySettings(array $data = [])
    {
        return OAuth2SecuritySettings::createFromArray($data);
    }

    /**
     * Get a list of supported types
     *
     * @return array
     */
    public function getCompatibleTypes()
    {
        return [OAuth2SecuritySettings::TYPE];
    }
}

redpajama_set_name: RedPajamaGithub


text:
*__Note:__ This changelog is in development, and is updated alongside the project. It should by no means be considered final.*

**Overview:**
Huge improvements to all aspects of the site.

**Changelog:**
 * Added a Pages app that handles any static pages.
    * Merged Frontpage app into Pages app
    * Merged shared files into Pages app
 * Changed the way that Push Messages are handled internally.
 * Changed the way that Modals are handled internally.
 * Created a new script: messenger.js
 * Migrated all of the content that is messenger specific from base.js to messenger.js
 * Added Browser Push Notifications (note: These are different from Push Messages)
 * Temporarily disabled PJAX
 * Redesigned Messenger Interface
 * Redesigned Frontpage
 * Greatly improved docs
    * Updated Docs frontpage
    * Articles are now sorted into four categories:
        * News (NE)
        * Support (SU)
        * Developer Documentation (DO)
        * Community Submissions (CO)
    * Added custom themes for each category.
    * Users with permission can now create articles.


text:
'use strict';

var assert = require('assert');
var TokenStream = require('../');

assert.throws(function () {
  new TokenStream('foo,bar');
});
var stream = new TokenStream([
  'a',
  'b',
  'c',
  'd'
]);
assert.throws(function () {
  stream.lookahead(9);
});
assert(stream.peek() === 'a');
assert(stream.lookahead(0) == 'a');
assert(stream.lookahead(1) == 'b');

assert(stream.advance() === 'a');
assert(stream.peek() === 'b');
assert(stream.lookahead(0) == 'b');
assert(stream.lookahead(1) == 'c');

stream.defer('z');
assert(stream.peek() === 'z');
assert(stream.lookahead(0) == 'z');
assert(stream.lookahead(1) == 'b');
assert(stream.advance() === 'z');
assert(stream.advance() === 'b');
assert(stream.advance() === 'c');
assert(stream.advance() === 'd');
assert.throws(function () {
  stream.peek();
});
assert.throws(function () {
  stream.lookahead(0);
});
assert.throws(function () {
  stream.lookahead(1);
});
assert.throws(function () {
  stream.advance();
});


text:
/*jshint plusplus:false*/

var fs     = require('fs');
var path   = require('path');
var assert = require('assert');

var complete = require('../lib/util/completion');
var config   = require('../lib/core/config');
var command  = require('../lib/commands/completion');
var commands = require('../lib/commands');

describe('completion', function () {

  before(function () {
    this.opts = complete(['bower', 'install'], {
      COMP_CWORD: '2',
      COMP_LINE: 'bower install',
      COMP_POINT: '14'
    });
  });

  beforeEach(function () {
    this.log = complete.log;
  });

  afterEach(function () {
    complete.log = this.log;
  });

  it('parses COMP_* in the env', function () {
    assert.deepEqual(this.opts, {
      w:            2,
      words:        [ 'bower', 'install' ],
      word:         'install',
      line:         'bower install',
      point:        14,
      length:       13,
      partialLine:  'bower install',
      partialWords: [ 'bower', 'install' ]
    });
  });

  it('filters out completion results', function () {
    var completed = [
      'backbone',
      'backbone-forms',
      'backbone-paginator',
      'backbone.forms',
      'backbone.paginator'
    ];

    var all = complete.abbrev({ word: 'ba' });
    var none = complete.abbrev({ word: 'foobar' });
    var form = complete.abbrev({ word: 'backbone-form' });
    var dots = complete.abbrev({ word: 'backbone.' });
    var dashed = complete.abbrev({ word: 'backbone-' });

    assert.deepEqual(completed.filter(all), completed);
    assert.deepEqual(completed.filter(none), []);
    assert.deepEqual(completed.filter(form), ['backbone-forms']);
    assert.deepEqual(completed.filter(dashed), ['backbone-forms', 'backbone-paginator']);
    assert.deepEqual(completed.filter(dots), ['backbone.forms', 'backbone.paginator']);
  });

  it('dumps the script when COMP_* aren\'t in the env', function (done) {
    command().on('end', function (data) {
      var script = fs.readFileSync(path.join(__dirname, '../templates/completion.mustache'), 'utf8');
      assert.equal(data, script);
      done();
    });
  });

  it('completes the list of command on first word', function () {
    complete.log = function (results) {
      assert.deepEqual(results, Object.keys(commands));
    };

    command([''], {
      COMP_CWORD: '1',
      COMP_LINE: 'bower ',
      COMP_POINT: '6'
    });
  });

  it('completes the list of options on first word', function () {
    complete.log = function (results) {
      assert.deepEqual(results, ['--no-color', '--help', '--version']);
    };

    command(['-'], {
      COMP_CWORD: '1',
      COMP_LINE: 'bower -',
      COMP_POINT: '7'
    });
  });

  it('completes the list of command on invalid command', function () {
    complete.log = function (results) {
      assert.deepEqual(results, Object.keys(commands));
    };

    command(['foobar'], {
      COMP_CWORD: '1',
      COMP_LINE: 'bower foobar',
      COMP_POINT: '12'
    });
  });

  it('delegates to command.completion for each bower command', function (done) {
    complete.log = function (results) {
      assert.ok(results.length);

      var jq = results.filter(function (res) {
        return res === 'jquery';
      });

      assert.equal(jq.length, 1);
    };

    var cmd = command(['install', 'jquery-'], {
      COMP_CWORD: '2',
      COMP_LINE: 'bower install jquery-',
      COMP_POINT: '14'
    });

    cmd.on('end', done);
  });

  describe('cache clean', function () {

    it('caches the result of <endpoint>/packages to the completion cache folder', function (done) {
      complete.log = function () {};

      var cmd = command(['install', 'jquery-'], {
        COMP_CWORD: '2',
        COMP_LINE: 'bower install jquery-',
        COMP_POINT: '14'
      });

      cmd.on('end', function () {
        var cache = path.join(config.completion, 'install.json');
        fs.stat(cache, done);
      });
    });

    it('is cleared with cache-clean command', function (done) {
      commands['cache-clean']().on('end', function () {
        var cache = path.join(config.completion, 'install.json');
        fs.stat(cache, function (err) {
          done(err ? null : new Error('completion results wasn\'t cleaned'));
        });
      });
    });

  });
});


text:
//-----------------------------------------------------------------------
// <copyright>
// This software is licensed as Microsoft Public License (Ms-PL).
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;

namespace Mite
{
    /// <summary>
    /// Base class of all mite connectors
    /// </summary>
    internal class DefaultWebAdapter : IWebAdapter
    {
        private static string _userAgent;

        //--------------------------------------------------------------------------
        /// <summary>
        /// Sends a HTTP get request.
        /// </summary>
        /// <param name="url">The url to which the request is send.</param>
        /// <returns>The response.</returns>
        public string SendGetRequest(string url)
        {
            Trace.Assert(!string.IsNullOrEmpty(url));
            Trace.WriteLine("Start GetRequest");

            HttpWebRequest request = CreateRequest(url);
            request.Method = "GET";

            // Get response
            using ( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string answer = reader.ReadToEnd();

                Trace.WriteLine(answer);

                Trace.WriteLine("End GetRequest");

                return answer;
            }
        }

        private static HttpWebRequest CreateRequest(string url)
        {
            string requestUrl = MiteConfiguration.CurrentConfiguration.Domain + url;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);

            if (MiteConfiguration.CurrentConfiguration.Proxy != null)
            {
                request.Proxy = MiteConfiguration.CurrentConfiguration.Proxy;
            }

            request.UserAgent = UserAgent;

            if ( !string.IsNullOrEmpty(MiteConfiguration.CurrentConfiguration.ApiKey) )
            {
                request.Headers.Add("X-MiteApiKey", MiteConfiguration.CurrentConfiguration.ApiKey);
            }
            else
            {
                request.Credentials = new NetworkCredential
                {
                    UserName = MiteConfiguration.CurrentConfiguration.User,
                    Password = MiteConfiguration.CurrentConfiguration.Password
                };
            }

            request.ContentType = "application/xml";

            return request;
        }

        protected static string UserAgent
        {
            get
            {
                if ( string.IsNullOrEmpty(_userAgent) )
                {
                    string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    string product = "mite.net";
                    string host = Environment.OSVersion.VersionString;

                    _userAgent = string.Format(CultureInfo.InvariantCulture, "{0}/{1} ({2})", product, version, host);
                }

                return _userAgent;
            }
        }

        //--------------------------------------------------------------------------
        /// <summary>
        /// Sends a HTTP post request.
        /// </summary>
        /// <param name="url">The url to which the request is send.</param>
        /// <param name="data">The data which is posted.</param>
        /// <returns>The response.</returns>
        public string SendPostRequest(string url, string data)
        {
            try
            {
                HttpWebRequest request = CreateRequest(url);
                request.Method = "POST";
                request.ContentType = "application/xml";

                byte[] byteData = Encoding.UTF8.GetBytes(data);
                request.ContentLength = byteData.Length;

                using ( Stream postStream = request.GetRequestStream() )
                {
                    postStream.Write(byteData, 0, byteData.Length);
                }

                // Get response
                using ( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
                {
                    // Get the response stream
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string res = reader.ReadToEnd();

                    Trace.WriteLine(res);

                    Trace.WriteLine("End PostRequest");

                    return res;
                }
            }
            catch ( WebException webException )
            {
                StreamReader reader = new StreamReader(webException.Response.GetResponseStream());
                string res = reader.ReadToEnd();

                throw MiteException.CreateFromResponse(res, webException);
            }
        }

        //--------------------------------------------------------------------------
        /// <summary>
        /// Sends a HTTP post request.
        /// </summary>
        /// <param name="url">The url to which the request is send.</param>
        /// <returns>The response.</returns>
        public string SendPostRequest(string url)
        {
            HttpWebRequest request = CreateRequest(url);

            request.Method = "POST";
            request.ContentLength = 0;

            // Get response
            using ( HttpWebResponse response = (HttpWebResponse) request.GetResponse() )
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string res = reader.ReadToEnd();

                Trace.WriteLine(res);

                Trace.WriteLine("End PostRequest");

                return res;
            }
        }

        //--------------------------------------------------------------------------
        /// <summary>
        /// Sends a put request.
        /// </summary>
        /// <param name="url">The url to which the request is send.</param>
        /// <param name="data">The data which is put.</param>
        /// <returns>The response.</returns>
        public string SendPutRequest(string url, string data)
        {
            byte[] byteData = Encoding.UTF8.GetBytes(data);

            HttpWebRequest request = CreateRequest(url);

            request.Method = "PUT";
            request.ContentLength = byteData.Length;

            using ( Stream putStream = request.GetRequestStream() )
            {
                putStream.Write(byteData, 0, byteData.Length);
            }

            try
            {
                // Get response
                using ( HttpWebResponse response = (HttpWebResponse) request.GetResponse() )
                {
                    // Get the response stream
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string res = reader.ReadToEnd();

                    Trace.WriteLine(res);

                    Trace.WriteLine("End PutRequest");

                    return res;
                }
            }
            catch ( WebException exception )
            {
                StreamReader reader = new StreamReader(exception.Response.GetResponseStream());
                string res = reader.ReadToEnd();

                throw MiteException.CreateFromResponse(res, exception);
            }
        }

        //--------------------------------------------------------------------------
        /// <summary>
        /// Sends a HTTP delete request.
        /// </summary>
        /// <param name="url">The url to which the request is send.</param>
        /// <returns>The response.</returns>
        public string SendDeleteRequest(string url)
        {
            HttpWebRequest request = CreateRequest(url);
            request.Method = "DELETE";

            using ( HttpWebResponse response = (HttpWebResponse) request.GetResponse() )
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string answer = reader.ReadToEnd();

                Trace.WriteLine(answer);

                Trace.WriteLine("End DeleteRequest");

                return answer;
            }
        }
    }
}


text:
{% extends "base.html" %}

{% block title %}Pending Suggestions{% endblock %}

{% block content %}

Suggestions

Team Medias

{{ suggestions_and_references_and_preferred|length }} Pending Team Media Suggestions

Video Approval Guidelines

        Do approve:

Chairman's video

Robot reveal

Robot testing

Awards ceremony

Practice matches

        Do NOT approve:

Full matches (from any PoV)

People dancing

Long, drawn out videos with little to no real content

Image Approval Guidelines

        Do approve:

Robot photos

Team photos with robot

        Do NOT approve:

GIFs

Images without robot

  <form action="/suggest/team/media/review" method="post" id="review_media">
      <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>

                      Select All Accepts
                      Select All Rejects
                      Deselect All

          {% for suggestion, reference, preferred in suggestions_and_references_and_preferred %}

                      <input class="accept" type="radio" name="accept_reject-{{suggestion.key.id()}}" value="accept::{{suggestion.key.id()}}"> Accept

                      <input class="reject" type="radio" name="accept_reject-{{suggestion.key.id()}}" value="reject::{{suggestion.key.id()}}"> Reject

                    <input type="text" class="form-control" name="year-{{suggestion.key.id()}}" placeholder="Year" value="{{suggestion.contents.year}}">

Team {{reference.team_number}}{% if reference.nickname %} - {{reference.nickname}}{% endif %} ({{suggestion.contents.year}})

                      {% set media = suggestion.candidate_media -%}
                      {% include "media_partials/media_display_partial.html" %}

                    {% if preferred %}
                    Existing Preferred:
                    {% endif %}
                    {% for media in preferred %}
                      {% if preferred|length >= max_preferred %}

                        <input type="radio" name="replace-preferred-{{suggestion.key.id()}}" value="{{media.key.id()}}"> Replace

                      {% endif %}

                        {% include "media_partials/image_thumbnail_partial.html" %}

                    {% endfor %}
                    {% if suggestion.contents.media_type_enum == 1 or suggestion.contents.media_type_enum == 2 or suggestion.contents.media_type_enum == 10 %}
                      {% if preferred|length < max_preferred %}

                        <input type="checkbox" name="preferred_keys[]" id="preferred_{{suggestion.key.id()}}" value="preferred::{{suggestion.key.id()}}" {% if suggestion.contents.default_preferred %}checked{% endif %}> Add as Preferred
(Doesn't do anything for non-images)

                      {% else %}

                          <input type="radio" name="replace-preferred-{{suggestion.key.id()}}" value="" checked> Keep Current Preferred

                      {% endif %}
                    {% endif %}

{{ suggestion.key.id() }}

{{ suggestion.author.get().email }}

{{ suggestion.author.get().nickname }}

Show contents_json

{{ suggestion.contents_json }}

{{ suggestion.private_details_json }}

          {% else %}

No suggestions! Go build more community!

          {% endfor %}

              <button class="btn btn-primary" type="submit"> Act On Selected</button>

  </form>

{% endblock %}

{% block inline_javascript %}

{% endblock %}


text:
module dojo.dnd{
export class Mover{
host : Object;
events : any[];
mouseButton : any;
onMouseMove (e:any) : any;
onMouseUp (e:any) : any;
onFirstMove (e:any) : any;
destroy () : any;
}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class it.uniroma1.lcl.dietrolequinte.Utente</title>
<meta name="date" content="2015-09-11">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
it.uniroma1.lcl.dietrolequinte.Utente

Packages that use Utente

Package
Description

it.uniroma1.lcl.dietrolequinte

it.uniroma1.lcl.dietrolequinte.loader

it.uniroma1.lcl.dietrolequinte.loader.chat

it.uniroma1.lcl.dietrolequinte.loader.query

it.uniroma1.lcl.dietrolequinte.search

Uses of Utente in it.uniroma1.lcl.dietrolequinte

Methods in it.uniroma1.lcl.dietrolequinte that return Utente

Modifier and Type
Method and Description

Utente
AbstractInterrogazione.getUser()

Getter per l'Utente dell'interrogazione

Methods in it.uniroma1.lcl.dietrolequinte with parameters of type Utente

Modifier and Type
Method and Description

int
Utente.compareTo(Utente o)

Constructors in it.uniroma1.lcl.dietrolequinte with parameters of type Utente

Constructor and Description

AbstractInterrogazione(Utente u,
                      java.lang.String stringaImmessa,
                      java.time.LocalDateTime ldt)

Uses of Utente in it.uniroma1.lcl.dietrolequinte.loader

Methods in it.uniroma1.lcl.dietrolequinte.loader that return types with arguments of type Utente

Modifier and Type
Method and Description

java.util.TreeSet<Utente>
AbstractLoader.getUsers()

Uses of Utente in it.uniroma1.lcl.dietrolequinte.loader.chat

Constructors in it.uniroma1.lcl.dietrolequinte.loader.chat with parameters of type Utente

Constructor and Description

Azione(Utente u,
      java.lang.String stringaImmessa,
      java.time.LocalDateTime ldt,
      java.lang.String azione)

InterrogazioneChat(Utente u,
                  java.lang.String stringaImmessa,
                  java.time.LocalDateTime ldt,
                  java.lang.String ipAddress,
                  java.lang.String azione,
                  java.lang.String messaggio)

Login(Utente u,
     java.lang.String stringaImmessa,
     java.time.LocalDateTime ldt,
     java.lang.String ipAddress)

Loginout(Utente u,
        java.lang.String stringaImmessa,
        java.time.LocalDateTime ldt,
        java.lang.String ipAddress)

Logout(Utente u,
      java.lang.String stringaImmessa,
      java.time.LocalDateTime ldt,
      java.lang.String ipAddress)

Messaggio(Utente u,
         java.lang.String stringaImmessa,
         java.time.LocalDateTime ldt,
         java.lang.String messaggio)

Uses of Utente in it.uniroma1.lcl.dietrolequinte.loader.query

Constructors in it.uniroma1.lcl.dietrolequinte.loader.query with parameters of type Utente

Constructor and Description

Interrogazione(Utente u,
              java.lang.String stringaImmessa,
              java.time.LocalDateTime ldt)

Interrogazione(Utente u,
              java.lang.String stringaImmessa,
              java.time.LocalDateTime ldt,
              java.lang.String linkCliccato,
              java.lang.Integer posizioneLink)

Uses of Utente in it.uniroma1.lcl.dietrolequinte.search

Methods in it.uniroma1.lcl.dietrolequinte.search that return types with arguments of type Utente

Modifier and Type
Method and Description

java.util.Collection<Utente>
Searcher.getUsers()

java.util.Collection<Utente>
Searcher.getUsers(java.lang.String s)

Methods in it.uniroma1.lcl.dietrolequinte.search with parameters of type Utente

Modifier and Type
Method and Description

java.util.Collection<SearchResult>
Searcher.search(Utente u,
      java.lang.String info)

Cerca i risultati secondo alcuni parametri

java.util.Collection<SearchResult>
Searcher.search(Utente u,
      java.lang.String info,
      java.time.LocalDateTime begin,
      java.time.LocalDateTime end)

Cerca i risultati secondo alcuni parametri entro un intervallo di date

java.util.Collection<SearchResult>
Searcher.search(Utente u,
      java.lang.String info,
      java.lang.String file)

Cerca i risultati secondo alcuni parametri

java.util.Collection<SearchResult>
Searcher.search(Utente u,
      java.lang.String info,
      java.lang.String file,
      java.time.LocalDateTime begin,
      java.time.LocalDateTime end)

Cerca i risultati secondo alcuni parametri entro un intervallo di date

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
var base_funcs = require("/home/da/imp/MyLife/apps/SITES/okdoki/test/casper_base");
var exists_f   = base_funcs.create_exists;
var test_f     = base_funcs.create_test;
var innerHTML_f= base_funcs.innerHTML_f;
var casper     = base_funcs.new_casper("sign_in");

var msg = function () {
  return document.querySelector('#sign_in div.errors').innerHTML;
};

var form                = '#form_homepage_priv ';
var success             = form + 'div.success';
var css_specify_display = function (form) { return $(form + 'div.specify').css('display'); };
var css_submit_display  = function (form) { return $(form + 'button.submit').css('display'); };
var css_fields_display = function (form) { return $(form + 'div.fields').css('display'); };
var css_menu_selected  = function () { return $('#form_homepage_priv select option:selected').val(); };
var submit              = form + 'button.submit';
var success             = form + 'div.success';
var css_body            = function (css) { return $('body').hasClass(css); };

// === Default css classes.
casper.thenOpen(base_funcs.url + '/info/go99', function () {
  this.test.assertEvalEqual(css_menu_selected, 'W', "Selected menu option should be 'W'");
  this.test.assertEval(css_body, "Body has default class: world_read.", 'world_read');
  this.test.assertEvalEquals(css_specify_display, 'none', "Specify text box hidden by default.", form);
  this.test.assertEvalEquals(css_submit_display, 'none', "Submit button hidden before any menu change.", form);
});

// === Changing privacy menu.
casper.then(function () {
  this.evaluate(function (form) { $(form + ' select.menu_priv').val('S').change(); }, form);
  this.wait(300);
  // this.test.assertEvalEquals(css_specify_display, 'block', "Specify text box shown when 'specify' selected in menu.", form);
  this.test.assertEvalEquals(css_submit_display, 'inline-block', "Submit button shown after menu change.", form);

  this.evaluate(function (form) { $(form + ' select.menu_priv').val('N').change(); }, form);
  this.wait(300);
  this.test.assertEvalEquals(css_specify_display, 'none', "Specify text box hidden when 'specify' not chosen in menu.", form);
});

// === Submitting privacy menu: N
casper.then(function () {
  this.evaluate(function (form) { $(form + ' select.menu_priv').val('N').change(); }, form);
  this.click(submit);
  this.waitForSelector(success, function () {
    this.test.assertEqual(this.fetchText(success), "Updated settings: no one but you can see this homepage.", "Success msg: when changed to No-One readable.");
    this.test.assertEvalEqual(css_fields_display, "block", "Form fields shown after success.", form);
  });

  this.reload(function () {
    this.test.assertEvalEqual(css_menu_selected, 'N', "Selected menu option should be 'N'");
  });
});

// === Submitting privacy menu: W
casper.then(function () {
  this.evaluate(function (form) { $(form + ' select.menu_priv').val('W').change(); }, form);
  this.click(submit);
  this.waitForSelector(success, function () {
    this.test.assertEqual(this.fetchText(success), "Updated settings: Anyone online may see this homepage.", "Success msg: when changed to world readable.");
    this.test.assertEvalEqual(css_fields_display, "block", "Form fields shown after success.", form);
  });
});

// === Submitting privacy menu: S
// casper.then(function () {
  // this.evaluate(function (form) { $(form + ' select.menu_priv').val('S').change(); }, form);
  // this.evaluate(function (form) { $(form + ' textarea').val('o1 o2 o3'); }, form);

  // this.click(submit);
  // this.waitForSelector(success, function () {
    // this.test.assertEqual(this.fetchText(success), "Updated settings: The following may see your homepage: o1, o2, o3", "Success msg: when changed to 'specify' readable.");
    // this.test.assertEvalEqual(css_fields_display, "block", "Form fields shown after success.", form);
  // });
// });

casper.run(function () {
  this.test.renderResults(true);
});


text:
package org.qfox.jestful.client;

import org.qfox.jestful.commons.Config;

import java.io.Serializable;

/**
 * Created by payne on 2017/3/28.
 */
public class Module extends Config implements Serializable {
    private static final long serialVersionUID = 8979830823718754930L;

    private static Module instance;

    private String name;
    private String version;
    private String parentName;
    private String parentVersion;

    private Module() {
    }

    public static Module getInstance() {
        if (instance != null) {
            return instance;
        }
        synchronized (Module.class) {
            if (instance != null) {
                return instance;
            }
            return instance = new Module();
        }
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public String getParentName() {
        return parentName;
    }

    public String getParentVersion() {
        return parentVersion;
    }
}


text:
angular.module('drawCanvas', [])

.controller('canvasCtrl', canvasCtrl);
console.clear();
function canvasCtrl(FBURL) {
  // DRAWING CANVAS
  var ref = FBURL.db;
  var pixelDataRef = ref.child('canvas');

  //Set up some globals
  var pixSize = 8,
    lastPoint = null,
    currentColor = "000",
    mouseDown = 0;
  // Set up our canvas
  var myCanvas = document.getElementById('drawing-canvas');
  var myContext = myCanvas.getContext ? myCanvas.getContext('2d') : null;
  if (myContext == null) {
    alert("You must use a browser that supports HTML5 Canvas to run this demo.");
    return;
  }
  //Setup each color palette & add it to the screen
  var colors = ["fff", "000", "f00", "0f0", "00f", "88f", "f8d", "f88", "f05", "f80", "0f8", "cf0"];
  for (c in colors) {
    var item = $('<div/>').css("backgroundColor", '#' + colors[c]).addClass("colorbox");
    item.click((function(e) {
      var col = colors[c];
      return function() {
        currentColor = col;
        $('.colorbox').removeClass("active");
        $(this).addClass("active");
      };
    })());
    item.appendTo('#colorholder');
  }

  //Keep track of if the mouse is up or down
  $(myCanvas).on('mousedown touchstart', function() {
    mouseDown = 1;
  })
  myCanvas.onmousedown = function() {};

  $(myCanvas).on('mouseup touchend', function() {
    mouseDown = 0;
    lastPoint = null;
  })
  myCanvas.onmouseup = function() {};

  //Set the active color
  $('.colorbox[style="background-color: rgb(0, 0, 0);"]').addClass("active");
  //Draw a line from the mouse's last position to its current position

  var offset = $('canvas').offset();
  var x1, y1, x0, y0, dx, dy, sx, sy, err, er;
  //Draw a line from the mouse's last position to its current position
  var drawLineOnMouseMove = function(e) {
    if (!mouseDown) return;
    e.preventDefault();

    // Bresenham's line algorithm. We use this to ensure smooth lines are drawn
    x1 = Math.floor((e.pageX - offset.left) / pixSize - 1);
    y1 = Math.floor((e.pageY - offset.top) / pixSize - 1);
    x0 = (lastPoint == null) ? x1 : lastPoint[0];
    y0 = (lastPoint == null) ? y1 : lastPoint[1];
    dx = Math.abs(x1 - x0);
    dy = Math.abs(y1 - y0);
    sx = (x0 < x1) ? 1 : -1;
    sy = (y0 < y1) ? 1 : -1;
    err = dx - dy;
    while (true) {
      pixelDataRef.child(x0 + ":" + y0).set(currentColor === "fff" ? null : currentColor);

      if (x0 == x1 && y0 == y1) return;
      e2 = 2 * err;
      if (e2 > -dy) {
        err = err - dy;
        x0 = x0 + sx;
      }
      if (e2 < dx) {
        err = err + dx;
        y0 = y0 + sy;
      }
    }
    lastPoint = [x1, y1];
  };

  var drawLineOnTouchMove = function(e) {
    if (!mouseDown) {
      return;
    }
    e.preventDefault();
    x1 = Math.floor((e.originalEvent.touches[0].pageX - offset.left) / pixSize - 1);
    y1 = Math.floor((e.originalEvent.touches[0].pageY - offset.top) / pixSize - 1);
    x0 = (lastPoint === null) ? x1 : lastPoint[0];
    y0 = (lastPoint === null) ? y1 : lastPoint[1];
    dx = Math.abs(x1 - x0);
    dy = Math.abs(y1 - y0);
    sx = (x0 < x1) ? 1 : -1;
    sy = (y0 < y1) ? 1 : -1;
    err = dx - dy;
    pixelDataRef.child(x0 + ':' + y0).set(currentColor === 'fff' ? null : currentColor);
    if (x0 === x1 && y0 === y1) return;
    e2 = 2 * err;
    if (e2 > -dy) {
      console.log("here");
      err = err - dy;
      x0 = x0 + sx;
    }
    if (e2 < dx) {
      err = err + dx;
      y0 = y0 + sy;
    }

    lastPoint = [x1, y1];
  };

  $(myCanvas).on('mousedown', drawLineOnMouseMove);
  $(myCanvas).on('mousemove', drawLineOnMouseMove);

  $(myCanvas).on('touchstart', drawLineOnTouchMove);
  $(myCanvas).on('touchmove', drawLineOnTouchMove);

  // Add callbacks that are fired any time the pixel data changes and adjusts the canvas appropriately.
  // Note that child_added events will be fired for initial pixel data as well.
  var drawPixel = function(snapshot) {
    var coords = snapshot.key().split(":");
    myContext.fillStyle = "#" + snapshot.val();
    myContext.fillRect(parseInt(coords[0]) * pixSize, parseInt(coords[1]) * pixSize, pixSize, pixSize);
  };
  var clearPixel = function(snapshot) {
    var coords = snapshot.key().split(":");
    myContext.clearRect(parseInt(coords[0]) * pixSize, parseInt(coords[1]) * pixSize, pixSize, pixSize);
  };
  pixelDataRef.on('child_added', drawPixel);
  pixelDataRef.on('child_changed', drawPixel);
  pixelDataRef.on('child_removed', clearPixel);

}


text:
package org.pesc.service;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pesc.api.StringUtils;
import org.pesc.api.model.*;
import org.pesc.api.repository.InstitutionUploadResultsRepository;
import org.pesc.api.repository.InstitutionUploadsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by James Whetstone (jwhetstone@ccctechcenter.org) on 5/6/16.
 */
@Service
public class InstitutionUploadService {

    private static final Log log = LogFactory.getLog(InstitutionUploadService.class);

    private static final int MAX_COLUMNS = 11;
    private static String[] REQUIRED_COLUMNS_NAMES = {"name","city","state","atp","act","ipeds","opeid","fice","cds","ceeb" };
    private static String[] OPTINOAL_COLUMN_NAMES = { "website","street","zip" };

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private SchoolCodesService schoolCodesService;

    @Autowired
    private InstitutionUploadsRepository uploadsRepository;

    @Autowired
    private InstitutionUploadResultsRepository resultsRepository;

    @Transactional(readOnly=false,propagation = Propagation.REQUIRED)
    @PreAuthorize("(#institutionsUpload.organizationId == principal.organizationId AND  hasRole('ROLE_ORG_ADMIN') ) OR hasRole('ROLE_SYSTEM_ADMIN')")
    public InstitutionsUpload create(InstitutionsUpload institutionsUpload)  {
        return uploadsRepository.save(institutionsUpload);
    }

    @Transactional(readOnly=false,propagation = Propagation.REQUIRED)
    @PreAuthorize("(#institutionsUpload.organizationId == principal.organizationId AND  hasRole('ROLE_ORG_ADMIN') ) OR hasRole('ROLE_SYSTEM_ADMIN')")
    public InstitutionsUpload update(InstitutionsUpload institutionsUpload)  {
        return uploadsRepository.save(institutionsUpload);
    }

    @Transactional(readOnly=true,propagation = Propagation.REQUIRED)
    @PreAuthorize("(#orgID == principal.organizationId AND  hasRole('ROLE_ORG_ADMIN') ) OR hasRole('ROLE_SYSTEM_ADMIN')")
    public List<InstitutionsUpload> getUploadsByOrganization(Integer orgID)  {
        return uploadsRepository.findByOrgId(orgID);
    }

    @Transactional(readOnly=true,propagation = Propagation.REQUIRED)
    @PostAuthorize("( (returnObject.organizationId == principal.organizationId AND hasRole('ROLE_ORG_ADMIN') ) OR hasRole('ROLE_SYSTEM_ADMIN'))")
    public InstitutionsUpload getUploadById(Integer uploadId)  {
        return uploadsRepository.findOne(uploadId);
    }

    @Transactional(readOnly=true,propagation = Propagation.REQUIRED)
    public List<InstitutionsUploadResult> getUploadResultsByUploadId(Integer uploadId)  {
        return resultsRepository.findByUploadId(uploadId);
    }

    @Transactional(readOnly=true,propagation = Propagation.REQUIRED)
    public List<InstitutionsUploadResult> getUploadResultsByOrgId(Integer orgID)  {
        return resultsRepository.findByOrgId(orgID);
    }

    @Transactional(readOnly=false,propagation = Propagation.REQUIRED)
    public InstitutionsUploadResult create(InstitutionsUploadResult institutionsResultUpload)  {
        return resultsRepository.save(institutionsResultUpload);
    }

    @Transactional(readOnly=true)
    public List<CSVStatusDTO> getCSVStatus(Integer uploadID)  {

        String sql = "SELECT iur.line_number, iu.end_time FROM institution_uploads iu JOIN institution_upload_results iur on iur.institution_upload_id = iu.id WHERE iu.id = ? order by iur.line_number DESC LIMIT 1";
        List<Map<String,Object>> rows = jdbcTemplate.queryForList(sql, uploadID);

        ArrayList<CSVStatusDTO> statusList = new ArrayList<CSVStatusDTO>();

        for(Map row : rows) {
            CSVStatusDTO status = new CSVStatusDTO();
            status.setLineNumber((Integer) row.get("line_Number"));
            java.sql.Timestamp dateTime = (java.sql.Timestamp)row.get("end_time");

            if (dateTime != null)
                 status.setEndTime(new Date(dateTime.getTime()));
            statusList.add(status);
        }

        return statusList;
    }

    private boolean isValidUploadFile(Map<String,Integer> headerMap) {

        for(String columnName : REQUIRED_COLUMNS_NAMES) {

            if (!headerMap.containsKey(columnName)) {
                return false;
            }
        }
        return true;

    }

    private void addSchoolCode(Set<SchoolCode> schoolCodes, String codeType, String code){
        if (!StringUtils.isEmpty(code)){
            SchoolCode schoolCode = new SchoolCode();
            schoolCode.setCodeType(codeType);
            schoolCode.setCode(code);
            schoolCodesService.validateSchoolCode(schoolCode);
            schoolCodes.add(schoolCode);
        }
    }

    @Async
    public void processCSVFile(InstitutionsUpload institutionsUpload, String filePath, Integer serviceProviderID) {

        try {
            institutionsUpload.setStartTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));

            this.update(institutionsUpload);

            final Reader reader = new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8");
            final CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader());

            if (!isValidUploadFile(parser.getHeaderMap() ) ) {
                InstitutionsUploadResult result = new InstitutionsUploadResult();
                result.setInstitutionUploadID(institutionsUpload.getId());
                result.setOrganizationID(serviceProviderID);

                result.setOutcome(InstitutionUploadResultsRepository.ERROR);
                StringBuilder buf = new StringBuilder("The institutions CSV file must contain a header record with the following case sensitive column names: ");
                buf.append(String.join(",", REQUIRED_COLUMNS_NAMES));
                result.setMessage(buf.toString());
                this.create(result);
                return;
            }

            try {
                for (final CSVRecord record : parser) {

                    Organization organization = new Organization();
                    organization.setName(record.get("name").trim());

                    if (record.isMapped("street"))
                        organization.setStreet(record.get("street").trim());

                    organization.setCity(record.get("city").trim());
                    organization.setState(record.get("state").trim());
                    if (record.isMapped("zip"))
                        organization.setZip(record.get("zip").trim());

                    if (record.isMapped("website"))
                        organization.setWebsite(record.get("website").trim());

                    InstitutionsUploadResult result = new InstitutionsUploadResult();
                    result.setInstitutionUploadID(institutionsUpload.getId());
                    result.setOrganizationID(serviceProviderID);
                    result.setLineNumber((int)parser.getCurrentLineNumber());

                    Set<SchoolCode> schoolCodes = new HashSet<SchoolCode>();

                    try {
                        addSchoolCode(schoolCodes, "ATP", record.get("atp").trim());
                        addSchoolCode(schoolCodes, "FICE", record.get("fice").trim());
                        addSchoolCode(schoolCodes, "IPEDS", record.get("ipeds").trim());
                        addSchoolCode(schoolCodes, "OPEID", record.get("opeid").trim());
                        addSchoolCode(schoolCodes, "ACT", record.get("act").trim());
                        addSchoolCode(schoolCodes, "CDS", record.get("cds").trim());
                        addSchoolCode(schoolCodes, "CEEB", record.get("ceeb").trim());
                    }
                    catch (IllegalArgumentException e) {
                        result.setLineNumber((int) parser.getCurrentLineNumber());

                        result.setOutcome(InstitutionUploadResultsRepository.ERROR);

                        if (e.getMessage() != null) {
                            result.setMessage(e.getMessage());
                        }
                        this.create(result);
                        continue;
                    }

                    if (schoolCodes.isEmpty()){
                        result.setLineNumber((int) parser.getCurrentLineNumber());

                        result.setOutcome(InstitutionUploadResultsRepository.ERROR);

                        result.setMessage(String.format("No school code was provided for %s.  At least one school code must be used to create an institution", record.get("name")));

                        this.create(result);
                        continue;
                    }

                    List<Organization> institutions = organizationService.findBySchoolCodes(schoolCodes);

                    if (institutions.size() == 1) {
                        organizationService.insecureLinkInstitutionWithServiceProvider(institutions.get(0).getId(), serviceProviderID);
                        result.setOutcome(InstitutionUploadResultsRepository.SUCCESS);
                        result.setMessage(
                                String.format("An institution was found with one or more of school code(s) ATP %s, FICE %s, IPEDS %s, ACT %s, OPEID %s, " +
                                        "and was added to the service provider's serviceable institutions.", record.get("atp"), record.get("fice"), record.get("ipeds"), record.get("act"), record.get("opeid")));
                        result.setInstitutionID(institutions.get(0).getId());
                        result.setInstitutionName(institutions.get(0).getName());
                    }
                    else if (institutions.isEmpty()) {
                        try {
                            organization = organizationService.createInstitution(organization, schoolCodes, serviceProviderID);
                            result.setMessage(String.format("An institution was created with the following school code(s) ATP %s, FICE %s, IPEDS %s, ACT %s, OPEID %s, " +
                                    "and was added to the service provider's serviceable institutions.", record.get("atp"), record.get("fice"), record.get("ipeds"), record.get("act"), record.get("opeid")));

                            result.setOutcome(InstitutionUploadResultsRepository.SUCCESS);
                            result.setInstitutionID(organization.getId());
                            result.setInstitutionName(organization.getName());
                        }
                        catch (Exception e) {
                            log.error("Failed to create institution.", e);
                            result.setOutcome(InstitutionUploadResultsRepository.ERROR);
                            StringBuilder messageBuilder = new StringBuilder(String.format(
                                    "
Could not create institution with code(s) ATP %s, FICE %s, IPEDS %s, ACT %s, OPEID %s.  Exception %s
",
                                    record.get("atp"), record.get("fice"), record.get("ipeds"), record.get("act"), record.get("opeid"), e.getClass().getCanonicalName()));
                            result.setMessage(messageBuilder.toString());
                            result.setInstitutionID(organization.getId());
                            result.setInstitutionName(organization.getName());
                        }
                    }
                    else {
                        StringBuilder messageBuilder = new StringBuilder(String.format(
                                "

%s was not processed because multiple institutions were found with the same school code(s) ATP %s, FICE %s, IPEDS %s, ACT %s, OPEID %s.  This indicates data inconsistency.
",
                                record.get("name"), record.get("atp"), record.get("fice"), record.get("ipeds"), record.get("act"), record.get("opeid")));

                        for(Organization institution : institutions) {
                            messageBuilder.append(String.format("
%s
", institution.getId(), institution.getName()));
                        }

                        messageBuilder.append("
");

                        result.setOutcome(InstitutionUploadResultsRepository.ERROR);
                        result.setMessage(messageBuilder.toString());
                        result.setInstitutionID(organization.getId());
                        result.setInstitutionName(organization.getName());
                    }

                    this.create(result);

                }
            }
            catch (Exception e){

                log.error("Failed to process institution upload file. Inserting result record.", e);

                InstitutionsUploadResult result = new InstitutionsUploadResult();
                result.setInstitutionUploadID(institutionsUpload.getId());
                result.setOrganizationID(serviceProviderID);
                result.setLineNumber((int) parser.getCurrentLineNumber());

                result.setOutcome(InstitutionUploadResultsRepository.ERROR);

                if (e.getMessage() != null) {
                    result.setMessage(e.getMessage());
                }
                this.create(result);
            }
            finally {
                parser.close();
                reader.close();

            }
        } catch (Exception e) {
            log.error("Failed to process CSV file for institution creation.", e);
        }
        finally {
            institutionsUpload.setEndTime(new Timestamp(Calendar.getInstance().getTimeInMillis()));
            this.update(institutionsUpload);
        }

    }
}


text:
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';
import Busboy from 'busboy';

import { API } from '../../../api/server';
import { getWorkspaceAccessToken, getUserCloudAccessToken } from '../../../cloud/server';
import { settings } from '../../../settings';
import { Info } from '../../../utils';
import { Settings, Users } from '../../../models/server';
import { Apps } from '../orchestrator';

const appsEngineVersionForMarketplace = Info.marketplaceApiVersion.replace(/-.*/g, '');
const getDefaultHeaders = () => ({
	'X-Apps-Engine-Version': appsEngineVersionForMarketplace,
});

const purchaseTypes = new Set(['buy', 'subscription']);

export class AppsRestApi {
	constructor(orch, manager) {
		this._orch = orch;
		this._manager = manager;
		this.loadAPI();
	}

	_handleFile(request, fileField) {
		const busboy = new Busboy({ headers: request.headers });

		return Meteor.wrapAsync((callback) => {
			busboy.on('file', Meteor.bindEnvironment((fieldname, file) => {
				if (fieldname !== fileField) {
					return callback(new Meteor.Error('invalid-field', `Expected the field "${ fileField }" but got "${ fieldname }" instead.`));
				}

				const fileData = [];
				file.on('data', Meteor.bindEnvironment((data) => {
					fileData.push(data);
				}));

				file.on('end', Meteor.bindEnvironment(() => callback(undefined, Buffer.concat(fileData))));
			}));

			request.pipe(busboy);
		})();
	}

	async loadAPI() {
		this.api = new API.ApiClass({
			version: 'apps',
			useDefaultAuth: true,
			prettyJson: false,
			enableCors: false,
			auth: API.getUserAuth(),
		});
		this.addManagementRoutes();
	}

	addManagementRoutes() {
		const orchestrator = this._orch;
		const manager = this._manager;
		const fileHandler = this._handleFile;

		this.api.addRoute('', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				const baseUrl = orchestrator.getMarketplaceUrl();

				// Gets the Apps from the marketplace
				if (this.queryParams.marketplace) {
					const headers = getDefaultHeaders();
					const token = getWorkspaceAccessToken();
					if (token) {
						headers.Authorization = `Bearer ${ token }`;
					}

					let result;
					try {
						result = HTTP.get(`${ baseUrl }/v1/apps`, {
							headers,
						});
					} catch (e) {
						orchestrator.getRocketChatLogger().error('Error getting the Apps:', e.response.data);
						return API.v1.internalError();
					}

					if (!result || result.statusCode !== 200) {
						orchestrator.getRocketChatLogger().error('Error getting the Apps:', result.data);
						return API.v1.failure();
					}

					return API.v1.success(result.data);
				}

				if (this.queryParams.categories) {
					const headers = getDefaultHeaders();
					const token = getWorkspaceAccessToken();
					if (token) {
						headers.Authorization = `Bearer ${ token }`;
					}

					let result;
					try {
						result = HTTP.get(`${ baseUrl }/v1/categories`, {
							headers,
						});
					} catch (e) {
						orchestrator.getRocketChatLogger().error('Error getting the categories from the Marketplace:', e.response.data);
						return API.v1.internalError();
					}

					if (!result || result.statusCode !== 200) {
						orchestrator.getRocketChatLogger().error('Error getting the categories from the Marketplace:', result.data);
						return API.v1.failure();
					}

					return API.v1.success(result.data);
				}

				if (this.queryParams.buildExternalUrl && this.queryParams.appId) {
					const workspaceId = settings.get('Cloud_Workspace_Id');

					if (!this.queryParams.purchaseType || !purchaseTypes.has(this.queryParams.purchaseType)) {
						return API.v1.failure({ error: 'Invalid purchase type' });
					}

					const token = getUserCloudAccessToken(this.getLoggedInUser()._id, true, 'marketplace:purchase', false);
					if (!token) {
						return API.v1.failure({ error: 'Unauthorized' });
					}

					const subscribeRoute = this.queryParams.details === 'true' ? 'subscribe/details' : 'subscribe';

					const seats = Users.getActiveLocalUserCount();

					return API.v1.success({
						url: `${ baseUrl }/apps/${ this.queryParams.appId }/${
							this.queryParams.purchaseType === 'buy' ? this.queryParams.purchaseType : subscribeRoute
						}?workspaceId=${ workspaceId }&token=${ token }&seats=${ seats }`,
					});
				}

				const apps = manager.get().map((prl) => {
					const info = prl.getInfo();
					info.languages = prl.getStorageItem().languageContent;
					info.status = prl.getStatus();

					return info;
				});

				return API.v1.success({ apps });
			},
			post() {
				let buff;
				let marketplaceInfo;

				if (this.bodyParams.url) {
					if (settings.get('Apps_Framework_Development_Mode') !== true) {
						return API.v1.failure({ error: 'Installation from url is disabled.' });
					}

					let result;
					try {
						result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: null } });
					} catch (e) {
						orchestrator.getRocketChatLogger().error('Error getting the app from url:', e.response.data);
						return API.v1.internalError();
					}

					if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') {
						return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' });
					}

					buff = result.content;
				} else if (this.bodyParams.appId && this.bodyParams.marketplace && this.bodyParams.version) {
					const baseUrl = orchestrator.getMarketplaceUrl();

					const headers = getDefaultHeaders();

					const downloadPromise = new Promise((resolve, reject) => {
						const token = getWorkspaceAccessToken(true, 'marketplace:download', false);

						HTTP.get(`${ baseUrl }/v1/apps/${ this.bodyParams.appId }/download/${ this.bodyParams.version }?token=${ token }`, {
							headers,
							npmRequestOptions: { encoding: null },
						}, (error, result) => {
							if (error) { reject(error); }

							resolve(result);
						});
					});

					const marketplacePromise = new Promise((resolve, reject) => {
						const token = getWorkspaceAccessToken();

						HTTP.get(`${ baseUrl }/v1/apps/${ this.bodyParams.appId }?appVersion=${ this.bodyParams.version }`, {
							headers: {
								Authorization: `Bearer ${ token }`,
								...headers,
							},
						}, (error, result) => {
							if (error) { reject(error); }

							resolve(result);
						});
					});

					try {
						const [downloadResult, marketplaceResult] = Promise.await(Promise.all([downloadPromise, marketplacePromise]));

						if (!downloadResult.headers['content-type'] || downloadResult.headers['content-type'] !== 'application/zip') {
							throw new Error('Invalid url. It doesn\'t exist or is not "application/zip".');
						}

						buff = downloadResult.content;
						marketplaceInfo = marketplaceResult.data[0];
					} catch (err) {
						return API.v1.failure(err.message);
					}
				} else {
					if (settings.get('Apps_Framework_Development_Mode') !== true) {
						return API.v1.failure({ error: 'Direct installation of an App is disabled.' });
					}

					buff = fileHandler(this.request, 'app');
				}

				if (!buff) {
					return API.v1.failure({ error: 'Failed to get a file to install for the App. ' });
				}

				const aff = Promise.await(manager.add(buff.toString('base64'), true, marketplaceInfo));
				const info = aff.getAppInfo();

				if (aff.hasStorageError()) {
					return API.v1.failure({ status: 'storage_error', messages: [aff.getStorageError()] });
				}

				if (aff.getCompilerErrors().length) {
					return API.v1.failure({ status: 'compiler_error', messages: aff.getCompilerErrors() });
				}

				if (aff.hasAppUserError()) {
					return API.v1.failure({
						status: 'app_user_error',
						messages: [aff.getAppUserError().message],
						payload: { username: aff.getAppUserError().username },
					});
				}

				info.status = aff.getApp().getStatus();

				return API.v1.success({
					app: info,
					implemented: aff.getImplementedInferfaces(),
					licenseValidation: aff.getLicenseValidationResult(),
				});
			},
		});

		this.api.addRoute('externalComponents', { authRequired: false }, {
			get() {
				const externalComponents = orchestrator.getProvidedComponents();

				return API.v1.success({ externalComponents });
			},
		});

		this.api.addRoute('languages', { authRequired: false }, {
			get() {
				const apps = manager.get().map((prl) => ({
					id: prl.getID(),
					languages: prl.getStorageItem().languageContent,
				}));

				return API.v1.success({ apps });
			},
		});

		this.api.addRoute('externalComponentEvent', { authRequired: true }, {
			post() {
				if (!this.bodyParams.externalComponent || !['IPostExternalComponentOpened', 'IPostExternalComponentClosed'].includes(this.bodyParams.event)) {
					return API.v1.failure({ error: 'Event and externalComponent must be provided.' });
				}

				try {
					const { event, externalComponent } = this.bodyParams;
					const result = Apps.getBridges().getListenerBridge().externalComponentEvent(event, externalComponent);

					return API.v1.success({ result });
				} catch (e) {
					orchestrator.getRocketChatLogger().error(`Error triggering external components' events ${ e.response.data }`);
					return API.v1.internalError();
				}
			},
		});

		this.api.addRoute('bundles/:id/apps', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				const baseUrl = orchestrator.getMarketplaceUrl();

				const headers = {};
				const token = getWorkspaceAccessToken();
				if (token) {
					headers.Authorization = `Bearer ${ token }`;
				}

				let result;
				try {
					result = HTTP.get(`${ baseUrl }/v1/bundles/${ this.urlParams.id }/apps`, {
						headers,
					});
				} catch (e) {
					orchestrator.getRocketChatLogger().error('Error getting the Bundle\'s Apps from the Marketplace:', e.response.data);
					return API.v1.internalError();
				}

				if (!result || result.statusCode !== 200 || result.data.length === 0) {
					orchestrator.getRocketChatLogger().error('Error getting the Bundle\'s Apps from the Marketplace:', result.data);
					return API.v1.failure();
				}

				return API.v1.success({ apps: result.data });
			},
		});

		const handleError = (message, e) => {
			orchestrator.getRocketChatLogger().error(message, e.response.data);

			if (e.response.statusCode >= 500 && e.response.statusCode <= 599) {
				return API.v1.internalError();
			}

			if (e.response.statusCode === 404) {
				return API.v1.notFound();
			}

			return API.v1.failure();
		};

		this.api.addRoute(':id', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				if (this.queryParams.marketplace && this.queryParams.version) {
					const baseUrl = orchestrator.getMarketplaceUrl();

					const headers = {}; // DO NOT ATTACH THE FRAMEWORK/ENGINE VERSION HERE.
					const token = getWorkspaceAccessToken();
					if (token) {
						headers.Authorization = `Bearer ${ token }`;
					}

					let result;
					try {
						result = HTTP.get(`${ baseUrl }/v1/apps/${ this.urlParams.id }?appVersion=${ this.queryParams.version }`, {
							headers,
						});
					} catch (e) {
						return handleError('Error getting the App information from the Marketplace:', e);
					}

					if (!result || result.statusCode !== 200 || result.data.length === 0) {
						orchestrator.getRocketChatLogger().error('Error getting the App information from the Marketplace:', result.data);
						return API.v1.failure();
					}

					return API.v1.success({ app: result.data[0] });
				}

				if (this.queryParams.marketplace && this.queryParams.update && this.queryParams.appVersion) {
					const baseUrl = orchestrator.getMarketplaceUrl();

					const headers = getDefaultHeaders();
					const token = getWorkspaceAccessToken();
					if (token) {
						headers.Authorization = `Bearer ${ token }`;
					}

					let result;
					try {
						result = HTTP.get(`${ baseUrl }/v1/apps/${ this.urlParams.id }/latest?frameworkVersion=${ appsEngineVersionForMarketplace }`, {
							headers,
						});
					} catch (e) {
						return handleError('Error getting the App update info from the Marketplace:', e);
					}

					if (result.statusCode !== 200 || result.data.length === 0) {
						orchestrator.getRocketChatLogger().error('Error getting the App update info from the Marketplace:', result.data);
						return API.v1.failure();
					}

					return API.v1.success({ app: result.data });
				}

				const prl = manager.getOneById(this.urlParams.id);

				if (prl) {
					const info = prl.getInfo();

					return API.v1.success({
						app: {
							...info,
							status: prl.getStatus(),
							licenseValidation: prl.getLatestLicenseValidationResult(),
						},
					});
				}

				return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
			},
			post() {
				let buff;

				if (this.bodyParams.url) {
					if (settings.get('Apps_Framework_Development_Mode') !== true) {
						return API.v1.failure({ error: 'Updating an App from a url is disabled.' });
					}

					const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: null } });

					if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') {
						return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' });
					}

					buff = result.content;
				} else if (this.bodyParams.appId && this.bodyParams.marketplace && this.bodyParams.version) {
					const baseUrl = orchestrator.getMarketplaceUrl();

					const headers = getDefaultHeaders();
					const token = getWorkspaceAccessToken();
					if (token) {
						headers.Authorization = `Bearer ${ token }`;
					}

					let result;
					try {
						result = HTTP.get(`${ baseUrl }/v1/apps/${ this.bodyParams.appId }/download/${ this.bodyParams.version }`, {
							headers,
							npmRequestOptions: { encoding: null },
						});
					} catch (e) {
						orchestrator.getRocketChatLogger().error('Error getting the App from the Marketplace:', e.response.data);
						return API.v1.internalError();
					}

					if (result.statusCode !== 200) {
						orchestrator.getRocketChatLogger().error('Error getting the App from the Marketplace:', result.data);
						return API.v1.failure();
					}

					if (!result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') {
						return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' });
					}

					buff = result.content;
				} else {
					if (settings.get('Apps_Framework_Development_Mode') !== true) {
						return API.v1.failure({ error: 'Direct updating of an App is disabled.' });
					}

					buff = fileHandler(this.request, 'app');
				}

				if (!buff) {
					return API.v1.failure({ error: 'Failed to get a file to install for the App. ' });
				}

				const aff = Promise.await(manager.update(buff.toString('base64')));
				const info = aff.getAppInfo();

				// Should the updated version have compiler errors, no App will be returned
				if (aff.getApp()) {
					info.status = aff.getApp().getStatus();
				} else {
					info.status = 'compiler_error';
				}

				return API.v1.success({
					app: info,
					implemented: aff.getImplementedInferfaces(),
					compilerErrors: aff.getCompilerErrors(),
				});
			},
			delete() {
				const prl = manager.getOneById(this.urlParams.id);

				if (!prl) {
					return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
				}

				Promise.await(manager.remove(prl.getID()));

				const info = prl.getInfo();
				info.status = prl.getStatus();

				return API.v1.success({ app: info });
			},
		});

		this.api.addRoute(':id/sync', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			post() {
				const baseUrl = orchestrator.getMarketplaceUrl();

				const headers = getDefaultHeaders();
				const token = getWorkspaceAccessToken();
				if (token) {
					headers.Authorization = `Bearer ${ token }`;
				}

				const [workspaceIdSetting] = Settings.findById('Cloud_Workspace_Id').fetch();

				let result;
				try {
					result = HTTP.get(`${ baseUrl }/v1/workspaces/${ workspaceIdSetting.value }/apps/${ this.urlParams.id }`, {
						headers,
					});
				} catch (e) {
					orchestrator.getRocketChatLogger().error('Error syncing the App from the Marketplace:', e.response.data);
					return API.v1.internalError();
				}

				if (result.statusCode !== 200) {
					orchestrator.getRocketChatLogger().error('Error syncing the App from the Marketplace:', result.data);
					return API.v1.failure();
				}

				Promise.await(Apps.updateAppsMarketplaceInfo([result.data]));

				return API.v1.success({ app: result.data });
			},
		});

		this.api.addRoute(':id/icon', { authRequired: false }, {
			get() {
				const prl = manager.getOneById(this.urlParams.id);
				if (!prl) {
					return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
				}

				const info = prl.getInfo();
				if (!info || !info.iconFileContent) {
					return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
				}

				const imageData = info.iconFileContent.split(';base64,');

				const buf = Buffer.from(imageData[1], 'base64');

				return {
					statusCode: 200,
					headers: {
						'Content-Length': buf.length,
						'Content-Type': imageData[0].replace('data:', ''),
					},
					body: buf,
				};
			},
		});

		this.api.addRoute(':id/languages', { authRequired: false }, {
			get() {
				const prl = manager.getOneById(this.urlParams.id);

				if (prl) {
					const languages = prl.getStorageItem().languageContent || {};

					return API.v1.success({ languages });
				}
				return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
			},
		});

		this.api.addRoute(':id/logs', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				const prl = manager.getOneById(this.urlParams.id);

				if (prl) {
					const { offset, count } = this.getPaginationItems();
					const { sort, fields, query } = this.parseJsonQuery();

					const ourQuery = Object.assign({}, query, { appId: prl.getID() });
					const options = {
						sort: sort || { _updatedAt: -1 },
						skip: offset,
						limit: count,
						fields,
					};

					const logs = Promise.await(orchestrator.getLogStorage().find(ourQuery, options));

					return API.v1.success({ logs });
				}
				return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
			},
		});

		this.api.addRoute(':id/settings', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				const prl = manager.getOneById(this.urlParams.id);

				if (prl) {
					const settings = Object.assign({}, prl.getStorageItem().settings);

					Object.keys(settings).forEach((k) => {
						if (settings[k].hidden) {
							delete settings[k];
						}
					});

					return API.v1.success({ settings });
				}
				return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
			},
			post() {
				if (!this.bodyParams || !this.bodyParams.settings) {
					return API.v1.failure('The settings to update must be present.');
				}

				const prl = manager.getOneById(this.urlParams.id);

				if (!prl) {
					return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
				}

				const { settings } = prl.getStorageItem();

				const updated = [];
				this.bodyParams.settings.forEach((s) => {
					if (settings[s.id]) {
						Promise.await(manager.getSettingsManager().updateAppSetting(this.urlParams.id, s));
						// Updating?
						updated.push(s);
					}
				});

				return API.v1.success({ updated });
			},
		});

		this.api.addRoute(':id/settings/:settingId', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				try {
					const setting = manager.getSettingsManager().getAppSetting(this.urlParams.id, this.urlParams.settingId);

					API.v1.success({ setting });
				} catch (e) {
					if (e.message.includes('No setting found')) {
						return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`);
					} if (e.message.includes('No App found')) {
						return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
					}
					return API.v1.failure(e.message);
				}
			},
			post() {
				if (!this.bodyParams.setting) {
					return API.v1.failure('Setting to update to must be present on the posted body.');
				}

				try {
					Promise.await(manager.getSettingsManager().updateAppSetting(this.urlParams.id, this.bodyParams.setting));

					return API.v1.success();
				} catch (e) {
					if (e.message.includes('No setting found')) {
						return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`);
					} if (e.message.includes('No App found')) {
						return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
					}
					return API.v1.failure(e.message);
				}
			},
		});

		this.api.addRoute(':id/apis', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				const prl = manager.getOneById(this.urlParams.id);

				if (prl) {
					return API.v1.success({
						apis: manager.apiManager.listApis(this.urlParams.id),
					});
				}
				return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
			},
		});

		this.api.addRoute(':id/status', { authRequired: true, permissionsRequired: ['manage-apps'] }, {
			get() {
				const prl = manager.getOneById(this.urlParams.id);

				if (prl) {
					return API.v1.success({ status: prl.getStatus() });
				}
				return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
			},
			post() {
				if (!this.bodyParams.status || typeof this.bodyParams.status !== 'string') {
					return API.v1.failure('Invalid status provided, it must be "status" field and a string.');
				}

				const prl = manager.getOneById(this.urlParams.id);

				if (!prl) {
					return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
				}

				const result = Promise.await(manager.changeStatus(prl.getID(), this.bodyParams.status));

				return API.v1.success({ status: result.getStatus() });
			},
		});
	}
}


text:
from unittest import TestCase as MyTest
import unittest

class RenamedImportTests(MyTest):
    def test_renamed_import_pass(self):
        pass

    def test_renamed_import_fail(self):
        self.assertTrue(False, "Force a failure in renamed import test.")

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


text:
var name = require('./naming');
var fs = require('fs');

exports.upload = function(req, res) {
    /*var review = {
        file: req.files.thumbnail,
    }*/
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    var returnObj = {
        metaSetup: {
            author: "www.nomis.dk - sp90(github)",
            title: "Boilerplate",
            pagetitle: "index",
            description: "This is a basic boilerplate which imply the best practice in frontend and a nodeJS express server",
            pageurl: fullUrl,
            imgurl: "imgurl"
        },
        content: {
            title: "First reveiw",
            thumbnail: "http://media-cache-ec0.pinimg.com/736x/73/a4/2e/73a42e19698eee5014186f73b1130f83.jpg",
            content: "Here is a long review of this food",
            rating: 8
        }
    };
    //var files = req.files;
    console.log(req.files);
    for (var i = 0; i < req.files.length; i++) {
        var file = req.files[i];
        console.log("file vvvvv ");
        console.log(file);
    };
    res.render("index", returnObj);
    /*var tmp_path = review.file.path;
    var target_path = './public/images/media/' + name.give() + "_" + review.file.name;

    fs.stat(target_path, function(err, stat) {
        if (err == null) {
            var newName = './public/images/media/' + name.give() + "_" + review.file.name;
            fs.rename(tmp_path, newName, function(err) {
                if (err) throw err;
                fs.unlink(tmp_path, function() {
                    if (err) throw err;
                    console.log('File uploaded to: ' + newName + ' - ' + review.file.size + ' bytes');
                    var nnLength = newName.length - 1;
                    var substredName = newName.substr(7, nnLength);
                    console.log(substredName);
                    var insetReview = {
                        header: req.body.header,
                        content: req.body.content,
                        file: substredName,
                        rating: req.body.rating
                    }
                    db.insert(insetReview, function(err, newDoc) { // Callback is optional
                        console.log(newDoc);
                    });
                    db.find({}, function(err, docs) {
                        res.render('index', {
                            header: 'FirstNEDB',
                            posts: docs
                        });
                    });
                });
            });
        } else if (err.code == 'ENOENT') {
            fs.rename(tmp_path, target_path, function(err) {
                if (err) throw err;
                fs.unlink(tmp_path, function() {
                    if (err) throw err;
                    console.log('File uploaded to: ' + target_path + ' - ' + review.file.size + ' bytes');
                    var pathLength = target_path.length - 1;
                    var substredName = target_path.substr(7, pathLength);
                    console.log(substredName);
                    var insetReview = {
                        header: req.body.header,
                        content: req.body.content,
                        file: substredName,
                        rating: req.body.rating
                    }
                    db.insert(insetReview, function(err, newDoc) { // Callback is optional
                        console.log(newDoc);
                    });
                    db.find({}, function(err, docs) {
                        res.render('index', {
                            header: 'FirstNEDB',
                            posts: docs
                        });
                    });
                });
            });
        } else {
            console.log('Some other error: ', err.code);
        }
    });*/
};


text:
Progress: 90%

        Reset

Recap Is everything correct ?

Applicant

{[{app.get('characterName')}]}

Corporation

{[{app.get('corporationName')}]}

Alliance

I Whip My Slaves Back and Forth

Reddit Username

{[{app.get('redditUsername')}]}

Email

Make sure this email is valid as we will need it to contact you when your application is reviewed.

        <input ng-model="email" type="email" class="form-control" name="email" id="email" placeholder="Email">

Motivation

Please write below why you wish to join us, who do you know, who could recommend you, etc...

        <textarea ng-model="motivation" class="form-control" name="motivation" id="motivation" rows="3"></textarea>

         Send application


text:
void EventHandler::addKeyboardHolder(KeyboardEventHolder _newHolder) {
	m_keyboardHolders.push_back(_newHolder);
}

void EventHandler::processKBHoldersPressed(SDL_KeyboardEvent* _event, float _dt) {
	for (auto holder : m_keyboardHolders)
		holder.processOnKeyPressed(_event, _dt);
}

void EventHandler::processKBHoldersReleased(SDL_KeyboardEvent* _event, float _dt) {
	for (auto holder : m_keyboardHolders)
		holder.processOnKeyReleased(_event, _dt);
}

void EventHandler::addMouseHolder(MouseEventHolder _newHolder) {
	m_mouseHolders.push_back(_newHolder);
}

void EventHandler::processMouseHoldersPressed(SDL_MouseButtonEvent* _event, float _dt) {
	for (auto holder : m_mouseHolders)
		holder.processOnButtonPressed(_event, _dt);
}

void EventHandler::processMouseHoldersReleased(SDL_MouseButtonEvent* _event, float _dt) {
	for (auto holder : m_mouseHolders)
		holder.processOnButtonReleased(_event, _dt);
}

void EventHandler::processMouseHoldersMoved(SDL_MouseMotionEvent* _event, float _dt) {
	for (auto holder : m_mouseHolders)
		holder.processOnMouseMoved(_event, _dt);
}


text:
<?php
session_start();
 echo("");
$error = array();
 echo("");

if(isset($_POST['Next']))
	{

if(empty($_POST['DonateOrgLocation']))
		{
			$error['Name'] = 'Required field';
		}

else {

     echo("");
   $_SESSION['DonateOrgLocation'] =  $_POST['DonateOrgLocation'];
   echo("") ;
}

}

?>

<!DOCTYPE html>

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

    <title>Food Rescue Hub</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Food Rescue Hub

                        About

                        Services

                        Contact

           <form method="post" action="signupdonate2.php" class="form-horizontal">

Where is <?php echo $_SESSION['DonateOrg']; ?> located?

                  <?php echo $error['Name']; ?>
                 <input class="big-input" type="text" name="DonateOrgLocation" placeholder="Location">

        <button onclick="history.go(-1);" type="reset" class="btn btn-default">Back</button>
        <input type="submit" name="Next" value="Next" class="btn btn-primary">

</form>


text:
package task

import (
	"time"
	"log"
)

type TaskContainer struct {
	name string
	running bool
	tasks []*Task

	add chan *Task
	stop chan bool
}

func NewContainer(name string) *TaskContainer {
	c := new(TaskContainer)
	c.name = name
	c.add = make(chan *Task)
	c.stop = make(chan bool)
	return c
}

func (c *TaskContainer) GetName() string {
	return c.name
}

func (c *TaskContainer) AddTask(taskName string, trigger *Trigger, job Job) bool {
	for _, task := range(c.tasks) {
		if task.GetName() == taskName {
			return false
		}
	}

	task := NewTask(taskName, trigger, job)
	c.tasks = append(c.tasks, task)
	if c.add != nil && c.running == true {
		c.add <- task
	}

	return true
}

func (c *TaskContainer) RemoveTask(taskName string) bool {

	for i := 0; i < len(c.tasks); {
		task := c.tasks[i]
		if task.name ==  taskName {
			task.Stop()
			c.tasks = append(c.tasks[:i], c.tasks[i+1:]...)
			return true
		}
	}

	return false
}

func (c *TaskContainer) GetTask(taskName string) *Task {
	for _, task := range(c.tasks) {
		if task.GetName() == taskName {
			return task
		}
	}
	return nil
}

func (c *TaskContainer) GetTasks() []*Task {
	return c.tasks
}

func (c *TaskContainer) Start() {

	log.Println("Start Container : " + c.GetName())

	c.running = true

	go func() {
		for {
			select {
			case <-time.After(time.Second * 1):
				for _, task := range (c.tasks) {
					go task.run()
				}
				continue
			case <-c.stop:
				log.Println("Stop Container : " + c.GetName())
				return
			case task := <-c.add:
				log.Println("Add New Task : " + task.GetName())
				go task.run()
			}
		}
	}()

}

func (c *TaskContainer) ResumeAllTask() {
	for _, task := range(c.tasks) {
		task.Start()
	}
}

func (c *TaskContainer) ResumeTask(taskName string) {
	for _, task := range(c.tasks) {
		if taskName == task.name {
			task.Start()
			break
		}
	}
}

func (c *TaskContainer) StopTask(taskName string) {
	for _, task := range(c.tasks) {
		if taskName == task.name {
			task.Stop()
			break
		}
	}
}

func (c *TaskContainer) StopAllTask() {
	for _, task := range(c.tasks) {
		task.Stop()
	}
}

func (c *TaskContainer) StopContainer() {
	c.running = false
	c.stop <- true
}


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

namespace ScriptNET.ZNotation
{
    public class NamedData
    {
        Dictionary<string, object> values = new Dictionary<string, object>();

        public object this[string name]
        {
            get
            {
                if (values.Keys.Contains(name))
                    return values[name];
                else
                    return Constants.Undefined;

            }
            set
            {
                if (values.Keys.Contains(name))
                    values[name] = value;
                else
                    values.Add(name, value);
            }
        }
    }
}


text:
package com.google.api.ads.dfp.jaxws.v201505;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             An Ad Exchange dynamic allocation creative.
 *
 *
 *
Java class for AdExchangeCreative complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="AdExchangeCreative">
 *   <complexContent>
 *     <extension base="{https://www.google.com/apis/ads/publisher/v201505}HasHtmlSnippetDynamicAllocationCreative">
 *       <sequence>
 *         <element name="isNativeEligible" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="isInterstitial" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AdExchangeCreative", propOrder = {
    "isNativeEligible",
    "isInterstitial"
})
public class AdExchangeCreative
    extends HasHtmlSnippetDynamicAllocationCreative
{

    protected Boolean isNativeEligible;
    protected Boolean isInterstitial;

    /**
     * Gets the value of the isNativeEligible property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIsNativeEligible() {
        return isNativeEligible;
    }

    /**
     * Sets the value of the isNativeEligible property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIsNativeEligible(Boolean value) {
        this.isNativeEligible = value;
    }

    /**
     * Gets the value of the isInterstitial property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIsInterstitial() {
        return isInterstitial;
    }

    /**
     * Sets the value of the isInterstitial property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIsInterstitial(Boolean value) {
        this.isInterstitial = value;
    }

}


text:
using namespace core::network::packet::client;

ClientPacket::ClientPacket(uint8_t packetID, uint16_t length) : core::network::packet::Packet(packetID, length) {
}

ClientPacket::ClientPacket(const uint8_t* packetBuffer) : core::network::packet::Packet(packetBuffer) {
}

ClientPacket::~ClientPacket() {
}


text:
require 'sprockets'

module Bitaculous
  module Animatify
    module Integrations # :nodoc:
      # The class for the Sprockets Integration.
      class SprocketsIntegration
        def self.append_paths(paths)
          paths.each { |path| append_path path }
        end

        def self.append_path(path)
          Sprockets.append_path path if File.directory? path
        end
      end
    end
  end
end


text:
from webkitpy.tool.steps.abstractstep import AbstractStep

class PostDiffForCommit(AbstractStep):
    def run(self, state):
        self._tool.bugs.add_patch_to_bug(
            state["bug_id"],
            self.cached_lookup(state, "diff"),
            "Patch for landing",
            mark_for_review=False,
            mark_for_landing=True)


text:
layout: default
permalink: /404.html
---

404


text:
#ifndef SAC_ENC_H
#define SAC_ENC_H

#include "stdio.h"

#include "sac_enc_polyphase.h"
#include "sac_enc_hybfilter.h"
#include "bitstream.h"

typedef struct sSpatialEnc {
  int treeConfig;
  int outputChannels;
  int timeSlots;
  int frameSize;
  SBR_ENCODER_ANA_FILTERBANK filterbank[6];
  tHybFilterStateEnc hybStateEnc[6];
  BSF_INSTANCE *bitstreamFormatter;
} tSpatialEnc;

tSpatialEnc *SpatialEncOpen(int treeConfig, int timeSlots, int *bufferSize, Stream *bitstream);

void SpatialEncApply(tSpatialEnc *self, float *audioInput, float *audioOutput, Stream *bitstream);

void SpatialEncClose(tSpatialEnc *self);

#endif


text:
package org.sakaiproject.feedback.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;

import javax.activation.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Proxy to allow FileItems to be used as DataSources for attachments.
 */
public class FileItemDataSource implements DataSource {

    private FileItem fileItem;

    public FileItemDataSource(FileItem fileItem) {
        this.fileItem = fileItem;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return fileItem.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new IOException("getOutputStream() isn't supported");
    }

    @Override
    public String getContentType() {
        return fileItem.getContentType();
    }

    @Override
    public String getName() {
        String fileName = fileItem.getName();
        if (fileName != null) {
            fileName = FilenameUtils.getName(fileName);
        }
        return fileName;
    }
}


text: DemoList::Application.config.session_store :cookie_store, key: '_DemoList_session'


text:
ChefScript: Time-Sequential Configuration Management Language for Operation Support
==========
Current Version: 0.2.0 (2015-10-31 03:55)

This software is Open Source Software under the MIT License.

- - -

### How to use
1. Setup Chef Workstation (included push-jobs), add target node and config knife command by knife.rb.
  Reference: http://a-msy.jp/wiki/wiki.cgi?page=OSSChefServer

2. Setup initial setting by chefscript/init.sh on Chef Workstation.
  Create MySQL database and user
  Change mode client program "cscli"
  Update PATH env for "cscli"
  Bundle install for dependency

3. Run the server program.
  Run on Chef Workstation: ruby chefscript/src/main.rb

4. Create ChefScript DSL, and manage ChefScript server by client program.
  Run on Client: cscli *

5. Please read more information from Wiki.

#### Caution
This software is beta version, so we may make changes to specifications.

- - -

### Update log
* Version 0.2.0 (2015-10-31 03:55)
Using backend storage system for failure recoverability.
REST API implementation for daemonize and etc.
  Run on Chef Workstation: ruby chefscript/src/main.rb
  Run on Client: cscli

* Version 0.1.0 (2015-06-28 01:25) [will be Discontinued]
Minimum functions version
  Run: ruby chefscript/OLD_VERSION/0.1.0/src/main.rb chefscript/OLD_VERSION/0.1.0/sample/dsl/dsl.rb

- - -

### Research
* 2014-11
第26回コンピュータシステム・シンポジウム (ComSys2014)
"ChefScript: 運用支援のための時系列記述が可能な構成管理手法"

* 2015-03
情報処理学会 第77回全国大会
"ChefScript: 運用ワークフロー記述を可能とする構成管理記述言語"
"ChefScript: A Workflow Description Language for System Configuration Management"

* 2015-08
Summer United Workshops on Parallel, Distributed and Cooperative Processing (SWoPP2015)
"ChefScript: ログベースの障害回復性を備えた運用ワークフロー記述言語"
"ChefScript: A Workflow Description Language with Log Based Recovery"

- - -


text:
namespace ORGame
{

    enum class Difficulty
    {
        NONE,
        Easy,
        Medium,
        Hard,
        Expert
    };

    enum class TrackType
    {
        NONE,
        Guitar,
        Bass,
        Drums,
        Keys,
        Vocals,
    };

    enum class NoteType
    {
        NONE,
        Green,
        Red,
        Yellow,
        Blue,
        Orange,
        Solo,
        Drive,
        Freestyle
    };

    struct TrackNote
    {
        NoteType type;
        double time;
        int32_t tickTimeStart;
        int32_t tickTimeEnd;
        double length;
        int objNoteID;
        int objTailID;
        bool isHopo;
        bool played;
    };

    struct TempoEvent
    {
        int numerator;
        int denominator;
        int qnScaleFactor;
        int qnLength;
        double time;
        int64_t tickTime;
    };

    enum class BarType
    {
        measure,
        beat,
        upbeat, // This isn't always half of a beat one example of this is: 6/8 compound time
    };

    struct BarEvent
    {
        BarType type;
        // int count;
        double time;
    };

    enum class EventType
    {
        solo,
        drive,
        freestyle,
    };

    // Events are for things that have a position/length with no special data accociated with them
    // So drive/solo/freestyle are some examples.
    struct Event
    {
        EventType type;
        double time;
        double length;
    };

    struct TrackInfo
    {
        TrackType type;
        Difficulty difficulty;
        bool hopoSupport;
    };

    class Song;

    class TempoTrack
    {
    public:
        void set_midi(ORCore::SmfReader* midi);

        void add_tempo_event(int ppqn, double time, int64_t tickTime);
        void add_time_sig_event(int numerator, int denominator, int compoundFactor, double time, int64_t tickTime);

        std::vector<TempoEvent*> &get_events(double start, double end);
        std::vector<TempoEvent> &get_events();

        void mark_bars();
        std::vector<BarEvent*> &get_bars(double start, double end);
        std::vector<BarEvent> &get_bars();

    private:
        ORCore::SmfReader* m_midi;

    	std::vector<TempoEvent> m_tempo;
        std::vector<BarEvent> m_bars;
    };

    class Track
    {
    public:

        Track(Song* song, TrackInfo info);

        TrackInfo info();

        void add_note(NoteType type, double time, int32_t tickTime, bool on);
        std::vector<TrackNote*> &get_notes_in_frame(double start, double end);
        std::vector<TrackNote> &get_notes();

        void mark_notes();

        void set_event(EventType type, double time, bool on);
        std::vector<Event> &get_events();

    private:
        Song* m_song;
        TrackInfo m_info;
        std::vector<TrackNote> m_notes;
        std::vector<Event> m_events;
    };

    class Song
    {
    public:
        Song(std::string songpath);
        ~Song();
        void add(TrackType type, Difficulty difficulty, bool hopoSupport);
        bool load();
        void load_track(TrackInfo& trackInfo);
        void load_tracks();
        std::vector<Track> *get_tracks();
        std::vector<TrackInfo> &get_track_info();
        TempoTrack *get_tempo_track();
        int16_t get_divison();
        double length();
        void start();

        // Time methods
        double get_song_time();
        uint32_t get_song_tick_time();

        uint32_t time_to_ticks(double time);
        double ticks_to_time(uint32_t ticks);

        uint32_t time_to_ticks_length(double startTime, double length);
        uint32_t time_to_ticks_range(double startTime, double endTime);

        double ticks_to_time_length(uint32_t startTicks, uint32_t tickLength);
        double ticks_to_time_range(uint32_t startTicks, uint32_t endTicks);

        double get_audio_time();
        void set_pause(bool pause);

    private:
        ORCore::SmfReader m_midi;
        std::vector<TrackInfo> m_tracksInfo;
        std::vector<Track> m_tracks;
        TempoTrack m_tempoTrack;
        std::string m_path;
        uint32_t m_length;
        ORCore::Timer m_songTimer;
        ORCore::VorbisSource m_songOgg;
        ORCore::CubebOutput m_audioOut;
        double m_pauseTime;
        std::shared_ptr<spdlog::logger> m_logger;

    };

    // Functions are mainly used within the Song class
    const std::string diff_type_to_name(Difficulty diff);
    const TrackType get_track_type(std::string trackName);
    const std::string track_name_to_type(TrackType type);
} // namespace ORGame