text:
/*
 * Description: Implementation of ETS ordered_set table type with
 *              fine-grained synchronization.
 *
 * Author: 	Kjell Winblad
 *
 * "erl_db_catree.c" contains more details about the implementation.
 *
 */

#ifndef _DB_CATREE_H
#define _DB_CATREE_H

struct DbTableCATreeNode;

typedef struct {
    Eterm term;
    struct erl_off_heap_header* oh;
    Uint size;
    Eterm heap[1];
} DbRouteKey;

typedef struct {
    erts_rwmtx_t lock; /* The lock for this base node */
    erts_atomic_t lock_statistics;
    int is_valid; /* If this base node is still valid */
    TreeDbTerm *root; /* The root of the sequential tree */
    ErtsThrPrgrLaterOp free_item; /* Used when freeing using thread progress */

    char end_of_struct__;
} DbTableCATreeBaseNode;

typedef struct {
#ifdef ERTS_ENABLE_LOCK_CHECK
    Sint lc_order;
#endif
    ErtsThrPrgrLaterOp free_item; /* Used when freeing using thread progress */
    erts_mtx_t lock; /* Used when joining route nodes */
    int is_valid; /* If this route node is still valid */
    erts_atomic_t left;
    erts_atomic_t right;
    DbRouteKey key;
} DbTableCATreeRouteNode;

typedef struct DbTableCATreeNode {
    int is_base_node;
    union {
        DbTableCATreeRouteNode route;
        DbTableCATreeBaseNode base;
    } u;
} DbTableCATreeNode;

typedef struct {
    Uint pos;          /* Current position on stack */
    Uint size;         /* The size of the stack array */
    DbTableCATreeNode** array; /* The stack */
} CATreeNodeStack;

typedef struct db_table_catree {
    DbTableCommon common;

    /* CA Tree-specific fields */
    erts_atomic_t root;         /* The tree root (DbTableCATreeNode*) */
    Uint deletion;		/* Being deleted */
    int is_routing_nodes_freed;
    /* The fields below are used by delete_all_objects and
       select_delete(DeleteAll)*/
    Uint nr_of_deleted_items;
    Binary* nr_of_deleted_items_wb;
} DbTableCATree;

typedef struct {
    DbTableCATree* tb;
    Eterm next_route_key;
    DbTableCATreeNode* locked_bnode;
    DbTableCATreeNode* bnode_parent;
    int bnode_level;
    int read_only;
    DbRouteKey* search_key;
} CATreeRootIterator;

void db_initialize_catree(void);

int db_create_catree(Process *p, DbTable *tbl);

TreeDbTerm** catree_find_root(Eterm key, CATreeRootIterator*);

TreeDbTerm** catree_find_next_from_pb_key_root(Eterm key, CATreeRootIterator*);
TreeDbTerm** catree_find_prev_from_pb_key_root(Eterm key, CATreeRootIterator*);
TreeDbTerm** catree_find_nextprev_root(CATreeRootIterator*, int next, Eterm* keyp);
TreeDbTerm** catree_find_next_root(CATreeRootIterator*, Eterm* keyp);
TreeDbTerm** catree_find_prev_root(CATreeRootIterator*, Eterm* keyp);
TreeDbTerm** catree_find_first_root(CATreeRootIterator*);
TreeDbTerm** catree_find_last_root(CATreeRootIterator*);

#ifdef ERTS_ENABLE_LOCK_COUNT
void erts_lcnt_enable_db_catree_lock_count(DbTableCATree *tb, int enable);
#endif

void db_catree_force_split(DbTableCATree*, int on);
void db_catree_debug_random_split_join(DbTableCATree*, int on);

typedef struct {
    Uint route_nodes;
    Uint base_nodes;
    Uint max_depth;
} DbCATreeStats;
void db_calc_stats_catree(DbTableCATree*, DbCATreeStats*);
void
erts_db_foreach_thr_prgr_offheap_catree(void (*func)(ErlOffHeap *, void *),
                                        void *arg);

#endif /* _DB_CATREE_H */

redpajama_set_name: RedPajamaGithub


text:
"""
    SoftLayer.tests.managers.ticket_tests
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :license: MIT, see LICENSE for more details.
"""
import SoftLayer
from SoftLayer import fixtures
from SoftLayer import testing

class TicketTests(testing.TestCase):

    def set_up(self):
        self.ticket = SoftLayer.TicketManager(self.client)

    def test_list_tickets(self):
        results = self.ticket.list_tickets()

        for result in results:
            self.assertIn(result['id'], [100, 101, 102])
        self.assert_called_with('SoftLayer_Account', 'getTickets')

    def test_list_tickets_all(self):
        results = self.ticket.list_tickets(open_status=True,
                                           closed_status=True)

        for result in results:
            self.assertIn(result['id'], [100, 101, 102])
        self.assert_called_with('SoftLayer_Account', 'getTickets')

    def test_list_tickets_open(self):
        results = self.ticket.list_tickets(open_status=True,
                                           closed_status=False)
        for result in results:
            self.assertIn(result['id'], [102])
        self.assert_called_with('SoftLayer_Account', 'getOpenTickets')

    def test_list_tickets_closed(self):
        results = self.ticket.list_tickets(open_status=False,
                                           closed_status=True)
        for result in results:
            self.assertIn(result['id'], [100, 101])
        self.assert_called_with('SoftLayer_Account', 'getClosedTickets')

    def test_list_tickets_false(self):
        exception = self.assertRaises(ValueError,
                                      self.ticket.list_tickets,
                                      open_status=False,
                                      closed_status=False)

        self.assertEqual('open_status and closed_status cannot both be False', str(exception))

    def test_list_subjects(self):
        list_expected_ids = [1001, 1002, 1003, 1004, 1005]

        results = self.ticket.list_subjects()
        for result in results:
            self.assertIn(result['id'], list_expected_ids)

    def test_get_instance(self):
        result = self.ticket.get_ticket(100)

        self.assertEqual(result, fixtures.SoftLayer_Ticket.getObject)
        self.assert_called_with('SoftLayer_Ticket', 'getObject',
                                identifier=100)

    def test_create_ticket(self):
        self.ticket.create_ticket(
            title="Cloud Instance Cancellation - 08/01/13",
            body="body",
            subject=1004)

        args = ({"assignedUserId": 12345,
                 "subjectId": 1004,
                 "title": "Cloud Instance Cancellation - 08/01/13"},
                "body")
        self.assert_called_with('SoftLayer_Ticket', 'createStandardTicket',
                                args=args)

    def test_update_ticket(self):
        # test a full update
        self.ticket.update_ticket(100, body='Update1')
        self.assert_called_with('SoftLayer_Ticket', 'addUpdate',
                                args=({'entry': 'Update1'},),
                                identifier=100)

    def test_attach_hardware(self):
        self.ticket.attach_hardware(100, 123)
        self.assert_called_with('SoftLayer_Ticket', 'addAttachedHardware',
                                args=(123,),
                                identifier=100)

    def test_attach_virtual_server(self):
        self.ticket.attach_virtual_server(100, 123)
        self.assert_called_with('SoftLayer_Ticket', 'addAttachedVirtualGuest',
                                args=(123,),
                                identifier=100)

    def test_detach_hardware(self):
        self.ticket.detach_hardware(100, 123)
        self.assert_called_with('SoftLayer_Ticket', 'removeAttachedHardware',
                                args=(123,),
                                identifier=100)

    def test_detach_virtual_server(self):
        self.ticket.detach_virtual_server(100, 123)
        self.assert_called_with('SoftLayer_Ticket',
                                'removeAttachedVirtualGuest',
                                args=(123,),
                                identifier=100)


text:
package dataMgmt;

/**
 * The status of a user associated with a project.
 * Created by fahslaj on 5/3/2016.
 */
public enum OnlineStatus {
    CONNECTED,
    NOT_CONNECTED
}


text:
@interface RootViewController ()

@end

@implementation RootViewController

- (IBAction)pushButton_tapped:(UIButton *)sender {
	UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
	[self.navigationController pushViewController:vc animated:YES];
}

@end


text:
/*
   THE FOLLOWING FUNCTIONS MAY NEED TO BE CHANGED
*/

// A window global for our game root variable.
var game = {};
// A window global for our id, which we can use to look ourselves up
var my_id = null;
// Keeps track of whether player is paying attention...
var visible;
var active_keys = [];
var speed_change = "none";
var started = false;
var ending = false;

// what happens when you press 'left'?
left_turn = function() {
    var self = game.get_player(my_id);
    self.angle = (Number(self.angle) - 5) % 360;
};

// what happens when you press 'left'?
right_turn = function() {
    var self = game.get_player(my_id);
    self.angle = (Number(self.angle) + 5) % 360;
};

client_ondisconnect = function(data) {
    // Redirect to exit survey
    console.log("server booted")
    if(game.get_player(my_id).kicked) {
        var URL = 'http://projects.csail.mit.edu/ci/turk/forms/away.html';
    } else if(game.get_player(my_id).inactive) {
        var URL = 'http://projects.csail.mit.edu/ci/turk/forms/error.html?id=' + my_id;
    } else if(game.get_player(my_id).lagging) {
        var URL = 'http://projects.csail.mit.edu/ci/turk/forms/latency.html?id=' + my_id;
    } else {
	var URL = 'http://projects.csail.mit.edu/ci/turk/forms/end.html?id=' + my_id;
    }
    window.location.replace(URL);
};

/*
Note: If you add some new variable to your game that must be shared
  across server and client, add it both here and the server_send_update
  function in game.core.js to make sure it syncs

Explanation: This function is at the center of the problem of
  networking -- everybody has different INSTANCES of the game. The
  server has its own, and both players have theirs too. This can get
  confusing because the server will update a variable, and the variable
  of the same name won't change in the clients (because they have a
  different instance of it). To make sure everybody's on the same page,
  the server regularly sends news about its variables to the clients so
  that they can update their variables to reflect changes.
*/
client_onserverupdate_received = function(data){

    // Update client versions of variables with data received from
    // server_send_update function in game.core.js
    if(data.players) {
        _.map(_.zip(data.players, game.players),
            function(z){
                z[1].id = z[0].id
                if (z[0].player == null) {
                    z[1].player = null
                } else {
                    var s_player = z[0].player
                    var l_player = z[1].player
                    if(z[0].id != my_id || l_player.angle == null)
			l_player.angle = s_player.angle
                    l_player.curr_background = s_player.cbg
		    l_player.total_points = s_player.tot
                    l_player.pos = game.pos(s_player.pos)
                    l_player.speed = s_player.speed
		    l_player.onwall = s_player.onwall
                    l_player.kicked = s_player.kicked
                    l_player.inactive = s_player.inactive
                    l_player.lagging = s_player.lagging
                }
            })
    }

    game.game_started = data.gs;
    game.players_threshold = data.pt;
    game.player_count = data.pc;
    game.waiting_remaining = data.wr;

};

// This is where clients parse socket.io messages from the server. If
// you want to add another event (labeled 'x', say), just add another
// case here, then call

//          this.instance.player_host.send("s.x. <data>")

