<commit_before>/* global document, window, location, chrome */

;(function() {
  var handlers = require('./modules/handlers').create('ct');
  require('./modules/msg').init('ct', handlers);

  var $ = require('./libs/jquery-1.11.2.min.js');
  window.jQuery = window.jQuery || $;
  var Hogan = require('./libs/hogan-3.0.1.js');
  require('./libs/typeahead.jquery.min.js');
  require('./libs/algoliasearch.min.js');

  var NB_REPOS = 5;
  var NB_MY_REPOS = 2;
  var NB_USERS = 3;

  var algolia = new window.AlgoliaSearch('TLCDTR8BIO', '686cce2f5dd3c38130b303e1c842c3e3');
  var users = algolia.initIndex('github_users');

  var templateUser = Hogan.compile('<div class="aa-suggestion aa-user">' +
    '{{#followers}}<span class="aa-infos">{{ followers }} <i class="octicon octicon-person"></i></span>{{/followers}}' +
    '<div class="aa-thumbnail"><img src="https://avatars2.githubusercontent.com/u/{{ id }}?v=2&s=30" /></div>' +
    '<a href="https://github.com/{{ login }}">'+
      '{{#name}}<span class="aa-name">{{{ _highlightResult.name.value }}}</span> {{/name}}' +
      '<span class="aa-login">{{{ _highlightResult.login.value }}}</span>' +
    '</a>' +
    '{{#company}}<br><span class="aa-company"><i class="octicon octicon-organization"></i> {{{ _highlightResult.company.value }}}</span>{{/company}}' +
  '</div>');

  var templateRepo = Hogan.compile('<div class="aa-suggestion aa-repo">' +
    '{{#stargazers_count}}<div class="aa-infos">{{ stargazers_count }} <i class="octicon octicon-star"></i></div>{{/stargazers_count}}' +
    '<span class="aa-name"><a href="https://github.com/{{ full_name }}/">{{{ _highlightResult.full_name.value }}}</a></span>' +
    '<div class="aa-description">{{{ _snippetResult.description.value }}}</div>' +
  '</div>');

  var templateYourRepo = Hogan.compile('<div class="aa-suggestion aa-repo">' +
    '<span class="aa-name">' +
      '<span class="repo-icon octicon {{#fork}}octicon-repo-forked{{/fork}}{{^fork}}{{#private}}octicon-lock{{/private}}{{^private}}octicon-repo{{/private}}{{/fork}}"></span> ' +
      '<a href="https://github.com/{{ full_name }}/">{{{ full_name }}}</a>' +
    '</span>' +
  '</div>');

  var yourRepositories = [];

  // crawl the repositories associated to a user or an organization
  var crawlRepositories = function(url, organization) {
    $.get(url).success(function(data) {
      // parse HTML-based list of repositories
      $('<ul>' + data + '</ul>').find('li').each(function() {
        var isPrivate = $(this).hasClass('private');
        var isFork = $(this).hasClass('fork');
        var owner = $(this).find('span.owner').text() || $(this).find('span.repo-and-owner').attr('title').split('/')[0];
        var repo = $(this).find('span.repo').text();
        var fullName = owner + '/' + repo;
        yourRepositories.push({
          organization: organization,
          full_name: fullName,
          owner: owner,
          repo: repo,
          fork: isFork,
          private: isPrivate
        });
      });

      // save repositories to local storage
      chrome.storage.local.set({ yourRepositories: yourRepositories });
    });
  };

  window.refreshRepositories = function() {
    console.log('Refreshing your repositories...');
    yourRepositories = [];

    // crawl your repositories
    crawlRepositories('/dashboard/ajax_your_repos');

    // get on the homepage to fetch your list of organization
    $.ajax('/', { headers: { 'X-Requested-With' : 'fake' } }).success(function(data) {
      $(data).find('.select-menu-list a.select-menu-item').each(function() {
        var href = $(this).attr('href');
        if (href.indexOf('/orgs/') === 0) {
          // and crawl all of them
          var organization = href.split('/')[2];
          crawlRepositories('/organizations/' + organization + '/ajax_your_repos', organization);
        }
      });
    });
  };

  $(document).ready(function() {
    var $q = $('.site-search input[name="q"]');
    $q.parent().addClass('awesome-autocomplete');

    // load local repositories or refresh
    chrome.storage.local.get('yourRepositories', function(result) {
      if (result && result.yourRepositories) {
        yourRepositories = result.yourRepositories;
      } else {
        window.refreshRepositories();
      }
    });

    // handle <Enter> action
    var $form = $q.closest('form');
    var submit = function(q) {
      location.href = $form.attr('action') + '?utf8=✓&q=' + encodeURIComponent(q);
    };

    // setup auto-completion menu
    $q.typeahead({ highlight: false, hint: false }, [
      {
        source: function(q, cb) { cb([]); }, // force empty
        name: 'default',
        templates: {
          empty: function(data) {
            return '<div class="aa-query">' +
              'Press <em>&lt;Enter&gt;</em> to search for "<em>' + $('<div />').text(data.query).html() + '</em>"' +
              '</div>';
          }
        }
      },
      {
        source: function(q, cb) {
          var matchingRepositories = [];
          for (var i = 0; i < yourRepositories.length && matchingRepositories.length < NB_MY_REPOS; ++i) {
            var hit = yourRepositories[i];
            if (hit.repo.toLowerCase().indexOf(q.toLowerCase()) > -1) { // FIXME
              matchingRepositories.push(hit);
            }
          }
          cb(matchingRepositories);
        },
        name: 'private',
        templates: {
          header: '<div class="aa-category">Your Repositories</div>',
          suggestion: function(hit) { return templateYourRepo.render(hit); }
        }
      },
      {
        source: function(q, cb) {
          var params = { attributesToRetrieve: ['full_name', 'homepage', 'stargazers_count', 'forks_count'], attributesToSnippet: ['description:50'] };
          algolia.startQueriesBatch();
          algolia.addQueryInBatch('github_repos', q, $.extend({ hitsPerPage: parseInt(NB_REPOS / 2 + 1, 10), numericFilters: 'stargazers_count>1000', restrictSearchableAttributes: 'name' }, params));
          algolia.addQueryInBatch('github_repos', q, $.extend({ hitsPerPage: NB_REPOS }, params));
          algolia.sendQueriesBatch(function(success, content) {
            var suggestions = [];
            if (success) {
              var dedup = {};
              for (var i = 0; i < content.results.length && suggestions.length < NB_REPOS; ++i) {
                for (var j = 0; j < content.results[i].hits.length && suggestions.length < NB_REPOS; ++j) {
                  var hit = content.results[i].hits[j];
                  if (dedup[hit.objectID]) {
                    continue;
                  }
                  dedup[hit.objectID] = true;
                  suggestions.push(hit);
                }
              }
            }
            cb(suggestions);
          });
        },
        name: 'repos',
        templates: {
          header: '<div class="aa-category">Repositories</div>',
          suggestion: function(hit) { return templateRepo.render(hit); }
        }
      },
      {
        source: users.ttAdapter({ hitsPerPage: NB_USERS, attributesToRetrieve: ['login', 'name', 'id', 'company', 'followers'] }),
        name: 'users',
        templates: {
          header: '<div class="aa-category">Users</div>',
          suggestion: function(hit) { return templateUser.render(hit); }
        }
      },
      {
        source: function(q, cb) { cb([]); }, // force empty
        name: 'branding',
        templates: {
          empty: function() {
            return '<div class="aa-branding">' +
              'Realtime Search by <a href="https://www.algolia.com"><img src="' + chrome.extension.getURL('images/algolia128x40.png') + '" title="Algolia" /></a>' +
              '</div>';
          }
        }
      }
    ]).on('typeahead:selected', function(event, suggestion, dataset) {
      if (dataset === 'users') {
        location.href = 'https://github.com/' + suggestion.login;
      } else if (dataset === 'repos') {
        location.href = 'https://github.com/' + suggestion.full_name;
      } else {
        console.log('Unknown dataset: ' + dataset);
      }
    }).on('keypress', function(e) {
      if (e.keyCode === 13) { // enter
        submit($(this).val());
      }
    }).focus();
  });
})();<commit_msg>Handle private suggestion selection as well<commit_after>/* global document, window, location, chrome */