// The corresponding function where the server parses messages from
// clients, look for "server_onMessage" in game.server.js.
client_onMessage = function(data) {

    var commands = data.split('.');
    var command = commands[0];
    var subcommand = commands[1] || null;
    var commanddata = commands[2] || null;

    switch(command) {
    case 's': //server message

        switch(subcommand) {
	case 'end' :
	    // Redirect to exit survey
	    console.log("received end message...")
	    var URL = 'http://projects.csail.mit.edu/ci/turk/forms/end.html?id=' + my_id;
	    window.location.replace(URL); break;
        case 'alert' : // Not in database, so you can't play...
            alert('You did not enter an ID');
            window.location.replace('http://nodejs.org'); break;
        case 'join' : //join a game requested
            var num_players = commanddata;
            client_onjoingame(num_players); break;
        case 'add_player' : // New player joined... Need to add them to our list.
            console.log("adding player" + commanddata)
            game.players.push({id: commanddata, player: new game_player(game)}); break;
        case 'begin_game' :
            client_newgame(); break;
        case 'blink' : //blink title
            flashTitle("GO!");  break;
        }
        break;
    }
};

// Restarts things on the client side. Necessary for iterated games.
client_newgame = function() {
    // Initiate countdown (with timeouts)
    //game.get_player(my_id).angle = null;
    started = true;
    client_countdown();
};

client_countdown = function() {
    var player = game.get_player(my_id);
    player.message = 'Begin in 3...';
    setTimeout(function(){player.message = 'Begin in 2...';},
               1000);
    setTimeout(function(){player.message = 'Begin in 1...';},
               2000);
    setTimeout(function(){
        player.message = 'GO!';
        game.start_time = new Date();},
	3000);
    setTimeout(function(){player.message = '';},
               4000);
}

client_update = function() {
    var player = game.get_player(my_id);

    //Clear the screen area
    game.ctx.clearRect(0,0,485,280);

    // Alter speeds
    if (speed_change != "none") {
        player.speed = speed_change == "up" ? game.max_speed : game.min_speed;
        game.socket.send("s." + String(player.speed).replace(/\./g,'-'));
        speed_change = "none"
    }

    // Turn if key is still being held... Don't do anything if both are held
    if (active_keys.length == 1) {
        if(_.contains(active_keys, 'right')) right_turn();
        if(_.contains(active_keys, 'left')) left_turn() ;
    }

    //Draw opponent next
    _.map(game.get_others(my_id), function(p){
        draw_player(game, p.player)
	draw_label(game, p.player, "Player " + p.id.slice(0,4))
    })

    // Draw points scoreboard
    $("#cumulative_bonus").html("Total bonus so far: $" + (player.total_points).fixed(2));

    onwall = player.onwall;
    if(onwall) {
	$("#curr_bonus").html("Current Score: 0%");
    } else {
	if(game.game_started) {
	    $("#curr_bonus").html("Current Score: " + Math.floor(player.curr_background*100) + "%");
	} else {
	    $("#curr_bonus").html("Current Score: ---");
	}
    }

    if(!started) {
	var left = timeRemaining(game.waiting_remaining, game.waiting_room_limit)
	var diff = game.players_threshold - game.player_count
	//game.get_player(my_id).message = 'Waiting for ' + diff + ' more players or ' + left['t'] + ' more ' + left['unit'] + '.';
    }

    if(game.game_started) {
	var left = new Date() - game.start_time;
	if((game.round_length*60 - Math.floor(left/1000)) < 6) {
	    var remainder = game.round_length*60 - Math.floor(left/1000);
	    if(remainder < 0)
		remainder = 0
	    player.message = 'Ending in ' + remainder;
	}
	left = timeRemaining(left, game.round_length);
	// Draw time remaining
	$("#time").html("Time remaining: " + left['t'] + " " + left['unit']);
    } else {
	$("#time").html('You are in the waiting room.');
    }

    //And then we draw ourself so we're always in front
    if(player.pos) {
	draw_player(game, player)
	draw_label(game, player, "YOU");
    }

};

var timeRemaining = function(remaining, limit) {
    var time_remaining = limit - Math.floor(remaining / (1000*60));
    if(time_remaining > 1) {
	return {t: time_remaining, unit: 'minutes', actual: (limit - remaining/1000)}
    } else {
	time_remaining = limit - Math.floor(remaining / (1000 * 60)*6)/6
	time_remaining = Math.max(Math.floor(time_remaining*6)*10, 10)
	return {t: time_remaining, unit: 'seconds', actual: (limit - remaining/1000)}
    }

}

var percentColors = [
//    { pct: 0.0, color: { r: 0xff, g: 0x00, b: 0 } },
    { pct: 0.0, color: { r: 0xff, g: 0xff, b: 0xff } },
    { pct: 1.0, color: { r: 0x00, g: 0xff, b: 0 } } ];

var getColorForPercentage = function(pct) {
    for (var i = 0; i < percentColors.length; i++) {
        if (pct <= percentColors[i].pct) {
            var lower = percentColors[i - 1] || { pct: 0.1, color: { r: 0x0, g: 0x00, b: 0 } };
            var upper = percentColors[i];
            var range = upper.pct - lower.pct;
            var rangePct = (pct - lower.pct) / range;
            var pctLower = 1 - rangePct;
            var pctUpper = rangePct;
            var color = {
                r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper),
                g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper),
                b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper)
            };
            return 'rgb(' + [color.r, color.g, color.b].join(',') + ')';
        }
    }
}

/*
  The following code should NOT need to be changed
*/

// When loading the page, we store references to our
// drawing canvases, and initiate a game instance.
window.onload = function(){
    //Create our game client instance.
    game = new game_core();

    //Connect to the socket.io server!
    client_connect_to_server(game);

    //Fetch the viewport
    game.viewport = document.getElementById('viewport');

    //Adjust its size
    game.viewport.width = game.world.width;
    game.viewport.height = game.world.height;

    // Keep track of which keys are being pressed. Keys fire continuously while held.
    KeyboardJS.on('left',
	function(){ // Only notify on FIRST press
	    if(!_.contains(active_keys, 'left')) {
		active_keys.push('left');
	    }
	},
	function(){ // Only notify on first release
	    if(_.contains(active_keys, 'left')) {
		game.socket.send('a.' + game.get_player(my_id).angle)
	    }
	    active_keys = _.without(active_keys, 'left');});
    KeyboardJS.on('right',
        function(){ // Only notify on first press
	    if(!_.contains(active_keys, 'right')) {
		active_keys.push('right');
	    }
	},
        function(){ // Only notify on first release
	    if(_.contains(active_keys, 'right')) {
		game.socket.send('a.' + game.get_player(my_id).angle)
	    }
	    active_keys = _.without(active_keys, 'right');})
    KeyboardJS.on('space',
        function(){speed_change = "up"},
        function(){speed_change = "down"})

    //Fetch the rendering contexts
    game.ctx = game.viewport.getContext('2d');

    //Set the draw style for the font
    game.ctx.font = '11px "Helvetica"';

    //Finally, start the loop
    game.update();
};

// Associates callback functions corresponding to different socket messages
client_connect_to_server = function(game) {
    //Store a local reference to our connection to the server
    game.socket = io.connect();

    //When we connect, we are not 'connected' until we have a server id
    //and are placed in a game by the server. The server sends us a message for that.
    game.socket.on('connect', function(){
//        game.state = 'connecting';
    }.bind(game));

    game.socket.on('ping', function(data){
	    game.socket.send('pong.' + data.sendTime + "." + data.tick_num)})
    //Sent when we are disconnected (network, server down, etc)
    game.socket.on('disconnect', client_ondisconnect.bind(game));
    //Sent each tick of the server simulation. This is our authoritive update
    game.socket.on('onserverupdate', client_onserverupdate_received);
    //Handle when we connect to the server, showing state and storing id's.
    game.socket.on('onconnected', client_onconnected.bind(game));
    //On message from the server, we parse the commands and send it to the handlers
    game.socket.on('message', client_onMessage.bind(game));
};

client_onconnected = function(data) {
    //The server responded that we are now in a game,
    //this lets us store the information about ourselves
    // so that we remember who we are.
    my_id = data.id;
    game.players[0].id = my_id;
    game.get_player(my_id).online = true;
};

client_onjoingame = function(num_players) {
    // Need client to know how many players there are, so they can set up the appropriate data structure
    _.map(_.range(num_players - 1), function(i){game.players.unshift({id: null, player: new game_player(game)})});
    // Set self color, leave others default white
    game.get_player(my_id).color = game.self_color;
    // Start 'em moving
    game.get_player(my_id).speed = game.min_speed;
    game.get_player(my_id).message = 'Please remain active while you wait.';
};

// Automatically registers whether user has switched tabs...
(function() {
    document.hidden = hidden = "hidden";

    // Standards:
    if (hidden in document)
        document.addEventListener("visibilitychange", onchange);
    else if ((hidden = "mozHidden") in document)
        document.addEventListener("mozvisibilitychange", onchange);
    else if ((hidden = "webkitHidden") in document)
        document.addEventListener("webkitvisibilitychange", onchange);
    else if ((hidden = "msHidden") in document)
        document.addEventListener("msvisibilitychange", onchange);
    // IE 9 and lower:
    else if ('onfocusin' in document)
        document.onfocusin = document.onfocusout = onchange;
    // All others:
    else
        window.onpageshow = window.onpagehide = window.onfocus
             = window.onblur = onchange;
})();

function onchange (evt) {
    var v = 'visible', h = 'hidden',
    evtMap = {
        focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
    };
    evt = evt || window.event;
    if (evt.type in evtMap) {
        document.body.className = evtMap[evt.type];
    } else {
        document.body.className = evt.target.hidden ? "hidden" : "visible";
    }
    visible = document.body.className;
    game.socket.send("h." + document.body.className);
};

// Flashes title to notify user that game has started
(function () {

    var original = document.title;
    var timeout;

    window.flashTitle = function (newMsg, howManyTimes) {
        function step() {
            document.title = (document.title == original) ? newMsg : original;
            if (visible == "hidden") {
                timeout = setTimeout(step, 500);
            } else {
                document.title = original;
            }
        };
        cancelFlashTitle(timeout);
        step();
    };

window.cancelFlashTitle = function (timeout) {
    clearTimeout(timeout);
    document.title = original;
};

}());


text:
namespace Microsoft.Azure.Management.DigitalTwins.Models
{
    using System.Collections.Generic;

    public partial class DigitalTwinsDescription
    {
        /// <summary>
        /// Initializes a new instance of the DigitalTwinsDescription class.
        /// </summary>
        /// <param name="location">The resource location.</param>
        /// <param name="id">The resource identifier.</param>
        /// <param name="name">The resource name.</param>
        /// <param name="type">The resource type.</param>
        /// <param name="tags">The resource tags.</param>
        /// <param name="identity">The managed identity for the
        /// DigitalTwinsInstance.</param>
        /// <param name="systemData">Metadata pertaining to creation and last
        /// modification of the DigitalTwinsInstance.</param>
        /// <param name="createdTime">Time when DigitalTwinsInstance was
        /// created.</param>
        /// <param name="lastUpdatedTime">Time when DigitalTwinsInstance was
        /// updated.</param>
        /// <param name="provisioningState">The provisioning state. Possible
        /// values include: 'Provisioning', 'Deleting', 'Updating',
        /// 'Succeeded', 'Failed', 'Canceled', 'Deleted', 'Warning',
        /// 'Suspending', 'Restoring', 'Moving'</param>
        /// <param name="hostName">Api endpoint to work with
        /// DigitalTwinsInstance.</param>
        /// <param name="privateEndpointConnections">The private endpoint
        /// connections.</param>
        /// <param name="publicNetworkAccess">Public network access for the
        /// DigitalTwinsInstance. Possible values include: 'Enabled',
        /// 'Disabled'</param>
        public DigitalTwinsDescription(string location, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), DigitalTwinsIdentity identity = default(DigitalTwinsIdentity), System.DateTime? createdTime = default(System.DateTime?), System.DateTime? lastUpdatedTime = default(System.DateTime?), string provisioningState = default(string), string hostName = default(string), IList<PrivateEndpointConnection> privateEndpointConnections = default(IList<PrivateEndpointConnection>), string publicNetworkAccess = default(string), SystemData systemData = default(SystemData))
            : base(location, id, name, type, tags, identity, systemData)
        {
            CreatedTime = createdTime;
            LastUpdatedTime = lastUpdatedTime;
            ProvisioningState = provisioningState;
            HostName = hostName;
            PrivateEndpointConnections = privateEndpointConnections;
            PublicNetworkAccess = publicNetworkAccess;
            CustomInit();
        }
    }
}