;(function() {
  var handlers = require('./modules/handlers').create('ct');
  require('./modules/msg').init('ct', handlers);

  var $ = require('./libs/jquery-1.11.2.min.js');
  window.jQuery = window.jQuery || $;
  var Hogan = require('./libs/hogan-3.0.1.js');
  require('./libs/typeahead.jquery.min.js');
  require('./libs/algoliasearch.min.js');

  var NB_REPOS = 5;
  var NB_MY_REPOS = 2;
  var NB_USERS = 3;

  var algolia = new window.AlgoliaSearch('TLCDTR8BIO', '686cce2f5dd3c38130b303e1c842c3e3');
  var users = algolia.initIndex('github_users');

  var templateUser = Hogan.compile('<div class="aa-suggestion aa-user">' +
    '{{#followers}}<span class="aa-infos">{{ followers }} <i class="octicon octicon-person"></i></span>{{/followers}}' +
    '<div class="aa-thumbnail"><img src="https://avatars2.githubusercontent.com/u/{{ id }}?v=2&s=30" /></div>' +
    '<a href="https://github.com/{{ login }}">'+
      '{{#name}}<span class="aa-name">{{{ _highlightResult.name.value }}}</span> {{/name}}' +
      '<span class="aa-login">{{{ _highlightResult.login.value }}}</span>' +
    '</a>' +
    '{{#company}}<br><span class="aa-company"><i class="octicon octicon-organization"></i> {{{ _highlightResult.company.value }}}</span>{{/company}}' +
  '</div>');

  var templateRepo = Hogan.compile('<div class="aa-suggestion aa-repo">' +
    '{{#stargazers_count}}<div class="aa-infos">{{ stargazers_count }} <i class="octicon octicon-star"></i></div>{{/stargazers_count}}' +
    '<span class="aa-name"><a href="https://github.com/{{ full_name }}/">{{{ _highlightResult.full_name.value }}}</a></span>' +
    '<div class="aa-description">{{{ _snippetResult.description.value }}}</div>' +
  '</div>');

  var templateYourRepo = Hogan.compile('<div class="aa-suggestion aa-repo">' +
    '<span class="aa-name">' +
      '<span class="repo-icon octicon {{#fork}}octicon-repo-forked{{/fork}}{{^fork}}{{#private}}octicon-lock{{/private}}{{^private}}octicon-repo{{/private}}{{/fork}}"></span> ' +
      '<a href="https://github.com/{{ full_name }}/">{{{ full_name }}}</a>' +
    '</span>' +
  '</div>');

  var yourRepositories = [];

  // crawl the repositories associated to a user or an organization
  var crawlRepositories = function(url, organization) {
    $.get(url).success(function(data) {
      // parse HTML-based list of repositories
      $('<ul>' + data + '</ul>').find('li').each(function() {
        var isPrivate = $(this).hasClass('private');
        var isFork = $(this).hasClass('fork');
        var owner = $(this).find('span.owner').text() || $(this).find('span.repo-and-owner').attr('title').split('/')[0];
        var repo = $(this).find('span.repo').text();
        var fullName = owner + '/' + repo;
        yourRepositories.push({
          organization: organization,
          full_name: fullName,
          owner: owner,
          repo: repo,
          fork: isFork,
          private: isPrivate
        });
      });

      // save repositories to local storage
      chrome.storage.local.set({ yourRepositories: yourRepositories });
    });
  };

  window.refreshRepositories = function() {
    console.log('Refreshing your repositories...');
    yourRepositories = [];

    // crawl your repositories
    crawlRepositories('/dashboard/ajax_your_repos');

    // get on the homepage to fetch your list of organization
    $.ajax('/', { headers: { 'X-Requested-With' : 'fake' } }).success(function(data) {
      $(data).find('.select-menu-list a.select-menu-item').each(function() {
        var href = $(this).attr('href');
        if (href.indexOf('/orgs/') === 0) {
          // and crawl all of them
          var organization = href.split('/')[2];
          crawlRepositories('/organizations/' + organization + '/ajax_your_repos', organization);
        }
      });
    });
  };

  $(document).ready(function() {
    var $q = $('.site-search input[name="q"]');
    $q.parent().addClass('awesome-autocomplete');

    // load local repositories or refresh
    chrome.storage.local.get('yourRepositories', function(result) {
      if (result && result.yourRepositories) {
        yourRepositories = result.yourRepositories;
      } else {
        window.refreshRepositories();
      }
    });

    // handle <Enter> action
    var $form = $q.closest('form');
    var submit = function(q) {
      location.href = $form.attr('action') + '?utf8=✓&q=' + encodeURIComponent(q);
    };

    // setup auto-completion menu
    $q.typeahead({ highlight: false, hint: false }, [
      {
        source: function(q, cb) { cb([]); }, // force empty
        name: 'default',
        templates: {
          empty: function(data) {
            return '<div class="aa-query">' +
              'Press <em>&lt;Enter&gt;</em> to search for "<em>' + $('<div />').text(data.query).html() + '</em>"' +
              '</div>';
          }
        }
      },
      {
        source: function(q, cb) {
          var matchingRepositories = [];
          for (var i = 0; i < yourRepositories.length && matchingRepositories.length < NB_MY_REPOS; ++i) {
            var hit = yourRepositories[i];
            if (hit.repo.toLowerCase().indexOf(q.toLowerCase()) > -1) { // FIXME
              matchingRepositories.push(hit);
            }
          }
          cb(matchingRepositories);
        },
        name: 'private',
        templates: {
          header: '<div class="aa-category">Your Repositories</div>',
          suggestion: function(hit) { return templateYourRepo.render(hit); }
        }
      },
      {
        source: function(q, cb) {
          var params = { attributesToRetrieve: ['full_name', 'homepage', 'stargazers_count', 'forks_count'], attributesToSnippet: ['description:50'] };
          algolia.startQueriesBatch();
          algolia.addQueryInBatch('github_repos', q, $.extend({ hitsPerPage: parseInt(NB_REPOS / 2 + 1, 10), numericFilters: 'stargazers_count>1000', restrictSearchableAttributes: 'name' }, params));
          algolia.addQueryInBatch('github_repos', q, $.extend({ hitsPerPage: NB_REPOS }, params));
          algolia.sendQueriesBatch(function(success, content) {
            var suggestions = [];
            if (success) {
              var dedup = {};
              for (var i = 0; i < content.results.length && suggestions.length < NB_REPOS; ++i) {
                for (var j = 0; j < content.results[i].hits.length && suggestions.length < NB_REPOS; ++j) {
                  var hit = content.results[i].hits[j];
                  if (dedup[hit.objectID]) {
                    continue;
                  }
                  dedup[hit.objectID] = true;
                  suggestions.push(hit);
                }
              }
            }
            cb(suggestions);
          });
        },
        name: 'repos',
        templates: {
          header: '<div class="aa-category">Repositories</div>',
          suggestion: function(hit) { return templateRepo.render(hit); }
        }
      },
      {
        source: users.ttAdapter({ hitsPerPage: NB_USERS, attributesToRetrieve: ['login', 'name', 'id', 'company', 'followers'] }),
        name: 'users',
        templates: {
          header: '<div class="aa-category">Users</div>',
          suggestion: function(hit) { return templateUser.render(hit); }
        }
      },
      {
        source: function(q, cb) { cb([]); }, // force empty
        name: 'branding',
        templates: {
          empty: function() {
            return '<div class="aa-branding">' +
              'Realtime Search by <a href="https://www.algolia.com"><img src="' + chrome.extension.getURL('images/algolia128x40.png') + '" title="Algolia" /></a>' +
              '</div>';
          }
        }
      }
    ]).on('typeahead:selected', function(event, suggestion, dataset) {
      if (dataset === 'users') {
        location.href = 'https://github.com/' + suggestion.login;
      } else if (dataset === 'repos' || dataset === 'private') {
        location.href = 'https://github.com/' + suggestion.full_name;
      } else {
        console.log('Unknown dataset: ' + dataset);
      }
    }).on('keypress', function(e) {
      if (e.keyCode === 13) { // enter
        submit($(this).val());
      }
    }).focus();
  });
})();
{'fraction_non_alphanumeric': 0.19099631887031562, 'fraction_numerical': 0.007241566592239454, 'mean_word_length': 2.536491677336748, 'pattern_counts': {'":': 0, '<': 137, '<?xml version=': 0, '>': 129, 'https://': 14, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2835779', 'n_tokens_mistral': 5296, 'n_tokens_neox': 5085, 'n_words': 953}