text:
import Vue from 'vue'

// ElementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import locale from 'element-ui/lib/locale/lang/en'

// Graphs
import TPHGraphs from './tphgraphs.vue'

document.addEventListener("DOMContentLoaded", function() {
    Vue.use(ElementUI, { locale })

    new Vue({
        el: '#bme280-web',
        render: h => h(TPHGraphs)
    });
});


text:
#ifndef GLM_GTX_constants
#define GLM_GTX_constants GLM_VERSION

#include "../gtc/constants.hpp"

#if(defined(GLM_MESSAGES))
#	pragma message("GLM: GLM_GTX_constants extension is deprecated, include GLM_GTC_constants (glm/gtc/constants.hpp) instead")
#endif

#endif//GLM_GTX_constants


text:
package art;

import java.util.*;

/**
 * Class:   ART1 - implementation of Adaptive Resonance Theory 1
 * Author:  Martin Veselovsky
 * Date:    28.10.2014
 * Info:    Classification of binary input vectors depending on vigilance
 *          parameter (limit of similarity) to in advance unknown number of classes.
 */
public class ART1 {

    // lists of neurons weights
    private List<double[]> b;   // bottom-up
    private List<int[]>    t;   // top-down

    private int n;      // number of input neurons / length of input
    private int m;      // number of output neurons

    private double vigilance = 0.8;     // limit of similarity
    private double similarity = 0.0;    // last step similarity

    private static int step_count = 0;
    private Boolean logging = true;

    /**
     * Constructor
     */
    public ART1() {
    }

    /**
     * Initialization of neurons weights
     */
    public void init(int n) {
        logLN("Initialization");

        this.n = n; // n input neurons (n == length of input vector)
        this.m = 1; // 1 output neuron in the beginning

        b = new ArrayList<double[]>();  // bottom-up
        t = new ArrayList<int[]>();     // top-down

        // init b weights
        double[] wb = new double[n];
        double num = 1.0 / (n + 1);
        Arrays.fill(wb, num);
        b.add(wb);

        // init t weights
        int[] wt = new int[n];
        Arrays.fill(wt, 1);
        t.add(wt);

        write();
    }

    /**
     * Learn neurons on testing dataset
     */
    public void test_adapt() {

        int[][] input = {{1,1,0,0,0,0,1}, {0,0,1,1,1,1,0}, {1,0,1,1,1,1,0}, {0,0,0,1,1,1,0}, {1,1,0,1,1,1,0}};
        init(input.length);

        // loop through input data
        for (int[] in: input) {
            step(in);
        }
    }

    /**
     * Process one input vector
     * @param in input vector which length is n
     * @return number of neuron to which was input assigned
     */
    public int step(int[] in) {

        step_count++;
        logLN("===========");
        logLN("> STEP: " + step_count);
        logLN("input vector:\n" + print_input(in));

        int assigned_neuron = -1;

        // create union with output neurons to process
        Set<Integer> A = new HashSet<Integer>();
        for (int i = 0; i < m; i++) A.add(i);   // all neurons are in at the start

        while (!A.isEmpty()) {

            // find neuron with largest y - winner
            int winner = 0;
            double y = 0, ymax = 0;
            for (int j: A) {                // through output neurons in A
                for (int i = 0; i < n; i++) // through all it's inputs
                    y += b.get(j)[i] * in[i];
                if (y > ymax) {
                    ymax = y;
                    winner = j;
                }
            }
            logLN("Winning neuron: " + winner);

            // compare similarity
            double sum_ti = 0;
            double sum_i  = 0;
            for (int i = 0; i < n; i++) {
                sum_ti += t.get(winner)[i] * in[i];
                sum_i += in[i];
            }
            similarity = sum_ti/sum_i;

            logLN("Similarity: " + similarity + "  (vigilance: " + vigilance + ")");

            // vigilance test
            if (similarity >= vigilance) {

                // vectors are similar enough, update weights
                for (int i = 0; i < n; i++)
                    b.get(winner)[i] = (t.get(winner)[i] * in[i]) / (0.5 + sum_ti);
                for (int i = 0; i < n; i++)
                    t.get(winner)[i] = t.get(winner)[i] * in[i];

                A.clear();  // break loop, get next input

                logLN("Neuron " + winner + " assigned to input vector.");
                assigned_neuron = winner;

            } else {
                // vectors are not similar enough, remove neuron from Set
                A.remove(winner);
                logLN("Neuron " + winner + " is not similar enough to input vector.");

                // create new neuron
                if (A.isEmpty()) {

                    // calculate b weights
                    double[] wb = new double[n];
                    for (int i = 0; i < n; i++)
                        wb[i] = in[i] / (0.5 + sum_i);
                    b.add(wb);

                    // set t weights same as input
                    int[] wt = new int[n];
                    System.arraycopy(in, 0, wt, 0, n);
                    t.add(wt);

                    logLN("Neuron " + m + " created for input vector");
                    assigned_neuron = m;
                    similarity = 1.0;   // for printings, useless for algorithm
                    m++;
                }
            }
        }
        write();

//      // waiting for key press
//        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//        try {
//            br.readLine();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        return assigned_neuron;
    }

    /**
     * Print all neurons weights
     * b - bottom-up weights (double)
     * t - top-down weights (int 0/1)
     */
    public void write() {
        logLN("Bottom-up");
        for (double[] i: b) {
            for (double j : i)
                log(" " + j);
            logLN("");
        }

        logLN("Top-down");
        for (int[] i: t) {
            int sum = 0;
            for (int j : i) {
                log(Integer.toString(j));
                sum += j;
            }
            logLN(" Sum t: " + sum);
        }
    }

    /**
     * Convert input vector as int to string
     * @param in input vector
     * @return string representation of input
     */
    public String print_input(int[] in) {
        String x = "";
        for (int i = 0; i < n; i++)
            x += in[i];
        return x;
    }

    public void logLN(String s) {
        if (logging)
            System.out.println(s);
    }

    public void log(String s) {
        if (logging)
            System.out.print(s);
    }

    // getters
    /**
     * @return list of bottom-up weights (double)
     */
    public List<double[]> getB() {
        return b;
    }
    /**
     * @return list of top-down weights (int 0/1)
     */
    public List<int[]> getT() {
        return t;
    }
    /**
     * @return number of input neurons / size of input vector
     */
    public int getN() {
        return n;
    }
    /**
     * @return number of output neurons
     */
    public int getM() {
        return m;
    }
    /**
     * @return vigilance parameter - limit of similarity
     */
    public double getVigilance() {
        return vigilance;
    }
    /**
     * @return last computed similarity between output neuron and input
     */
    public double getSimilarity() {
        return similarity;
    }

    // setters
    /**
     * @param value vigilance in range <0,1>
     */
    public void setVigilance(double value) {
        this.vigilance = value;
    }
    /**
     * @param logging allow or decline logging
     */
    public void setLogging(Boolean logging) {
        this.logging = logging;
    }
}


text:
sap.ui.define([
	"sap/base/Log",
	"sap/ui/model/SimpleType",
	"sap/ui/model/Type"
], function (Log, SimpleType, Type) {
	/*global QUnit*/
	"use strict";

	//*********************************************************************************************
	QUnit.module("sap.ui.model.SimpleType", {
		beforeEach : function () {
			this.oLogMock = this.mock(Log);
			this.oLogMock.expects("warning").never();
			this.oLogMock.expects("error").never();
		}
	});

	//*********************************************************************************************
	QUnit.test("basics", function (assert) {
		var oType = new SimpleType();

		assert.ok(oType instanceof Type, "is a Type");
		assert.ok(oType instanceof SimpleType, "is a SimpleType");
		assert.strictEqual(oType.getName(), "SimpleType", "type name");
		assert.deepEqual(oType.oFormatOptions, {}, "default format options");
		assert.deepEqual(oType.oConstraints, {}, "default constraints");
	});

	//*********************************************************************************************
	QUnit.test("c'tor sets constraints and format options", function (assert) {
		var oConstraints = "~oConstraints",
			oFormatOptions = "~oFormatOptions",
			oType;

		// code under test
		oType = new SimpleType(oFormatOptions, oConstraints);

		assert.strictEqual(oType.oConstraints, oConstraints);
		assert.strictEqual(oType.oFormatOptions, oFormatOptions);

		// code under test
		oType = new SimpleType(null, null);

		assert.deepEqual(oType.oConstraints, {});
		assert.deepEqual(oType.oFormatOptions, {});
	});

	//*********************************************************************************************
	QUnit.test("getConstraints: with and w/o constraints", function (assert) {
		var oConstraintsResult,
			oQux = {qux : "quux"},
			oType = new SimpleType(undefined, {foo : "bar", baz : oQux});

		// code under test
		oConstraintsResult = oType.getConstraints();

		assert.deepEqual(oConstraintsResult, {foo : "bar", baz : oQux});
		assert.notStrictEqual(oConstraintsResult, oType.oConstraints);
		assert.notStrictEqual(oConstraintsResult.baz, oQux);

		// code under test
		assert.deepEqual(new SimpleType().getConstraints(), {});
	});

	//*********************************************************************************************
	QUnit.test("getFormatOptions: with and w/o format options", function (assert) {
		var oFormatOptionsResult,
			oQux = {qux : "quux"},
			oType = new SimpleType({foo : "bar", baz : oQux});

		// code under test
		oFormatOptionsResult = oType.getFormatOptions();

		assert.deepEqual(oFormatOptionsResult, {foo : "bar", baz : oQux});
		assert.notStrictEqual(oFormatOptionsResult, oType.oFormatOptions);
		assert.notStrictEqual(oFormatOptionsResult.baz, oQux);

		// code under test
		assert.deepEqual(new SimpleType().getFormatOptions(), {});
	});
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace MineSweeper.Graphics
{
    public static class GraphicsEngine
    {
        static BasicEffect effect;
        public static RasterizerState s_Regular = new RasterizerState();
        public static RasterizerState s_ScissorsOn = new RasterizerState() { ScissorTestEnable = true };

        public static void Initialize()
        {
            effect = new BasicEffect(MineSweeper.graphics.GraphicsDevice);
            effect.VertexColorEnabled = true;
            effect.Projection = Matrix.CreateOrthographicOffCenter
                (0, MineSweeper.graphics.GraphicsDevice.Viewport.Width,
                MineSweeper.graphics.GraphicsDevice.Viewport.Height, 0,
                0, 1);

            GUI.GUIEngine.Initialize();
        }

        public static void LoadContent(ContentManager content)
        {
            Game.Tiles.TileSquare.tileFont = content.Load<SpriteFont>("Fonts/TileFont");
            GUI.Elements.Button.font = content.Load<SpriteFont>("Fonts/ButtonFont");
            GUI.Elements.TextBox.font = content.Load<SpriteFont>("Fonts/ButtonFont");
            GUI.Elements.Label.defaultFont = content.Load<SpriteFont>("Fonts/ButtonFont");

            Game.Tiles.TileSquare.texture = content.Load<Texture2D>("Game/square");
            Entity.EntityManager.sprites = content.Load<Texture2D>("Game/entityes");
            GUI.Elements.Button.texture = content.Load<Texture2D>("GUI/button");
            GUI.Elements.TextBox.texture = content.Load<Texture2D>("GUI/textbox");
            GUI.Elements.Panel.texture = content.Load<Texture2D>("GUI/button");

            GUI.GUIEngine.LoadContent(content);
        }

        public static void Draw()
        {
            MineSweeper.spriteBatch.Begin();
            if (MineSweeper.IsField())
            {
                MineSweeper.gameField.Draw();
                Entity.EntityManager.Draw();
            }
            GUI.GUIEngine.Draw();
            MineSweeper.spriteBatch.End();
        }
    }
}


text:
<?php

namespace Torneos\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Decks\Form\DecksForm;
use Decks\Model\Entity\Cards,
Decks\Model\Entity\Decks,
Decks\Model\Entity\DeckCards,
Decks\Model\Entity\Tournaments;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }

    public function verAction()
    {
        return new ViewModel();
    }
}


text:
require 'spec_helper'

describe Adsentry::Aggregator do

  before(:each) do
    $ADSENTRY_REDIS.flushdb
  end

  it "registers a queue with itself" do
    Adsentry::Aggregator.register("some_queue")
  end

  it "recites the queues as a list" do
    Adsentry::Aggregator.register("some_queue")
    Adsentry::Aggregator.recite.should == ["some_queue"]
  end

  it "reports a hash of queue sizes and members" do
    Adsentry::Annalist.new('some_queue').insert('12345')
    Adsentry::Aggregator.report.should == [{name: "some_queue", count: 1, members: ['12345']}]
  end
end


text:
#ifndef _gkBone_h_
#define _gkBone_h_

#include "gkSerialize.h"

class gkBone
{
public:
	typedef utArray<gkBone*> BoneList;

public:

	gkBone(const gkString& name);
	~gkBone();

	void setParent(gkBone* bone);

	void setRestPosition(const gkTransformState& st);

	void applyChannelTransform(const gkTransformState& channel, gkScalar weight);
	void applyPoseTransform(const gkTransformState& pose);
	void applyRootTransform(const gkTransformState& root);

	const gkTransformState&  getRest(void)      {return m_bind;}

	gkTransformState&        getPose(void)      {return m_pose;}

	gkBone*                  getParent(void)    {return m_parent;}
	BoneList&                getChildren(void)  {return m_children;}

	const gkString&          getName(void)      {return m_name;}

	// Internal use
	UTsize                  _getBoneIndex(void);
	void                    _setOgreBone(Ogre::Bone* bone);

private:

	const gkString m_name;

	Ogre::Bone* m_bone;

	gkBone*      m_parent;
	BoneList    m_children;

	gkTransformState m_bind;

	// The current pose matrix, calculated in applyChannelTransform
	gkTransformState m_pose;
};

#endif//_gkBone_h_


text:
(function () {
	'use strict';
	stControllers.controller('TrackCtrl', ['$scope', '$http',
		function ($scope, $http) {
			$scope.filePath = '/Users/cpollet/Downloads/sample.fit';

			$scope.map = {
				center: {
					latitude: 46.2,
					longitude: 6.15
				},
				options: {
					mapTypeId: google.maps.MapTypeId.TERRAIN
				},
				zoom: 12,
				events: {
					tilesloaded: function (mapInstance) {
						$scope.$apply(function () {
							$scope.mapInstance = mapInstance;
						});
					}
				}
			};

			$scope.updateRoute = function () {
				$http.get('api/v1/track?filePath=' + $scope.filePath)
					.success(function (data) {
						$scope.track = data;

						var trackPathCoordinates = [];

						for (var i = 0; i < data['trackPoints'].length; i++) {
							var latLng = new google.maps.LatLng(
								data['trackPoints'][i]['latitude'],
								data['trackPoints'][i]['longitude']
							);
							trackPathCoordinates.push(latLng);
						}

						var trackPath = new google.maps.Polyline({
							path: trackPathCoordinates,
							geodesic: true,
							strokeColor: '#FF0000',
							strokeOpacity: 1.0,
							strokeWeight: 2
						});

						trackPath.setMap($scope.mapInstance);
					});
			};

			$scope.updateMap = function () {
				window.setTimeout(function () {
					google.maps.event.trigger($scope.mapInstance, 'resize');
					$scope.mapInstance.setCenter(new google.maps.LatLng($scope.map.center.latitude, $scope.map.center.longitude));
				}, 100);
			}
		}
	]);
})();


text:
@implementation NSFetchRequest (BBCoreDataExtensions)

+ (NSFetchRequest *)BB_fetchRequestForEntityName:(NSString *)entityName predicate:(NSPredicate *)predicate sortDescriptors:(NSArray *)sortDescriptors limit:(NSUInteger)limit offset:(NSUInteger)offset; {
    NSParameterAssert(entityName);

    NSFetchRequest *retval = [[NSFetchRequest alloc] initWithEntityName:entityName];

    if (predicate) {
        [retval setPredicate:predicate];
    }
    if (sortDescriptors) {
        [retval setSortDescriptors:sortDescriptors];
    }
    if (limit > 0) {
        [retval setFetchLimit:limit];
    }
    if (offset > 0) {
        [retval setFetchOffset:offset];
    }

    return retval;
}

@end


text:
object bug {

  abstract class Cap[S] {
    def init: Fig[Unit, S]
  }

  case class Foo()
  case class Fig[A, B]()

  case object Tak extends Cap[Foo] {
    def init: Fig[Unit, Foo] = Fig[Unit, Foo]()
  }
}


text:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Calendar;

public class TestCases {
    public static void main(String[] args) throws FileNotFoundException {
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
        Date StartDate = new Date(),EndDate = new Date();
        try {
            StartDate = ft.parse("2004-02-09");
        } catch (ParseException ex) {
            Logger.getLogger(TestCases.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            EndDate = ft.parse("2017-06-15");
        } catch (ParseException ex) {
            Logger.getLogger(TestCases.class.getName()).log(Level.SEVERE, null, ex);
        }
        String fileWrite = "";//Format of string is
        //ID,StartDate,EndDate,No of Days,Rate,Principal,Paid,Percentage paid
        Calendar start = Calendar.getInstance();
        start.setTime(StartDate);
        Calendar end = Calendar.getInstance();
        end.setTime(EndDate);
        int i = 1;
        for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
            // Do your job here with `date`.
            fileWrite += Integer.toString(i++);
            fileWrite += ",";

            fileWrite += ft.format(date);
            fileWrite += ",";

            int principal = ThreadLocalRandom.current().nextInt(10000, 101010101 + 1);
            fileWrite += Integer.toString(principal);
            fileWrite += ",";

            Random rand = new Random();
            float percentage = (float) (rand.nextFloat() * (100.0));
            percentage = (float) ((float) Math.round(percentage * 100.0d)/100.0d);
            double paid = (double) (principal * percentage/100.0);
            paid = (double) ((double) Math.round(paid * 100.0d)/100.0d);

            DecimalFormat df = new DecimalFormat("#");
            df.setMaximumFractionDigits(5);
            fileWrite += df.format(paid);
            fileWrite += ",";

            fileWrite += Float.toString(percentage);
            fileWrite += "\n";
        }
        System.out.println(fileWrite);
        try (PrintStream out = new PrintStream(new FileOutputStream("TestCsvData.csv"))) {
            out.print(fileWrite);
        }
        /*
        for(int i=1;i<=1000;i++){
            fileWrite += Integer.toString(i);
            fileWrite += ",";

            long random = ThreadLocalRandom.current().nextLong(StartDate.getTime(), EndDate.getTime());
            Date start = new Date(random);
            fileWrite += ft.format(start);
            fileWrite += ",";

            random = ThreadLocalRandom.current().nextLong(start.getTime(), EndDate.getTime());
            Date end = new Date(random);
            fileWrite += ft.format(end);
            fileWrite += ",";

            int diffInDays;
            diffInDays = (int)( (end.getTime() - start.getTime())/ (1000 * 60 * 60 * 24) );
            fileWrite += Integer.toString(diffInDays);
            fileWrite += ",13,";

            int principal = ThreadLocalRandom.current().nextInt(10000, 101010101 + 1);
            fileWrite += Integer.toString(principal);
            fileWrite += ",";

            Random rand = new Random();
            float percentage = (float) (rand.nextFloat() * (100.0));
            percentage = (float) ((float) Math.round(percentage * 100.0d)/100.0d);
            double paid = (double) (principal * percentage/100.0);
            paid = (double) ((double) Math.round(paid * 100.0d)/100.0d);

            DecimalFormat df = new DecimalFormat("#");
            df.setMaximumFractionDigits(5);
            fileWrite += df.format(paid);
            fileWrite += ",";

            fileWrite += Float.toString(percentage);
            fileWrite += "\n";
        }
        //System.out.println(fileWrite);
        try (PrintStream out = new PrintStream(new FileOutputStream("TestCsvData.csv"))) {
            out.print(fileWrite);

        }
        */
    }
}


text:
package space.gatt.GasaiBot;

import de.btobastian.javacord.DiscordAPI;
import de.btobastian.javacord.entities.User;
import de.btobastian.javacord.entities.message.Message;
import de.btobastian.javacord.entities.message.MessageBuilder;
import de.btobastian.javacord.entities.message.MessageDecoration;
import de.btobastian.javacord.listener.message.MessageCreateListener;
import space.gatt.JavacordCommander.Settings;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.URLConnection;

/**
* Created by Zach on 6/03/2016.
*/
public class ImageStorer {

    private HashMap<String, File> imageCache = new HashMap<>();
    private HashMap<String, String> gifCache = new HashMap<>();

    public synchronized void cacheImage(String url, String extension, String name){
        File imgf = new File(name + "." + extension);
        if (imgf.exists()){
            imageCache.put(name, imgf);
            return;
        }
        try {
            if (extension.equalsIgnoreCase("gif")){
                byte[] b = new byte[1];
                URL urlU = new URL(url);
                URLConnection urlConnection = urlU.openConnection();
                urlConnection.connect();
                DataInputStream di = new DataInputStream(urlConnection.getInputStream());

                FileOutputStream fo = new FileOutputStream(name + "." + extension);
                while (-1 != di.read(b, 0, 1))
                  fo.write(b, 0, 1);
                di.close();
                fo.close();
                imageCache.put(name, new File(name + "." + extension));
                return;
            }
            BufferedImage img = ImageIO.read(new URL(url));
            ImageIO.write(img, extension, imgf);
            imageCache.put(name, imgf);
        }catch (IOException e){
        }
    }

    public File getImage(String name){
        String[] extensions = new String[]{"png","jpg","gif","jpeg"};
        for (String e : extensions){
            File f = new File(name + "." + e);
            if (f.exists()){
                return f;
            }
        }
        return null;
    }

    @Deprecated
    public synchronized void cacheImages(){
    }
}


text:
package com.intellij.xml.breadcrumbs;

import com.intellij.application.options.editor.WebEditorOptions;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.fileTypes.FileTypeEvent;
import com.intellij.openapi.fileTypes.FileTypeListener;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileAdapter;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFilePropertyEvent;
import com.intellij.openapi.vfs.impl.http.HttpVirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiManager;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class BreadcrumbsLoaderComponent extends AbstractProjectComponent {
  public BreadcrumbsLoaderComponent(@NotNull final Project project) {
    super(project);
  }

  @Override
  @NonNls
  @NotNull
  public String getComponentName() {
    return "HtmlBreadcrumbsComponent";
  }

  @Override
  public void initComponent() {
    MessageBusConnection connection = myProject.getMessageBus().connect(myProject);
    connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new MyFileEditorManagerListener());
    connection.subscribe(WebEditorOptions.WEB_EDITOR_OPTIONS, new MyWebEditorOptionsListener());
    connection.subscribe(FileTypeManager.TOPIC, new MyFileTypeListener());

    MyVirtualFileListener listener = new MyVirtualFileListener();
    VirtualFileManager.getInstance().addVirtualFileListener(listener, myProject);
  }

  private static class MyFileEditorManagerListener extends FileEditorManagerAdapter {
    @Override
    public void fileOpened(@NotNull final FileEditorManager source, @NotNull final VirtualFile file) {
      reinitBreadcrumbsComponent(source, file, WebEditorOptions.getInstance());
    }
  }

  private class MyVirtualFileListener extends VirtualFileAdapter {
    @Override
    public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
      if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) {
        FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
        VirtualFile file = event.getFile();
        if (fileEditorManager.isFileOpen(file)) {
          reinitBreadcrumbsComponent(fileEditorManager, file, WebEditorOptions.getInstance());
        }
      }
    }
  }

  private class MyWebEditorOptionsListener implements WebEditorOptions.WebEditorOptionsListener {
    @Override
    public void breadcrumbsOptionsChanged(@NotNull WebEditorOptions options) {
      reinitBreadcrumbsInAllEditors(options);
    }
  }

  private class MyFileTypeListener extends FileTypeListener.Adapter {
    @Override
    public void fileTypesChanged(@NotNull FileTypeEvent event) {
      reinitBreadcrumbsInAllEditors(WebEditorOptions.getInstance());
    }
  }

  private void reinitBreadcrumbsInAllEditors(@NotNull WebEditorOptions options) {
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    for (VirtualFile virtualFile : fileEditorManager.getOpenFiles()) {
      reinitBreadcrumbsComponent(fileEditorManager, virtualFile, options);
    }
  }

  private static void reinitBreadcrumbsComponent(@NotNull final FileEditorManager fileEditorManager,
                                                 @NotNull VirtualFile file,
                                                 @NotNull WebEditorOptions webEditorOptions) {
    if (webEditorOptions.isBreadcrumbsEnabled() && isSuitable(fileEditorManager.getProject(), file, webEditorOptions)) {
      FileEditor[] fileEditors = fileEditorManager.getAllEditors(file);
      for (final FileEditor fileEditor : fileEditors) {
        if (fileEditor instanceof TextEditor) {
          Editor editor = ((TextEditor)fileEditor).getEditor();
          if (BreadcrumbsXmlWrapper.getBreadcrumbsComponent(editor) != null) {
            continue;
          }
          final BreadcrumbsXmlWrapper wrapper = new BreadcrumbsXmlWrapper(editor, webEditorOptions);
          final JComponent c = wrapper.getComponent();
          fileEditorManager.addTopComponent(fileEditor, c);

          Disposer.register(fileEditor, new Disposable() {
            @Override
            public void dispose() {
              disposeWrapper(fileEditorManager, fileEditor, wrapper);
            }
          });
        }
      }
    }
    else {
      removeBreadcrumbs(fileEditorManager, file);
    }
  }

  private static void removeBreadcrumbs(@NotNull FileEditorManager fileEditorManager, @NotNull VirtualFile file) {
    final FileEditor[] fileEditors = fileEditorManager.getAllEditors(file);
    for (FileEditor fileEditor : fileEditors) {
      if (fileEditor instanceof TextEditor) {
        Editor editor = ((TextEditor)fileEditor).getEditor();
        BreadcrumbsXmlWrapper wrapper = BreadcrumbsXmlWrapper.getBreadcrumbsComponent(editor);
        if (wrapper != null) {
          disposeWrapper(fileEditorManager, fileEditor, wrapper);
        }
      }
    }
  }

  private static boolean isSuitable(@NotNull Project project, @NotNull VirtualFile file, @NotNull WebEditorOptions webEditorOptions) {
    if (file instanceof HttpVirtualFile) {
      return false;
    }

    final FileViewProvider provider = PsiManager.getInstance(project).findViewProvider(file);
    return provider != null && BreadcrumbsXmlWrapper.findInfoProvider(provider, webEditorOptions) != null;
  }

  private static void disposeWrapper(@NotNull FileEditorManager fileEditorManager,
                                     @NotNull FileEditor fileEditor,
                                     @NotNull BreadcrumbsXmlWrapper wrapper) {
    fileEditorManager.removeTopComponent(fileEditor, wrapper.getComponent());
    Disposer.dispose(wrapper);
  }
}


text:
require_relative '../module'

module Snapshot
  module Fixes
    # This fix is needed due to a bug in UI Tests that creates invalid screenshots when the
    # simulator is not scaled to a 100%
    # Issue: https://github.com/fastlane/snapshot/issues/249
    # Radar: https://openradar.appspot.com/radar?id=6127019184095232

    class SimulatorZoomFix
      def self.patch
        UI.message("Patching simulators '#{config_path}' to scale to 100%")

        FastlaneCore::DeviceManager.simulators.each do |simulator|
          simulator_name = simulator.name.tr("\s", "-")
          key = "SimulatorWindowLastScale-com.apple.CoreSimulator.SimDeviceType.#{simulator_name}"

          Helper.backticks("defaults write '#{config_path}' '#{key}' '1.0'", print: FastlaneCore::Globals.verbose?)
        end
      end

      def self.config_path
        File.join(File.expand_path("~"), "Library", "Preferences", "com.apple.iphonesimulator.plist")
      end
    end
  end
end


text:
namespace base {
class SingleThreadTaskRunner;
}

namespace media {

class AudioRenderer;
class DemuxerStreamProvider;
class TimeSource;
class VideoRenderer;
class WallClockTimeSource;

class MEDIA_EXPORT RendererImpl : public Renderer {
 public:
  // Renders audio/video streams using |audio_renderer| and |video_renderer|
  // provided. All methods except for GetMediaTime() run on the |task_runner|.
  // GetMediaTime() runs on the render main thread because it's part of JS sync
  // API.
  RendererImpl(const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
               std::unique_ptr<AudioRenderer> audio_renderer,
               std::unique_ptr<VideoRenderer> video_renderer);

  ~RendererImpl() final;

  // Renderer implementation.
  void Initialize(DemuxerStreamProvider* demuxer_stream_provider,
                  RendererClient* client,
                  const PipelineStatusCB& init_cb) final;
  void SetCdm(CdmContext* cdm_context,
              const CdmAttachedCB& cdm_attached_cb) final;
  void Flush(const base::Closure& flush_cb) final;
  void StartPlayingFrom(base::TimeDelta time) final;
  void SetPlaybackRate(double playback_rate) final;
  void SetVolume(float volume) final;
  base::TimeDelta GetMediaTime() final;
  bool HasAudio() final;
  bool HasVideo() final;

  // Helper functions for testing purposes. Must be called before Initialize().
  void DisableUnderflowForTesting();
  void EnableClocklessVideoPlaybackForTesting();
  void set_time_source_for_testing(TimeSource* time_source) {
    time_source_ = time_source;
  }
  void set_video_underflow_threshold_for_testing(base::TimeDelta threshold) {
    video_underflow_threshold_ = threshold;
  }

 private:
  class RendererClientInternal;

  enum State {
    STATE_UNINITIALIZED,
    STATE_INIT_PENDING_CDM,  // Initialization is waiting for the CDM to be set.
    STATE_INITIALIZING,      // Initializing audio/video renderers.
    STATE_FLUSHING,
    STATE_PLAYING,
    STATE_ERROR
  };

  bool GetWallClockTimes(const std::vector<base::TimeDelta>& media_timestamps,
                         std::vector<base::TimeTicks>* wall_clock_times);

  bool HasEncryptedStream();

  void FinishInitialization(PipelineStatus status);

  // Helper functions and callbacks for Initialize().
  void InitializeAudioRenderer();
  void OnAudioRendererInitializeDone(PipelineStatus status);
  void InitializeVideoRenderer();
  void OnVideoRendererInitializeDone(PipelineStatus status);

  // Helper functions and callbacks for Flush().
  void FlushAudioRenderer();
  void OnAudioRendererFlushDone();
  void FlushVideoRenderer();
  void OnVideoRendererFlushDone();

  // Callback executed by filters to update statistics.
  void OnStatisticsUpdate(const PipelineStatistics& stats);

  // Collection of callback methods and helpers for tracking changes in
  // buffering state and transition from paused/underflow states and playing
  // states.
  //
  // While in the kPlaying state:
  //   - A waiting to non-waiting transition indicates preroll has completed
  //     and StartPlayback() should be called
  //   - A non-waiting to waiting transition indicates underflow has occurred
  //     and PausePlayback() should be called
  void OnBufferingStateChange(DemuxerStream::Type type,
                              BufferingState new_buffering_state);
  bool WaitingForEnoughData() const;
  void PausePlayback();
  void StartPlayback();

  // Callbacks executed when a renderer has ended.
  void OnRendererEnded(DemuxerStream::Type type);
  bool PlaybackHasEnded() const;
  void RunEndedCallbackIfNeeded();

  // Callback executed when a runtime error happens.
  void OnError(PipelineStatus error);
  void OnWaitingForDecryptionKey();
  void OnVideoNaturalSizeChange(const gfx::Size& size);
  void OnVideoOpacityChange(bool opaque);

  State state_;

  // Task runner used to execute pipeline tasks.
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;

  DemuxerStreamProvider* demuxer_stream_provider_;
  RendererClient* client_;

  // Temporary callback used for Initialize() and Flush().
  PipelineStatusCB init_cb_;
  base::Closure flush_cb_;

  std::unique_ptr<RendererClientInternal> audio_renderer_client_;
  std::unique_ptr<RendererClientInternal> video_renderer_client_;
  std::unique_ptr<AudioRenderer> audio_renderer_;
  std::unique_ptr<VideoRenderer> video_renderer_;

  // Renderer-provided time source used to control playback.
  TimeSource* time_source_;
  std::unique_ptr<WallClockTimeSource> wall_clock_time_source_;
  bool time_ticking_;
  double playback_rate_;

  // The time to start playback from after starting/seeking has completed.
  base::TimeDelta start_time_;

  BufferingState audio_buffering_state_;
  BufferingState video_buffering_state_;

  // Whether we've received the audio/video ended events.
  bool audio_ended_;
  bool video_ended_;

  CdmContext* cdm_context_;
  CdmAttachedCB pending_cdm_attached_cb_;

  bool underflow_disabled_for_testing_;
  bool clockless_video_playback_enabled_for_testing_;

  // Used to defer underflow for video when audio is present.
  base::CancelableClosure deferred_underflow_cb_;

  // The amount of time to wait before declaring underflow if the video renderer
  // runs out of data but the audio renderer still has enough.
  base::TimeDelta video_underflow_threshold_;

  base::WeakPtr<RendererImpl> weak_this_;
  base::WeakPtrFactory<RendererImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(RendererImpl);
};

}  // namespace media

#endif  // MEDIA_RENDERERS_RENDERER_IMPL_H_


text:
@class AboutViewController;

@protocol AboutViewControllerDelegate <NSObject>
@optional
- (void)aboutViewControllerDidTouch:(AboutViewController *)aboutView;
@end

@interface AboutViewController : UIViewController <UIWebViewDelegate> {
	id <AboutViewControllerDelegate> delegate;
	UIWebView *webView;
	UIBarButtonItem *buttonClose;
}

@property (nonatomic, assign) id <AboutViewControllerDelegate> delegate;
@property (nonatomic, retain) IBOutlet UIWebView *webView;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *buttonClose;

- (IBAction)buttonCloseDidTouch:(id)sender;

@end


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link rel="stylesheet" type="text/css" href="PSSTYLEREQ_1.css">
<link rel="stylesheet" type="text/css" href="SSS_STYLESHEET_1.css">
<title id="PSPAGETITLE">Enrollment Shopping Cart</title>

<input type="button" id="COPYCONSOLE" value="Copy" onclick="ptConsole2.copy();" alt="copy to clipboard" title="copy to clipboard"><input type="button" id="CLEARCONSOLE" onclick="ptConsole2.clear();" value="Clear" alt="clear console" title="clear console"><input type="button" id="HIDECONSOLE" onclick="ptConsole2.hide();" value="Hide" alt="hide console" title="hide console"><input type="button" id="CLOSECONSOLE" onclick="ptConsole2.deactive();" value="Close" alt="close console" title="close console">

<form name="win1" method="post" action="https://ses.ent.northwestern.edu/psc/caesar_1/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_CART.GBL" autocomplete="off" class="PSForm">

<input type="hidden" name="ICType" id="ICType" value="Panel">
<input type="hidden" name="ICElementNum" id="ICElementNum" value="1">
<input type="hidden" name="ICStateNum" id="ICStateNum" value="6">
<input type="hidden" name="ICAction" id="ICAction" value="None">
<input type="hidden" name="ICXPos" id="ICXPos" value="0">
<input type="hidden" name="ICYPos" id="ICYPos" value="0">
<input type="hidden" name="ResponsetoDiffFrame" id="ResponsetoDiffFrame" value="-1">
<input type="hidden" name="TargetFrameName" id="TargetFrameName" value="None">
<input type="hidden" name="GSrchRaUrl" id="GSrchRaUrl" value="None">
<input type="hidden" name="FacetPath" id="FacetPath" value="None">
<input type="hidden" name="ICFocus" id="ICFocus" value="">
<input type="hidden" name="ICSaveWarningFilter" id="ICSaveWarningFilter" value="0">
<input type="hidden" name="ICChanged" id="ICChanged" value="-1">
<input type="hidden" name="ICResubmit" id="ICResubmit" value="0">
<input type="hidden" name="ICSID" id="ICSID" value="HiRUmdOOPACGV1vZqgwPTOk7ObgS2Oelvglh56EwGyI=">
<input type="hidden" name="ICActionPrompt" id="ICActionPrompt" value="false">
<input type="hidden" name="ICFind" id="ICFind" value="">
<input type="hidden" name="ICAddCount" id="ICAddCount" value="">

<select name="DERIVED_SSTSNAV_SSTS_MAIN_GOTO$22$" id="DERIVED_SSTSNAV_SSTS_MAIN_GOTO$22$" tabindex="31" size="1" class="PSDROPDOWNLIST" style="width:148px; " onchange="addchg_win1(this);return doEdits_win1(this,'','N','N','N','N','Y','Y',0);" psnchg="0">
<option value="0050">Homepage</option>
<option value="0200">My Academics</option>
<option value="0100">Student Center</option>
<option value="0500">User Preferences</option>
<option value="9999" selected="selected">go to ...</option>
</select>

Liu Liu

Search

Enroll

Exam Schedule

My Academics

my class schedule

add

drop

swap

edit

term information

Add Classes

1. Select classes to add

To select classes for another term, select the term and click Change.

When you are satisfied with your class selections, proceed to step 2 of 3.

Proceed to Step 2 of 3

Change Term

2014 Spring | The Graduate School | Northwestern University

Open

Closed

Wait List

Add to Cart:

Enter Class Nbr

Enter

<input type="text" name="DERIVED_REGFRM1_CLASS_NBR" id="DERIVED_REGFRM1_CLASS_NBR" tabindex="66" value="" class="PSEDITBOX" style="width:35px; text-align:right; " maxlength="5" onchange="addchg_win1(this);oChange_win1=this;" psnchg="0">

Find Classes

<input type="radio" name="DERIVED_REGFRM1_SSR_CLS_SRCH_TYPE$75$" id="DERIVED_REGFRM1_SSR_CLS_SRCH_TYPE$75$" class="PSRADIOBUTTON" tabindex="68" value="06" checked="checked" onclick="setupTimeout2();doFocus_win1(this,false,true);">Class Search

Search

2014 Spring Shopping Cart

Select
Class
Days/Times
Room
Instructor
Units
Status

<input type="hidden" name="P_SELECT$chk$0" id="P_SELECT$chk$0" value="N">
<input type="checkbox" name="P_SELECT$0" id="P_SELECT$0" class="PSCHECKBOX" tabindex="101" value="Y" onclick="setupTimeout2();	this.form.P_SELECT$chk$0.value=(this.checked?'Y':'N');doFocus_win1(this,false,true);" psnchg="0">

IEMS 420-0-20

 (38610)

Th 6:00PM - 9:30PM

Ford Eng Design Cntr ITW 1350

P. Leonardi

1.00

Delete

for selected:

Proceed to Step 2 of 3

 My 2014 Spring Class Schedule

Enrolled

Dropped

Wait Listed

Class
Description
Days/Times
Room
Instructor
Units
Status

EECS 495-0-25

 (38002)

Special Topics in EECS (Lecture)

We 1:00PM - 4:00PM

Frances Searle Building 3220

O. Cossairt

1.00

EECS 495-0-29

 (34603)

Special Topics in EECS (Lecture)

We 6:00PM - 8:50PM

Louis Hall 226

L. Birnbaum,

R. Gordon

1.00

EECS 499-0-95

 (34970)

Projects (Ind Study)

TBA

O. Cossairt

1.00

EECS 510-0-20

 (38373)

Seminar (Seminar)

TuTh 12:30PM - 1:50PM

Technological Institute LG52

A. Choudhary

1.00

Search

Enroll

Exam Schedule

My Academics

My Class Schedule

Add

Drop

Swap

Edit

Term Information

<select name="DERIVED_SSTSNAV_SSTS_MAIN_GOTO$155$" id="DERIVED_SSTSNAV_SSTS_MAIN_GOTO$155$" tabindex="175" size="1" class="PSDROPDOWNLIST" style="width:148px; " onchange="addchg_win1(this);return doEdits_win1(this,'','N','N','N','N','Y','Y',0);" psnchg="0">
<option value="0050">Homepage</option>
<option value="0200">My Academics</option>
<option value="0100">Student Center</option>
<option value="0500">User Preferences</option>
<option value="9999" selected="selected">go to ...</option>
</select>

</form>

t

test

t

Help

test

Default Local Node:<input type="text" readonly="readonly" name="ptus_defaultlocalnode" id="ptus_defaultlocalnode" value="PSFT_LS">
Portal:<input type="text" readonly="readonly" name="ptus_portal" id="ptus_portal" value="EMPLOYEE">
Node:<input type="text" readonly="readonly" name="ptus_node" id="ptus_node" value="HRMS">
WorkCenter Id:<input type="text" readonly="readonly" name="ptus_workcenterid" id="ptus_workcenterid" value="">
Url:<input type="text" readonly="readonly" name="ptus_componenturl" id="ptus_componenturl" value="https://ses.ent.northwestern.edu/psp/caesar_1/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_CART.GBL">
Component:<input type="text" readonly="readonly" name="ptus_component" id="ptus_component" value="Enrollment Shopping Cart">


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29473_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans18.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">"5 Energy Services

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">March 22, 2015

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">North Dakota Mineral Resources Survey Certification Sheet
Company: Continental Resources, Inc. Well: Candee 4
Well Number: 9H
Location: Dunn County, ND
Job Number: DDMT—l41075

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Well API# 33-025—02665

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Attached please find the original surveys performed on the above referenced well by MS Energy Services. The data is true, correct, complete and within the limitations of the tool as set forth by MS Energy Services. 1 am authorized and qualified to make this report and it conforms to the principles and procedures as set forth by MS Energy Services. The surveys were performed as listed below.
m
Name of Surveyor Drain hole No. Surveyed Depths Dates Performed Survey Kelly Brackett Original Wellbore 2,306' — 20,452' MD 12/18/2014 to 01/06/2015 MWD

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">If any other information is required, please contact the undersigned at the letterhead address and telephone number.
Amber Greer MWD Operations Office Administrator

MS Directional I MS Guidance | M5 Survey | MS Wireline

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">7821 Will Rogers Blvd. Fort Worth. Texas 76140
817.568.1038 (office) 817.568.1499 (fax) www.msenergyservioescom


text:
class PostCommitService < BaseService
  def execute(sha, branch)
    commit = repository.commit(sha)
    full_ref = 'refs/heads/' + branch
    old_sha = commit.parent_id || Gitlab::Git::BLANK_SHA
    GitPushService.new.execute(project, current_user, old_sha, sha, full_ref)
  end
end


text:
import pytest
from pytest_embedded import Dut

@pytest.mark.esp32
@pytest.mark.esp32s2
@pytest.mark.esp32s3
@pytest.mark.esp32c3
@pytest.mark.generic
def test_onewire_ds18b20_example(dut: Dut) -> None:
    dut.expect_exact('onewire_rmt: RMT Tx channel created for 1-wire bus')
    dut.expect_exact('onewire_rmt: RMT Rx channel created for 1-wire bus')
    dut.expect_exact('example: 1-wire bus installed')
    dut.expect_exact('example: 1-wire bus deleted')


text:
FlvPatcher
==========

Shell scripts to generate specially patched FLV files to avoid being encoded again by some online video sites.


text:
package com.vladkel.eFindMe.IHM;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

import com.vladkel.eFindMe.IHM.Controller.SearchUserAutoComplete;
import com.vladkel.eFindMe.IHM.View.AddUrlView;
import com.vladkel.eFindMe.IHM.View.AddUserView;
import com.vladkel.eFindMe.IHM.View.BePatientView;
import com.vladkel.eFindMe.IHM.model.UrlFindModel;
import com.vladkel.eFindMe.IHM.model.UrlFindTableModel;
import com.vladkel.eFindMe.IHM.model.UserFindTableModel;
import com.vladkel.eFindMe.graph.Graph;
import com.vladkel.eFindMe.graph.parsingxml.GraphXML;
import com.vladkel.eFindMe.search.engine.SearchEngine;
import com.vladkel.eFindMe.search.engine.model.Url;
import com.vladkel.eFindMe.search.engine.model.User;

public class MainWindow
{
	private JFrame mainFrame = new JFrame();
	private JToolBar toolBar = new JToolBar();
	private JButton addUser = new JButton("Ajouter un utilisateur");
	private JButton consultUsers = new JButton("Consulter les utilisateurs");
    private JTextField searchUserTextField = new JTextField();
	private JButton searchUserButton = new JButton("Go");

	private JPanel userDetail = new JPanel();

	private JLabel detailLabel = new JLabel("Informations sur le client");

	private JLabel idLabel = new JLabel("Indice :");
	private JTextField idTextField = new JTextField();

	private JLabel nameLabel = new JLabel("Nom :");
	private JTextField nameTextField = new JTextField();

	private JLabel firstNameLabel = new JLabel("Prénom :");
	private JTextField firstNameTextField = new JTextField();

	private JLabel emailLabel = new JLabel("Email :");
	private JTextField emailTextField = new JTextField();

	private JLabel urlsToLookForLabel = new JLabel("Vos urls :");

	private DefaultListModel<Url> modelUrlsToLookFor = new DefaultListModel<Url>();
	private JList<Url> listUrlsToLookFor = new JList<Url>(modelUrlsToLookFor);
    private JButton addUrl = new JButton("+");
    private JButton deleteUrl = new JButton("-");

	private JLabel urlsFindLabel = new JLabel("Urls trouvés :");
	private JTable tableUrlsFind = new JTable();
    JScrollPane jspUrlsFind = new JScrollPane(tableUrlsFind);

	private JButton search = new JButton("Lancer la recherche");
	private JButton delete = new JButton("Supprimer");
    private JButton update = new JButton("Modifier");

	private Graph graph = new Graph();

	private	SearchUserAutoComplete autoSuggestor = new SearchUserAutoComplete(searchUserTextField, mainFrame, null, Color.WHITE, Color.BLACK, Color.RED, 1f);

	private static MainWindow instance = null;
	public static MainWindow getInstance() {

		if(instance == null) {
			instance = new MainWindow();
	    }

		return instance;
	}

	// Select User
	private JPanel selectUser = new JPanel();
	private JLabel chooseUser = new JLabel("Selectionner le client");
	private JTable tableUsersFind = new JTable();
    JScrollPane jspUsersFind = new JScrollPane(tableUsersFind);
    private JButton buttonSelectUser = new JButton("Valider");

	@SuppressWarnings("static-access")
	public MainWindow()
	{
		SearchEngine.getInstance().getConfs().loadUsers();

		// getCurrentUser();

		mainFrame.setTitle("eFindMe");
		mainFrame.setExtendedState(mainFrame.MAXIMIZED_BOTH);
		Toolkit outil = mainFrame.getToolkit();
		mainFrame.setSize(outil.getScreenSize());
		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainFrame.setVisible(true);

		mainFrame.setLayout(new BorderLayout());

		initToolBar();
	    initSelectUser();

		mainFrame.getContentPane().add(graph, BorderLayout.CENTER);
		mainFrame.setVisible(true);
		events();
	}

	@SuppressWarnings("unused")
	private void getCurrentUser()
	{
		// Check the last used user
		SearchEngine.getInstance().currentUser = SearchEngine.getInstance().getConfs().getUsers().get("1");
	}

	@SuppressWarnings("static-access")
	private void initSelectUser()
	{
		selectUser.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width / 4,mainFrame.MAXIMIZED_VERT));

		selectUser.setLayout(new GridBagLayout());
		selectUser.setBorder(BorderFactory.createLineBorder(Color.black));
		GridBagConstraints gbc = new GridBagConstraints();

		chooseUser.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/5,Toolkit.getDefaultToolkit().getScreenSize().height / 13));
		chooseUser.setFont(new Font("Arial", Font.BOLD, 22));

	    jspUsersFind.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/5,Toolkit.getDefaultToolkit().getScreenSize().height/2));

		List<User> usersFind = new ArrayList<User>();

		for(Integer i = 0 ; i < SearchEngine.getInstance().getConfs().getUsers().size() ; i++)
	    {
	    	 User u = SearchEngine.getInstance().getConfs().getUsers().get(i.toString());
	    	 usersFind.add(u);
	    }

		tableUsersFind.setModel(new UserFindTableModel(usersFind));

		gbc.gridx = 0;
	    gbc.gridy = 0;
	    gbc.gridheight = 2;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.CENTER;
	    selectUser.add(chooseUser, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 2;
	    gbc.gridheight = 2;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.CENTER;
	    gbc.insets = new Insets(15,0,0,0);
	    selectUser.add(jspUsersFind, gbc);

	    gbc.gridx = 1;
	    gbc.gridy = 4;
	    gbc.gridheight = 2;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(15,0,0,0);
	    selectUser.add(buttonSelectUser, gbc);

		mainFrame.getContentPane().add(selectUser, BorderLayout.WEST);
	}

	@SuppressWarnings("static-access")
	private void initUserDetail()
	{
		selectUser.setVisible(false);
		setUser();

		userDetail.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width / 4,mainFrame.MAXIMIZED_VERT));

		userDetail.setLayout(new GridBagLayout());
		userDetail.setBorder(BorderFactory.createLineBorder(Color.black));
		GridBagConstraints gbc = new GridBagConstraints();

		idTextField.setEditable(false);
		idTextField.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/10,20));
		nameTextField.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/10,20));
		firstNameTextField.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/10,20));
		emailTextField.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/10,20));

		detailLabel.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/5,Toolkit.getDefaultToolkit().getScreenSize().height / 13));
		detailLabel.setFont(new Font("Arial", Font.BOLD, 22));

		urlsToLookForLabel.setFont(new Font("Arial", Font.BOLD, 14));
		urlsFindLabel.setFont(new Font("Arial", Font.BOLD, 14));

		listUrlsToLookFor.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/5,100));

	    jspUrlsFind.setPreferredSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().width/5,Toolkit.getDefaultToolkit().getScreenSize().height/3));

		search.setBackground(Color.WHITE);
	    update.setBackground(Color.WHITE);
	    delete.setBackground(Color.WHITE);

		gbc.gridx = 0;
	    gbc.gridy = 0;
	    gbc.gridheight = 2;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.CENTER;
	    userDetail.add(detailLabel, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 2;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(0,0,0,0);
	    userDetail.add(idLabel, gbc);

	    gbc.gridx = 1;
	    gbc.gridy = 2;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.WEST;
	    gbc.insets = new Insets(0,20,0,0);
	    userDetail.add(idTextField, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 3;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(5,0,0,0);
	    userDetail.add(nameLabel, gbc);

	    gbc.gridx = 1;
	    gbc.gridy = 3;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.WEST;
	    gbc.insets = new Insets(5,20,0,0);
	    userDetail.add(nameTextField, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 4;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(5,0,0,0);
	    userDetail.add(firstNameLabel, gbc);

	    gbc.gridx = 1;
	    gbc.gridy = 4;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.WEST;
	    gbc.insets = new Insets(5,20,0,0);
	    userDetail.add(firstNameTextField, gbc);

		gbc.gridx = 0;
		gbc.gridy = 5;
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.anchor = GridBagConstraints.EAST;
		gbc.insets = new Insets(5,0,0,0);
		userDetail.add(emailLabel, gbc);

		gbc.gridx = 1;
		gbc.gridy = 5;
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.anchor = GridBagConstraints.WEST;
		gbc.insets = new Insets(5,20,0,0);
		userDetail.add(emailTextField, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 6;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(urlsToLookForLabel, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 7;
	    gbc.gridheight = 2;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.CENTER;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(listUrlsToLookFor, gbc);

	    JPanel pan = new JPanel();
	    pan.setLayout(new BoxLayout(pan,BoxLayout.X_AXIS));
	    pan.add(addUrl);

	    pan.add(Box.createHorizontalStrut(10));
	    pan.add(deleteUrl);

	    gbc.gridx = 0;
	    gbc.gridy = 9;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.CENTER;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(pan, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 11;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(urlsFindLabel, gbc);

	    gbc.gridx = 0;
	    gbc.gridy = 12;
	    gbc.gridheight = 2;
	    gbc.gridwidth = 2;
	    gbc.anchor = GridBagConstraints.WEST;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(jspUrlsFind, gbc);

		gbc.gridx = 0;
		gbc.gridy = 14;
		gbc.gridheight = 1;
		gbc.gridwidth = 1;
		gbc.anchor = GridBagConstraints.WEST;
		gbc.insets = new Insets(15,0,0,0);
		userDetail.add(search, gbc);

		gbc.gridx = 1;
	    gbc.gridy = 14;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.CENTER;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(update, gbc);

		gbc.gridx = 1;
	    gbc.gridy = 14;
	    gbc.gridheight = 1;
	    gbc.gridwidth = 1;
	    gbc.anchor = GridBagConstraints.EAST;
	    gbc.insets = new Insets(15,0,0,0);
	    userDetail.add(delete, gbc);

		mainFrame.getContentPane().add(userDetail, BorderLayout.WEST);
	}

	public void setUser()
	{
		GraphXML.getInstance().getDataXml(Integer.parseInt(SearchEngine.getInstance().currentUser.getId()));

		graph.initGraph();

        List<String> users = new ArrayList<String>();

	    for(Integer i = 0 ; i < SearchEngine.getInstance().getConfs().getUsers().size() ; i++)
	    {
	    	 User u = SearchEngine.getInstance().getConfs().getUsers().get(i.toString());
	    	 users.add(u.getFirstname() + " " + u.getName());
	    }

        autoSuggestor.setDictionary(users);

		User user = SearchEngine.getInstance().currentUser;

		idTextField.setText(user.getId());
		nameTextField.setText(user.getName());
		firstNameTextField.setText(user.getFirstname());
		emailTextField.setText(user.getEmail());

		List<UrlFindModel> urlsFind = new ArrayList<UrlFindModel>();
		modelUrlsToLookFor.clear();

		for(Url url : user.getUrlsToLookFor())
			modelUrlsToLookFor.addElement(url);

		for(Url url : SearchEngine.getInstance().currentUser.getUrls().values()){
			UrlFindModel ufm = new UrlFindModel(url.getUrl(), url.getTrust().toString());
		    urlsFind.add(ufm);
		}

		tableUrlsFind.setModel(new UrlFindTableModel(urlsFind));

  		mainFrame.revalidate();
	}

	private void initToolBar()
	{
		toolBar.setFloatable(false);

	    addUser.setBackground(Color.WHITE);
	    consultUsers.setBackground(Color.WHITE);

	    toolBar.addSeparator();
	    toolBar.add(addUser);
	    toolBar.addSeparator();
	    toolBar.add(consultUsers);
	    toolBar.add(Box.createHorizontalGlue());

	    searchUserTextField.setMaximumSize(new Dimension(200,20));
	    searchUserTextField.setPreferredSize(new Dimension(200,20));
	    searchUserTextField.setToolTipText("Rechercher un utilisateur");
	    searchUserTextField.setText("Rechercher un utilisateur ...");

	    searchUserButton.setMaximumSize(new Dimension(50,20));
	    searchUserButton.setPreferredSize(new Dimension(50,20));

        toolBar.add(searchUserTextField);
        toolBar.add(searchUserButton);

	    mainFrame.getContentPane().add(toolBar, BorderLayout.NORTH);
	}

	private void events()
	{
		addUser.addActionListener(new ActionListener(){
		      public void actionPerformed(ActionEvent event){
		    	  @SuppressWarnings("unused")
				AddUserView auv = new AddUserView();
		      }
		    });

		searchUserButton.addActionListener(new ActionListener(){
		      public void actionPerformed(ActionEvent event){

		    	  for(Integer i = 0 ; i <  SearchEngine.getInstance().getConfs().getUsers().size() ; i++)
		  	      {
		  	    	 User u = SearchEngine.getInstance().getConfs().getUsers().get(i.toString());

		  	    	 if(searchUserTextField.getText().replaceAll(" ","").equals((u.getFirstname() + " " + u.getName()).replaceAll(" ","")))
		  	    	 {
		  	    		 SearchEngine.getInstance().currentUser = SearchEngine.getInstance().getConfs().getUsers().get(i.toString());
		  	    		 setUser();
		  	    	 }
		  	      }
		      }
		});

		searchUserTextField.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
            	if(searchUserTextField.getText().equals("Rechercher un utilisateur ..."))
		    		searchUserTextField.setText("");
            }
        });

		final MainWindow self = this;

		addUrl.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("addUrl pressed");
				new AddUrlView(self);
			}
		});

		buttonSelectUser.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int row = tableUsersFind.convertRowIndexToModel(tableUsersFind.getSelectedRow());
	            UserFindTableModel model = (UserFindTableModel)tableUsersFind.getModel();

	            User user = model.getRowAt(row);

	            SearchEngine.getInstance().currentUser = user;

	            selectUser.setVisible(false);
				userDetail.setVisible(true);
				initUserDetail();

				mainFrame.validate();
				mainFrame.repaint();
			}
		});

		deleteUrl.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("deleteUrl pressed");

				int index = listUrlsToLookFor.getSelectedIndex();

				if(index != -1){
					String message = "Etes vous sûr de vouloir supprimer l'url '" +
							((Url)modelUrlsToLookFor.getElementAt(index)).getName() +
							"'?";
					String title = "Supprimer une url";
					int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);

					if (reply == JOptionPane.YES_OPTION)
						modelUrlsToLookFor.remove(index);
				}
			}
		});

		update.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if(isReadyToUpdate()){

					String message = "Etes vous sûr de vouloir enregistrer les modifications aportées ?";
					String title = "Enregistrer les modifications ?";
					int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);

					if(reply == JOptionPane.YES_OPTION){

						SearchEngine.getInstance().currentUser.removeSelfXMLFiles();

						User user = new User();

						user.setId(SearchEngine.getInstance().currentUser.getId());
						user.setName(nameTextField.getText());
						user.setFirstname(firstNameTextField.getText());
						user.setEmail(emailTextField.getText());

						for(int i = 0; i < listUrlsToLookFor.getModel().getSize(); i++){
							user.getUrlsToLookFor().add((Url)modelUrlsToLookFor.getElementAt(i));
							System.out.println(((Url)modelUrlsToLookFor.getElementAt(i)).getName() + " added to current user");
						}

						/**
						 * We don't save the urls, so we need to launch a new search
						 */

						user.writeSelfXMLFiles();
						SearchEngine.getInstance().updateConf();
						SearchEngine.getInstance().currentUser = SearchEngine.getInstance().getConfs().getUsers().get(user.getId());
						initUserDetail();
					}
				}
				else {
					JOptionPane.showMessageDialog(null,
							"Veuillez remplir au moins les champs Nom et Prénom pour modifier un utilisateur."
					);
				}
			}
		});

		delete.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				String message = "Etes vous sûr de vouloir supprimer l'utilisateur ?";
				String title = "Supprimer l'utilisateur ?";
				int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);

				if(reply == JOptionPane.YES_OPTION){

					SearchEngine.getInstance().currentUser.removeSelfXMLFiles();

					@SuppressWarnings("static-access")
					User user = new SearchEngine().getInstance().currentUser;

					user.removeSelfXMLFiles();
					SearchEngine.getInstance().updateConf();

					showSelectUser();

				}
			}
		});

		search.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				searchForCurrentUser();
			}
		});

		consultUsers.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				showSelectUser();
			}
		});
	}

	public void showSelectUser(){
		selectUser.setVisible(true);
		userDetail.setVisible(false);
	    initSelectUser();

		mainFrame.validate();
		mainFrame.repaint();
	}

	private boolean isReadyToUpdate(){
		return firstNameTextField.getText().length() > 0 &&
				nameTextField.getText().length() > 0
				;
	}

	public void searchForCurrentUser(){

		System.out.println("searchForCurrentUser()");

		try{
			@SuppressWarnings("unused")
			BePatientView bePatient = new BePatientView();
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	/*
	 * Getters and Setters
	 */

	public DefaultListModel<Url> getModelUrlsToLookFor(){
		return modelUrlsToLookFor;
	}

}


text:
package org.docksidestage.compatible10x.dbflute.vendor;

import java.util.List;

import org.dbflute.bhv.referrer.ConditionBeanSetupper;
import org.dbflute.cbean.result.ListResultBean;
import org.docksidestage.compatible10x.dbflute.cbean.ProductStatusCB;
import org.docksidestage.compatible10x.dbflute.cbean.PurchaseCB;
import org.docksidestage.compatible10x.dbflute.cbean.SummaryProductCB;
import org.docksidestage.compatible10x.dbflute.exbhv.ProductStatusBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.PurchaseBhv;
import org.docksidestage.compatible10x.dbflute.exbhv.SummaryProductBhv;
import org.docksidestage.compatible10x.dbflute.exentity.ProductStatus;
import org.docksidestage.compatible10x.dbflute.exentity.Purchase;
import org.docksidestage.compatible10x.dbflute.exentity.SummaryProduct;
import org.docksidestage.compatible10x.unit.UnitContainerTestCase;

/**
 * @author jflute
 * @since 0.7.7 (2008/07/23 Wednesday)
 */
public class VendorViewTest extends UnitContainerTestCase {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    private PurchaseBhv purchaseBhv;
    private SummaryProductBhv summaryProductBhv;
    private ProductStatusBhv productStatusBhv;

    // ===================================================================================
    //                                                                       Table to View
    //                                                                       =============
    public void test_TableToView_setupSelect() {
        // ## Arrange ##
        PurchaseCB cb = new PurchaseCB();
        cb.setupSelect_SummaryProduct();

        // ## Act ##
        ListResultBean<Purchase> purchaseList = purchaseBhv.selectList(cb);

        // ## Assert ##
        for (Purchase purchase : purchaseList) {
            SummaryProduct summaryProduct = purchase.getSummaryProduct();
            log(purchase.getPurchaseId() + ", " + summaryProduct);
            assertNotNull(summaryProduct);
        }
    }

    // ===================================================================================
    //                                                                       View to Table
    //                                                                       =============
    public void test_ViewToTable_setupSelect() {
        // ## Arrange ##
        SummaryProductCB cb = new SummaryProductCB();
        cb.setupSelect_ProductStatus();

        // ## Act ##
        ListResultBean<SummaryProduct> productList = summaryProductBhv.selectList(cb);

        // ## Assert ##
        for (SummaryProduct product : productList) {
            assertNotNull(product.getProductStatus());
        }
    }

    public void test_ViewToTable_local_loadReferrer() {
        // ## Arrange ##
        SummaryProductCB cb = new SummaryProductCB();
        ListResultBean<SummaryProduct> summaryProductList = summaryProductBhv.selectList(cb);

        // ## Act ##
        summaryProductBhv.loadPurchaseList(summaryProductList, new ConditionBeanSetupper<PurchaseCB>() {
            public void setup(PurchaseCB cb) {
                cb.query().addOrderBy_PurchaseDatetime_Desc();
            }
        });

        // ## Assert ##
        boolean existsPurchase = false;
        for (SummaryProduct summaryProduct : summaryProductList) {
            log(summaryProduct);
            List<Purchase> purchaseList = summaryProduct.getPurchaseList();
            for (Purchase purchase : purchaseList) {
                log("    " + purchase.toString());
                existsPurchase = true;
            }
        }
        assertTrue(existsPurchase);
    }

    public void test_ViewToTable_foreign_loadReferrer() {
        // ## Arrange ##
        ProductStatusCB cb = new ProductStatusCB();
        ListResultBean<ProductStatus> productStatusList = productStatusBhv.selectList(cb);

        // ## Act ##
        productStatusBhv.loadSummaryProductList(productStatusList, new ConditionBeanSetupper<SummaryProductCB>() {
            public void setup(SummaryProductCB cb) {
                cb.query().addOrderBy_LatestPurchaseDatetime_Desc();
            }
        });

        // ## Assert ##
        boolean existsSummaryProduct = false;
        for (ProductStatus productStatus : productStatusList) {
            log(productStatus);
            List<SummaryProduct> summaryProductList = productStatus.getSummaryProductList();
            for (SummaryProduct summaryProduct : summaryProductList) {
                log("    " + summaryProduct.toString());
                existsSummaryProduct = true;
            }
        }
        assertTrue(existsSummaryProduct);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape>
        <solid android:color="#474724" />
        <stroke android:width="1dp" android:color="#39391D" />
    </shape></item>

    <item android:state_enabled="false"><shape>
        <solid android:color="#868669" />
        <stroke android:width="1dp" android:color="#79795E" />
    </shape></item>

    <item><shape>
        <solid android:color="#666633" />
        <stroke android:width="1dp" android:color="#525229" />
    </shape></item>

</selector>


text:
package com.google.gerrit.server.events;

import com.google.gerrit.reviewdb.Change;

import java.util.List;

public class ChangeAttribute {
    public String project;
    public String branch;
    public String topic;
    public String id;
    public String number;
    public String subject;
    public AccountAttribute owner;
    public String url;

    public Long createdOn;
    public Long lastUpdated;
    public String sortKey;
    public Boolean open;
    public Change.Status status;
    public List<MessageAttribute> comments;

    public List<TrackingIdAttribute> trackingIds;
    public PatchSetAttribute currentPatchSet;
    public List<PatchSetAttribute> patchSets;
}


text:
package html

import (
	"fmt"

	"github.com/mokelab-go/markdown"
	"github.com/mokelab-go/markdown/ast"
)

type impl struct {
}

func NewMarkdown() markdown.Markdown {
	return &impl{}
}

func (o *impl) Compile(src string) (string, error) {
	tree, err := ast.Parse(src)
	if err != nil {
		return "", err
	}
	out := make([]byte, 0, len(src)*2)
	out = printBlock(out, tree)
	return string(out), nil
}

func appendStr(out []byte, text string) []byte {
	return append(out, text...)
}

func printBlock(out []byte, block *ast.Block) []byte {
	switch block.Type {
	case ast.TypeRoot:
		return printChildren(out, block)
	case ast.TypeH1:
		out = appendStr(out, "
")
		out = printChildren(out, block)
		out = appendStr(out, "
\n\n")
	case ast.TypeH2:
		out = appendStr(out, "
")
		out = printChildren(out, block)
		out = appendStr(out, "
\n\n")
	case ast.TypeP:
		out = appendStr(out, "
")
		out = printChildren(out, block)
		out = appendStr(out, "
\n\n")
	case ast.TypePreCode:
		out = appendStr(out, "
")
		out = printChildren(out, block)
		out = appendStr(out, "
\n\n")
	case ast.TypeUL:
		out = appendStr(out, "
\n")
		out = printChildren(out, block)
		out = appendStr(out, "
\n\n")
	case ast.TypeLI:
		out = appendStr(out, "
")
		out = printChildren(out, block)
		out = appendStr(out, "
\n")
	case ast.TypeAnchor:
		out = appendStr(out, fmt.Sprintf("%s", block.URL, block.Value))
	case ast.TypeImage:
		out = appendStr(out, fmt.Sprintf("", block.URL, block.Value))
	case ast.TypeText:
		if len(block.Value) == 0 {
			out = printChildren(out, block)
		} else {
			out = appendStr(out, block.Value)
		}
	case ast.TypeCode:
		out = appendStr(out, "")
		out = appendStr(out, block.Value)
		out = appendStr(out, "\n\n")
	}
	return out
}

func printChildren(out []byte, block *ast.Block) []byte {
	for _, e := range block.Children {
		out = printBlock(out, e)
	}
	return out
}