Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add a buffer modifying linter spec | describe 'buffer modifying linters', ->
getModuleMain = -> atom.packages.getActivePackage('linter').mainModule.instance
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage('status-bar')
.catch (err)->
console.log err
waitsForPromise ->
atom.packages.activatePackage('lint... | |
Split code for finding sales orders into component | class Skr.Components.SalesOrderFinder extends Lanes.React.Component
propTypes:
onModelSet: React.PropTypes.func
commands: React.PropTypes.object
dataObjects:
sales_order: ->
@props.sales_order || new Skr.Models.SalesOrder
query: ->
new Lanes.Models.Quer... | |
Fix root url on server side | RocketChat.settings.onload 'Site_Url', (key, value, initialLoad) ->
if value?.trim() isnt ''
__meteor_runtime_config__.ROOT_URL = value
if Meteor.absoluteUrl.defaultOptions?.rootUrl?
Meteor.absoluteUrl.defaultOptions.rootUrl = value
| RocketChat.settings.get 'Site_Url', (key, value) ->
if value?.trim() isnt ''
__meteor_runtime_config__.ROOT_URL = value
if Meteor.absoluteUrl.defaultOptions?.rootUrl?
Meteor.absoluteUrl.defaultOptions.rootUrl = value
|
Add key bindings for frequently used commands. | # Keybindings require three things to be fully defined: A selector that is
# matched against the focused element, the keystroke and the command to
# execute.
#
# Below is a basic keybinding which registers on all platforms by applying to
# the root workspace element.
# For more detailed documentation see
# https://ato... | |
Add linter indie API usage spec | describe 'Linter Indie API', ->
linter = null
{wait} = require('./common')
Remote = require('remote')
beforeEach ->
global.setTimeout = Remote.getGlobal('setTimeout')
global.setInterval = Remote.getGlobal('setInterval')
waitsForPromise ->
atom.packages.activate('linter').then ->
lint... | |
Fix message sender pastie link | class Kandan.Views.Chatbox extends Backbone.View
template: JST['chatbox']
tagName: 'div'
className: 'chatbox'
events:
"keypress .chat-input": 'postMessageOnEnter'
"click .post" : 'postMessage'
postMessageOnEnter: (event)->
if event.keyCode == 13
@postMessage(event)
even... | class Kandan.Views.Chatbox extends Backbone.View
template: JST['chatbox']
tagName: 'div'
className: 'chatbox'
events:
"keypress .chat-input": 'postMessageOnEnter'
"click .post" : 'postMessage'
postMessageOnEnter: (event)->
if event.keyCode == 13
@postMessage(event)
even... |
Initialize user's area tokens field with data | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
jQuery ->
$('#user_area_tokens').tokenInput '/areas.json'
theme: 'facebook'
prePo... | |
Add Angular filter for wrapping words larger than N characters. | define [
"base"
], (App) ->
DEF_MIN_LENGTH = 20
_getWrappedWordsString = (baseStr, wrapperElName, minLength) ->
minLength = minLength || DEF_MIN_LENGTH
findWordsRegEx = new RegExp "\\w{#{minLength},}", "g"
wrappingTemplate = "<#{wrapperElName} style='word-break: break-all;'>$&</#{wrapperElName}>"
baseStr.... | |
Add Settings model on client side | module.exports = class Settings extends Backbone.Model
urlRoot: 'settings'
# Make sure that put requests doesn't add id to the url.
sync: (method, model, options) ->
options.url ='settings'
return Backbone.sync method, model, options
| |
Allow changing of filename on a case insensitive fs | path = require 'path'
{fs} = require 'atom'
Dialog = require './dialog'
module.exports =
class MoveDialog extends Dialog
constructor: (@initialPath) ->
if fs.isDirectorySync(@initialPath)
prompt = 'Enter the new path for the directory.'
else
prompt = 'Enter the new path for the file.'
supe... | path = require 'path'
{fs} = require 'atom'
Dialog = require './dialog'
module.exports =
class MoveDialog extends Dialog
constructor: (@initialPath) ->
if fs.isDirectorySync(@initialPath)
prompt = 'Enter the new path for the directory.'
else
prompt = 'Enter the new path for the file.'
supe... |
Use coccyx subview tear down helper | ProjectMonitor.Views ||= {}
class ProjectMonitor.Views.HomeView extends Backbone.View
tagName: "ol"
className: "projects"
template: JST["backbone/templates/home"]
initialize: (options) ->
@_addTileView(tile) for tile in @collection.models
@collection.on 'reset', =>
for cid,view of @subViews
... | ProjectMonitor.Views ||= {}
class ProjectMonitor.Views.HomeView extends Backbone.View
tagName: "ol"
className: "projects"
template: JST["backbone/templates/home"]
initialize: (options) ->
@_addTileView(tile) for tile in @collection.models
@collection.on 'reset', =>
@.tearDownRegisteredSubViews(... |
Expand the "Thanks Obama" responses | # Description
# Blames Obama for everything that's bad in your life.
#
# Dependencies:
# "cheerio": "0.10.7",
# "request": "2.14.0"
#
# Configuration:
# None
#
# Commands:
# thanks obama - A random image from http://thanks-obama.tumblr.com
#
# Notes:
# It would be nice if we could load a larger sample of im... | # Description
# Blames Obama for everything that's bad in your life.
#
# Dependencies:
# "cheerio": "0.10.7",
# "request": "2.14.0"
#
# Configuration:
# None
#
# Commands:
# thanks obama - A random image from http://thanks-obama.tumblr.com
#
# Notes:
# It would be nice if we could load a larger sample of im... |
Clear project paths after view is created | _ = require 'underscore'
module.exports =
projectPaths: null
fuzzyFinderView: null
loadPathsTask: null
activate: (state) ->
rootView.command 'fuzzy-finder:toggle-file-finder', =>
@createView().toggleFileFinder()
rootView.command 'fuzzy-finder:toggle-buffer-finder', =>
@createView().toggleB... | _ = require 'underscore'
module.exports =
projectPaths: null
fuzzyFinderView: null
loadPathsTask: null
activate: (state) ->
rootView.command 'fuzzy-finder:toggle-file-finder', =>
@createView().toggleFileFinder()
rootView.command 'fuzzy-finder:toggle-buffer-finder', =>
@createView().toggleB... |
Fix HousingForm DataTable column properties | $ ->
$('.housing-location-table').DataTable({
dom: "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
pagingType: "simple_numbers",
"columnDefs": [
{
"orderable": false,
"targets": [5,6,7,8]
},
{
"searchable": false,
"targets": [2,3,4... | $ ->
$('.housing-location-table').DataTable({
dom: "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
pagingType: "simple_numbers",
"columnDefs": [
{
"orderable": false,
"targets": [2,3,7,8]
},
{
"searchable": false,
"targets": [2,3,4... |
Add unit test for GET /CloudHealthCheck | "use strict"
request = require 'supertest'
assert = require 'assert'
app = req = null
before ->
app = module.parent.exports.app
req = request(app)
describe '/CloudHealthCheck', ->
it 'should return status for MongoDB and Redis', (done) ->
key = 'b523ceb5e16fb92b2a999676a87698d1'
req.get('/CloudHe... | |
Kill process when task is aborted | _ = require 'underscore'
BufferedProcess = require 'buffered-process'
$ = require 'jquery'
module.exports =
class LoadPathsTask
aborted: false
constructor: (@callback) ->
start: ->
rootPath = project.getPath()
ignoredNames = config.get('fuzzyFinder.ignoredNames') ? []
ignoredNames = ignoredNames.co... | _ = require 'underscore'
BufferedProcess = require 'buffered-process'
$ = require 'jquery'
module.exports =
class LoadPathsTask
aborted: false
constructor: (@callback) ->
start: ->
rootPath = project.getPath()
ignoredNames = config.get('fuzzyFinder.ignoredNames') ? []
ignoredNames = ignoredNames.co... |
Allow any comment about l[ou]lz | # lulz - BRING THE LOLZ from bukk.it
Select = require("soupselect").select
HtmlParser = require "htmlparser"
util = require 'util'
module.exports = (robot) ->
robot.respond /l[ou]lz/i, (msg) ->
msg.http("http://bukk.it")
.get() (err, res, body) ->
handler = new HtmlParser.DefaultHandler()
... | # lulz - BRING THE LOLZ from bukk.it
Select = require("soupselect").select
HtmlParser = require "htmlparser"
module.exports = (robot) ->
robot.respond /.*l[ou]lz/i, (msg) ->
msg.http("http://bukk.it")
.get() (err, res, body) ->
handler = new HtmlParser.DefaultHandler()
parser = new Ht... |
Create view to auto save a checkbox | Dashboard.AutoSaveCheckboxView = Ember.View.extend
template: Ember.Handlebars.compile("{{input type='checkbox' checked=view.attr}}")
tagName: 'span'
attributeBindings: [
'attr'
'resource'
]
didInsertElement: ->
self = this
@$('input').on 'change', ->
self.set('attr', $(this).is(':check... | |
Add task to publish packages | async = require 'async'
request = require 'request'
# Configure and publish all packages in package.json to atom.io
#
# This task should be run whenever you want to be sure that atom.io contains
# all the packages and versions referenced in Atom's package.json file.
module.exports = (grunt) ->
baseUrl = "https://git... | |
Disable built-in help for the lulz | module.exports = (robot) ->
lulz = ['lol', 'rofl', 'lmao']
robot.respond /lulz/i, (res) ->
res.send res.random lulz
robot.listenerMiddleware (context, next, done) ->
# console.log context.response.message
if context.response.message.text == 'pjcbot help'
context.response.send context.response.... | |
Write test coverage for ViewCache | describe "Marowak.ViewCache", ->
beforeEach ->
@cache = new Marowak.ViewCache
@view = new Backbone.View
@cid = 1
@cache.add @cid, @view
describe "#fetch", ->
it 'retrieves a view by a corresponding id', ->
expect(@cache.fetch(@cid)).toBe @view
describe "#remove", ->
it 'deletes a ... | |
Add expected section relationship behavior of indicators | suite('Indicator Model')
test('when initialised with no section attribute, it creates and empty section collection', ->
indicator = new Backbone.Models.Indicator(section: null)
assert.strictEqual indicator.get('sections').constructor.name, 'SectionCollection'
)
test('when initialised with sections attributes,
... | |
Add context menu entry for setting a breakpoint | 'context-menu':
'atom-text-editor': [
{
label: 'Debug'
submenu: [
{label: 'Toggle Breakpoint', command: 'debugger:toggle-breakpoint-at-current-line'}
]
}
]
| |
Add simple variable default and retrieve module. | ###*
# @overview This module loads default variables in to the Stout UI variable
# system which can shared compiled variables between SASS and JavaScript with
# support for extension.
# @module vars/default
###
err = require 'stout-core/err'
reduce = require 'lodash/reduce'
variables = {}
###*
# Parses the passed... | |
Add stub for model tests |
describe 'MinimapModel', ->
[workspaceElement, editor, editorView] = []
beforeEach ->
waitsForPromise ->
atom.workspace.open('sample.js')
runs ->
workspaceElement = atom.views.getView(atom.workspace)
jasmine.attachToDOM(workspaceElement)
atom.config.set 'minimap.autoToggle', false... | |
Add menu to toggle command palette | 'menu': [
{
'label': 'View'
'submenu': [
{
'label': 'Toggle Command Palette'
'command': 'command-palette:toggle'
}
]
}
{
'label': 'Packages'
'submenu': [
{
'label': 'Command Palette',
'submenu': [
{
'label': 'Toggle'
... | |
Add some Coffeescript to fetch our latest Tumblr blog post. | Tumblr = Tumblr or {}
Tumblr.RecentPosts = (el, postsCount) ->
apiUrl = "http://blog.hello-base.com/api/read/json?callback=?&filter=text&num=" + (postsCount or 10)
titleTypes =
regular: "regular-title"
link: "link-text"
quote: "quote-source"
photo: "photo-caption"
conversation: "conversation-tit... | |
Add component to resize buffers | noflo = require 'noflo'
sharp = require 'sharp'
Canvas = require('noflo-canvas').canvas
# @runtime noflo-nodejs
# @name ResizeBuffer
exports.getComponent = ->
c = new noflo.Component
c.icon = 'expand'
c.description = 'Resize a given image buffer to a new dimension'
c.inPorts.add 'buffer',
datatype: 'obj... | |
Add basic Message Registry class |
class MessageRegistry
constructor: (@linter)->
@messages = new Map()
set: (linter, messages) ->
@classifyMessages(messages)
@messages.set(linter, messages)
delete: (linter) ->
@messages.delete(linter)
get: ->
@messages
classifyMessages: (messages)->
isProject = @linter.state.scop... | |
Add the ability to query status for a PR | # Description:
# Get the CI status reported to GitHub for a repo and pull request
#
# Dependencies:
# "githubot": "0.4.x"
#
# Configuration:
# HUBOT_GITHUB_TOKEN
# HUBOT_GITHUB_USER
# HUBOT_GITHUB_API
#
# Commands:
# hubot repo show <repo> - shows activity of repository
#
# Notes:
# HUBOT_GITHUB_API allow... | |
Add specs for Message Registry | describe 'message-registry', ->
MessageRegistry = require('../lib/messages')
EditorLinter = require('../lib/editor-linter')
LinterRegistry = require('../lib/linter-registry')
getLinterRegistry = ->
linterRegistry = new LinterRegistry
editorLinter = new EditorLinter(atom.workspace.getActiveTextEditor())
... | |
Add indementent chart component draft | # # https://github.com/jhudson8/react-chartjs/blob/master/dist/react-chartjs.js
## Example
# PieChart = CustomChart.Pie
# MyComponent = React.createClass
# render: ->
# React.createElement PieChart
# data: chartData
# options: chartOptions
@CustomChart = (chartType) ->
console.log chartType
c... | |
Include source file for AreaTable entity | r = require('restructure')
Entity = require('../entity')
LocalizedStringRef = require('../localized-string-ref')
module.exports = Entity(
id: r.uint32le
mapID: r.uint32le
parentID: r.uint32le
areaBit: r.uint32le
flags: r.uint32le
soundPreferenceID: r.uint32le
underwaterSoundPreferenceID: r.uint32le
so... | |
Add spec toggle auto run | RubocopAutoCorrect = require '../lib/rubocop-auto-correct'
describe "RubocopAutoCorrect", ->
beforeEach ->
atom.config.set('rubocop-auto-correct.autoRun', false)
it "toggle auto run", ->
@rubocopAutoCorrect = new RubocopAutoCorrect
expect(atom.config.get('rubocop-auto-correct').autoRun).toBe false
... | |
Hide and unset categories when filtering by followed artists | Backbone = require 'backbone'
template = -> require('./index.jade') arguments...
module.exports = class CategoryFilterView extends Backbone.View
events:
'click .cf-categories__category' : 'toggleCategory'
initialize: ({ @params, @aggregations, @categoryMap }) ->
throw new Error "Requires a params model" ... | Backbone = require 'backbone'
template = -> require('./index.jade') arguments...
module.exports = class CategoryFilterView extends Backbone.View
events:
'click .cf-categories__category' : 'toggleCategory'
initialize: ({ @params, @aggregations, @categoryMap }) ->
throw new Error "Requires a params model" ... |
Add helper script for extracting list of options and languages | jsonStringify = require('json-stable-stringify')
Languages = require('../src/languages')
languages = new Languages().languages
# console.log(languages.length)
_ = require('lodash')
# options = _.chain(languages)
# .map((lang) -> return lang.options or [])
# .flatten()
# .reduce((resu... | |
Add class on main section. | `import Em from "vendor/ember"`
Component = Em.Component.extend
type: Em.computed "content.type", -> "oxisection-" + @get "content.type"
actions:
buttonClick: (button) ->
Em.set button, "loading", true
if button.action
@container.lookup("route:openxpki").sendAjax... | `import Em from "vendor/ember"`
Component = Em.Component.extend
classNameBindings: ["type"]
type: Em.computed "content.type", -> "oxisection-" + @get "content.type"
actions:
buttonClick: (button) ->
Em.set button, "loading", true
if button.action
@container... |
Update to imageButton for android | root.ImageButton_Framework_Android = class ImageButton_Framework_Android extends root.ImageButton_Framework
constructor:(options = {}) ->
options = root._.extend {}, options
super options
createBackButton: (settings) =>
createButton: (settings) =>
@button = Ti.UI.createView {
height: ... | |
Add the test cases for OrderItemBuilder.coffee | #= require jquery
#= require jasmine-jquery
#= require comable/admin/order_item_builder
describe 'OrderItemBuilder', ->
described_class = null
subject = null
beforeEach ->
described_class = OrderItemBuilder
subject = described_class.prototype
describe '#fillOrderItem', ->
variant = {
id: 1
... | |
Add a request to get all recurring events | cozydb = require 'cozydb'
tagsView =
map: (doc) ->
doc.tags?.forEach? (tag, index) ->
type = if index is 0 then 'calendar' else 'tag'
emit [type, tag], true
reduce: "_count"
module.exports =
tag:
byName : cozydb.defaultRequests.by 'name'
alarm:
a... | cozydb = require 'cozydb'
tagsView =
map: (doc) ->
doc.tags?.forEach? (tag, index) ->
type = if index is 0 then 'calendar' else 'tag'
emit [type, tag], true
reduce: "_count"
module.exports =
tag:
byName : cozydb.defaultRequests.by 'name'
alarm:
a... |
Enable multi language filter in projects_path | $ ->
projects = $('#projects').clone()
$('#languages a').click (e) ->
language = $(this).data().language
$('#noprojects').hide()
if language?
language = [language] unless $.isArray(language)
$('#languages li')
.addClass('disabled')
.find($.map(language, (l) -> "a[data-lan... | $ ->
projects = $('#projects').clone()
languages = []
$('#languages a').click (e) ->
clicked_language = $(this).data().language
unless clicked_language?
$('#languages li').removeClass('disabled')
$('#projects').html(projects.find('.project'))
projects = $('#projects').clone()
$('... |
Add integration test for states (create, update, delete) | _ = require 'underscore'
Q = require 'q'
SphereClient = require '../../lib/client'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newState = ->
key: uniqueId 's'
type: 'LineItemState'
updateState = (version) ->
version: version
actions: [
{... | |
Add example purely for output demonstration | Quest = require '../../src/quest'
module.exports =
class OutputExampleQuest extends Quest
adventure: ->
console.log "So, what's a person like?".bold
@sql """
CREATE TEMP TABLE people (
name varchar(256),
birthdate date,
title varchar(256)
);
"""
... | |
Disable code folding in Atom | # Your init script
#
# Atom will evaluate this file each time a new window is opened. It is run
# after packages are loaded/activated and after the previous editor state
# has been restored.
#
# An example hack to log to the console when each text editor is saved.
#
# atom.workspace.observeTextEditors (editor) ->
# e... | |
Test cases for handling default function | describe 'Overloadad functions', ->
overloadableFunction = null
spiedFunction = jasmine.createSpy()
describe 'Default function', ->
it 'should throw error when default function isn\'t undefined or a function', ->
func = null
for item in [7, 'foo', true, null, {}... | |
Add grunt task to download release assets. | fs = require 'fs'
path = require 'path'
os = require 'os'
minimatch = require 'minimatch'
GitHub = require '../lib/github'
module.exports = (grunt) ->
taskName = 'download-github-releases'
grunt.registerTask taskName, 'Download assets from GitHub Releases', ->
done = @async()
config ... | |
Add some unit tests for preprocessor | #==============================================================================
# lib/preprocessor.js module
#==============================================================================
describe 'preprocessor', ->
util = require '../test-util'
mocks = require 'mocks'
m = pp = mockFs = doneSpy = fakePreprocess... | |
Remove page actions buttons on overview section | Augury.Views.Home.Index = Backbone.View.extend(
initialize: ->
render: ->
@env = _(Augury.connections).findWhere(id: Augury.env.id)
@$el.html JST["admin/templates/home/index"](env: @env)
$('#content-header').find('.page-title').text('Overview')
this
)
| Augury.Views.Home.Index = Backbone.View.extend(
initialize: ->
render: ->
@env = _(Augury.connections).findWhere(id: Augury.env.id)
@$el.html JST["admin/templates/home/index"](env: @env)
$('#content-header').find('.page-actions').remove()
$('#content-header').find('.page-title').text('Overview')
... |
Apply button does not jump to "Apply" | _ = require 'underscore'
Backbone = require 'backbone'
View = require './view.coffee'
Jump = require '../../../components/jump/view.coffee'
module.exports = class PartnershipsRouter extends Backbone.Router
routes:
'gallery-partnerships': 'toTop'
'gallery-partnerships/:slug': 'toSection'
'institution-part... | _ = require 'underscore'
Backbone = require 'backbone'
View = require './view.coffee'
Jump = require '../../../components/jump/view.coffee'
module.exports = class PartnershipsRouter extends Backbone.Router
routes:
'gallery-partnerships': 'toTop'
'gallery-partnerships/:slug': 'toSection'
'institution-part... |
Remove uncapitalize from artist route | #
# The artist page found at /artist/:id.
#
express = require 'express'
routes = require './routes'
sections = require './sections'
timeout = require 'connect-timeout'
uncapitalize = require 'express-uncapitalize'
app = module.exports = express()
app.set 'views', __dirname + '/templates'
app.set 'view engine', 'jade'... | #
# The artist page found at /artist/:id.
#
express = require 'express'
routes = require './routes'
sections = require './sections'
timeout = require 'connect-timeout'
app = module.exports = express()
app.set 'views', __dirname + '/templates'
app.set 'view engine', 'jade'
app.get '/artist/:id/follow', routes.follow
... |
Allow Hubot to fetch app performance stats from New Relic | # Display current app performance stats from New Relic
#
# You need to set the following variables:
# HUBOT_NEWRELIC_ACCOUNT_ID = "<Account ID>"
# HUBOT_NEWRELIC_APP_ID = "<Application ID>"
# HUBOT_NEWRELIC_API_KEY = "<API Key>"
#
# How to find these settings:
# After signing into New Relic, select your... | |
Add joke me from /r/jokes | # joke me - Pull a random joke from /r/jokes
module.exports = (robot) ->
robot.respond /joke me/i, (msg) ->
msg.http('http://www.reddit.com/r/jokes.json')
.get() (err, res, body) ->
try
data = JSON.parse body
children = data.data.children
joke = msg.random(children).d... | |
Create base class for common context menu on credential and stack list. | kd = require 'kd'
JView = require 'app/jview'
KDButtonViewWithMenu = kd.ButtonViewWithMenu
ActivityItemMenuItem = require 'activity/views/activityitemmenuitem'
module.exports = class BaseStackTemplateListItem extends kd.ListItemView
JView.mixin @prototype
constructor: (optio... | |
Use parameter instead of ivar | DeferredAtomPackage = require 'deferred-atom-package'
LoadPathsTask = require './src/load-paths-task'
module.exports =
class FuzzyFinder extends DeferredAtomPackage
loadEvents: [
'fuzzy-finder:toggle-file-finder'
'fuzzy-finder:toggle-buffer-finder'
'fuzzy-finder:find-under-cursor'
]
instanceClass: '... | DeferredAtomPackage = require 'deferred-atom-package'
LoadPathsTask = require './src/load-paths-task'
module.exports =
class FuzzyFinder extends DeferredAtomPackage
loadEvents: [
'fuzzy-finder:toggle-file-finder'
'fuzzy-finder:toggle-buffer-finder'
'fuzzy-finder:find-under-cursor'
]
instanceClass: '... |
Add bootstrap slider react component | Slider = React.createClass(
getDefaultProps: ->
{
min: 0
max: 100
step: 1
value: 50
toolTip: false
onSlide: ->
}
handleSlide: (event) ->
@props.onSlide event.value
componentWillUpdate: (nextProps, nextState) ->
nextState.slider.val nextProps.value
component... | |
Add publisher script for Nu.nl | ###
// ==UserScript==
// @name Factlink Publisher Pluging for Nu.nl
// @description Enable Factlink on Nu.nl
// @include http*://*.nu.nl/*
// @version 0.0.1
// @grant unsafeWindow
// ==/UserScript==
###
# Compile this file using: coffee -c <filename>
# Drag the compiled file (<name>.user.js) to chrome://extensions to... | |
Add a lightweight JSON-RPC implementation | kopi.module("kopi.jsonrpc")
.require("kopi.exceptions")
.request("kopi.utils")
.define (exports, exceptions, utils) ->
###
A lightweight JSON-RPC message wrapper
###
MESSAGE_PREFIX = "kopi-message"
JSON_RPC_VERSION = "2.0"
###
Build a request
###
request = (id, method, params... | |
Fix scroll on spacebar press | # Taken from https://gist.github.com/leshniak/f3b163b23bbfac5dad313b628f3c09ac
# Fixes scrolling on space key in atom-text-editor.mini
fixScrollOnSpace = () =>
editorSelector = 'atom-text-editor[mini]'
handleSpace = (event) =>
return if event.keyCode != 32 # do nothing if not a space key
el = ... | |
Add unit tests for /login and /logout | "use strict"
assert = require 'assert'
server = require '../coffee/server.coffee'
exports.cookie = cookie = null
describe '/login', ->
it 'should server a login page', (done) ->
server.inject method: 'GET', url: '/login', (res) ->
assert.equal res.statusCode, 200
assert /<input type="text" name="us... | |
Return the router object when initializing filter | Backbone = require 'backbone'
ArtworkFilterRouter = require './router.coffee'
module.exports.init = (options = {}) ->
new ArtworkFilterRouter options
require './analytics.coffee'
Backbone.history.start(pushState: true) unless Backbone.History.started
| Backbone = require 'backbone'
ArtworkFilterRouter = require './router.coffee'
module.exports.init = (options = {}) ->
router = new ArtworkFilterRouter options
require './analytics.coffee'
Backbone.history.start(pushState: true) unless Backbone.History.started
router
|
Use temp dir in specs | fs = require 'fs'
path = require 'path'
grunt = require 'grunt'
temp = require 'temp'
describe 'create-windows-installer task', ->
it 'creates a nuget package', ->
outputDirectory = __dirname
grunt.config.init
pkg: grunt.file.readJSON(path.join(__dirname, 'fixtures', 'app', 'resources', 'app', 'packa... | fs = require 'fs'
path = require 'path'
grunt = require 'grunt'
temp = require 'temp'
describe 'create-windows-installer task', ->
it 'creates a nuget package', ->
outputDirectory = temp.mkdirSync('grunt-atom-shell-installer-')
grunt.config.init
pkg: grunt.file.readJSON(path.join(__dirname, 'fixtures... |
Add Rewinder test. Works on Node 0.10, fails on Node 0.12 | RewindBuffer = $src "rewind_buffer"
FileSource = $src "sources/file"
Logger = $src "logger"
mp3 = $file "mp3/mp3-44100-128-s.mp3"
class BytesReceived extends require("stream").Writable
constructor: ->
super
@bytes = 0
_write: (chunk,encoding,cb) ->
@bytes += chunk.len... | |
Create view helper for getShortTaskIDMiddleEllipsis utils method | Handlebars.registerHelper 'ifEqual', (v1, v2, options) -> if v1 is v2 then options.fn @ else options.inverse @
Handlebars.registerHelper 'ifLT', (v1, v2, options) -> if v1 < v2 then options.fn @ else options.inverse @
Handlebars.registerHelper 'ifGT', (v1, v2, options) -> if v1 > v2 then options.fn @ else options.inver... | Handlebars.registerHelper 'ifEqual', (v1, v2, options) -> if v1 is v2 then options.fn @ else options.inverse @
Handlebars.registerHelper 'ifLT', (v1, v2, options) -> if v1 < v2 then options.fn @ else options.inverse @
Handlebars.registerHelper 'ifGT', (v1, v2, options) -> if v1 > v2 then options.fn @ else options.inver... |
Add a redux like store as the successor | # TODO-2 try to load the state from local storage.
# BUT if there's no cookie, then act like local storage isn't there.
# Also, state changes should update the data in local storage as well.
listeners = []
state = window.preload or {}
reducer = ->
module.exports = {
setReducer: (fn) ->
reducer = fn
s... | |
Mark Notification public and add docs | {Emitter} = require 'event-kit'
# Experimental: This will likely change, do not use.
module.exports =
class Notification
constructor: (@type, @message, @options={}) ->
@emitter = new Emitter
@timestamp = new Date()
@dismissed = true
@dismissed = false if @isDismissable()
@displayed = false
onD... | {Emitter} = require 'event-kit'
# Public: A notification to the user containing a message and type.
module.exports =
class Notification
constructor: (@type, @message, @options={}) ->
@emitter = new Emitter
@timestamp = new Date()
@dismissed = true
@dismissed = false if @isDismissable()
@displayed... |
Create radio button coffee script | root = exports ? this
RadioButtonsModule =
bindToRadioButtons: ->
$('input[type=radio]').on 'change', ->
$("[name='" + $(this).attr('name') + "']").parent().removeClass("selected")
$(this).parent().addClass('selected')
setup: ->
RadioButtonsModule.bindToRadioButtons()
root.RadioButtonsModule... | |
Change git next/prev diff keys | '.atom-text-editor':
'alt-g down': 'unset!'
'alt-g j': 'git-diff:move-to-next-diff'
'alt-g up': 'unset!'
'alt-g k': 'git-diff:move-to-previous-diff'
| |
Add a suite of helper functions in CoffeeScript | {toString} = Object.prototype
# Uppercase the first letter of a string
ucFirst = (value) ->
value.replace /\b(\w)(.*$)/g, (match, firstLetter, remainder) ->
firstLetter.toUpperCase() + remainder
# Type-checking helpers
isArray = (value) -> "[object Array]" is toString.call(value)
isObject = (value) -> "[object ... | |
Add BobCat JS file for BobCat files. | # Require 'nyulibraries'
# = require nyulibraries
$ ->
# BobCat Tabs Tips
new window.popover.Popover(".nav-tabs li a").init()
new window.popover.PartialHoverPopover("#account h2 a").init()
| |
Add a simple test case for desktopCapturer | assert = require 'assert'
{desktopCapturer} = require 'electron'
describe 'desktopCapturer', ->
it 'should returns something', (done) ->
desktopCapturer.getSources {types: ['window', 'screen']}, (error, sources) ->
assert.equal error, null
assert.notEqual sources.length, 0
done()
| |
Add basic request handling node server | sys = require 'sys'
http = require 'http'
http.createServer((request, response) ->
sys.puts 'I got kicked'
response.writeHeader 200, {"Content-Type": "text/plain"}
response.write 'It works!'
response.end()
).listen 8080
sys.puts 'Listening on port 8080'
| |
Add Chat js handling logic | window.InteractionWebTools ||= {}
window.InteractionWebTools.chat = new Chat
$ ->
InteractionWebTools.chat.receiveMessages()
$(document).on 'submit', 'form.chat-message-form', (e) ->
e.preventDefault()
input = $(@).find 'input[name=content]'
InteractionWebTools.chat.sendMessage input.val()
input.val ''
fa... | |
Add spec for required ports | if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1
chai = require 'chai' unless chai
component = require '../src/lib/Component.coffee'
port = require '../src/lib/Port.coffee'
socket = require '../src/lib/InternalSocket.coffee'
else
component = require 'noflo/s... | |
Fix a silly error from changing approach midway. | # Description:
# Report the status of a Minecraft server
# Uses http://api.syfaro.net/
#
# Dependencies:
# None
#
# Configuration:
# server_url and server_port, below
#
# Commands:
# mcstatus - Report the status of the configured minecraft server.
#
# Author:
# annabunches
default_url = 'mc.wtf.cat'
defaul... | # Description:
# Report the status of a Minecraft server
# Uses http://api.syfaro.net/
#
# Dependencies:
# None
#
# Configuration:
# server_url and server_port, below
#
# Commands:
# mcstatus - Report the status of the configured minecraft server.
#
# Author:
# annabunches
default_url = 'mc.wtf.cat'
defaul... |
Add test script using Dialog | Path = require "path"
Dialog = require Path.join __dirname, "..", "src", "dialog"
module.exports = (robot) ->
# robot.hear /.*/i, (msg) ->
# dialog = Dialog.getDialog msg.envelope.user.name, msg.envelope.room
# console.log dialog
# dialog?.callback.call dialog, msg
robot.respond /dialog/i, (msg) ->
... | |
Include ImageSizes for featured links | _ = require 'underscore'
Backbone = require 'backbone'
Items = require '../collections/items.coffee'
LayoutSyle = require './mixins/layout_style.coffee'
{ Image, Markdown } = require 'artsy-backbone-mixins'
{ SECURE_IMAGES_URL } = require('sharify').data
module.exports = class FeaturedLink extends Backbone.Model
_.e... | _ = require 'underscore'
Backbone = require 'backbone'
Items = require '../collections/items.coffee'
LayoutSyle = require './mixins/layout_style.coffee'
{ Image, Markdown } = require 'artsy-backbone-mixins'
{ SECURE_IMAGES_URL } = require('sharify').data
ImageSizes = require './mixins/image_sizes.coffee'
module.export... |
Add some basic linter-behavior specs | describe 'Linter Behavior', ->
linter = null
linterState = null
bottomContainer = null
trigger = (el, name) ->
event = document.createEvent('HTMLEvents');
event.initEvent(name, true, false);
el.dispatchEvent(event);
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage('linter... | |
Reset data for each test | DB = require '../lib/db'
describe "DB", ->
db = null
test1 = off
test2 = off
data =
testproject1:
title: "Test project 1"
group: "Test"
paths: [
"/Users/project-1"
]
testproject2:
title: "Test project 2"
paths: [
"/Users/project-2"
]
before... | DB = require '../lib/db'
describe "DB", ->
db = null
data = null
beforeEach ->
db = new DB()
data =
testproject1:
title: "Test project 1"
group: "Test"
paths: [
"/Users/project-1"
]
testproject2:
title: "Test project 2"
paths: [
... |
Remove the explicit for_sale filter and instead sort works by -decayed_merch on mobile web | _ = require 'underscore'
Backbone = require 'backbone'
qs = require 'qs'
FilterArtworks = require '../../collections/filter_artworks.coffee'
FilterView = require './view.coffee'
{ FILTER_ROOT } = require('sharify').data
module.exports =
setupFilter: (options) ->
defaults =
startHistory: yes
{ aggrega... | _ = require 'underscore'
Backbone = require 'backbone'
qs = require 'qs'
FilterArtworks = require '../../collections/filter_artworks.coffee'
FilterView = require './view.coffee'
{ FILTER_ROOT } = require('sharify').data
module.exports =
setupFilter: (options) ->
defaults =
startHistory: yes
{ aggrega... |
Add Programmer class (for updating firmware) | "use strict"
# Pre dependencies
# (none)
###*
@class Programmer
Firmware updater class
###
module.exports = class Programmer
null
#--------------------------------------------------------------------------------
# Public methods
#
#-------------------------------------------------------------------------... | |
Add tests for changing node properties | global.window = { location: '' }
chai = require('chai')
chai.config.includeStack = true
expect = chai.expect
should = chai.should()
Sinon = require('sinon')
requireModel = (name) -> require "#{__dirname}/../src/code/models/#{name}"
Node = requireModel 'node'
GraphStore = requir... | |
Add test for simple cors over spdy | class SimpleCorsSpdyTest
constructor: ($http) ->
@result = "pending"
@display_name = "Simple CORS over SPDY"
@$http = $http
run: ->
a = Math.floor((Math.random() * 100000) + 1)
b = Math.floor((Math.random() * 100000) + 1)
@$http(
method: "GET"
url: "https://corstest-api.coshx.co... | |
Add tests for layout mixins. | jest.autoMockOff()
fs = require 'fs'
path = require 'path'
sass = require 'node-sass'
css = require 'css'
renderSass = (sass_source) ->
output = sass.renderSync
data: """
@import "marquee"
#{ sass_source }
"""
... | |
Add rad json matcher with legit output on failure | _ = require 'underscore'
beforeEach ->
@addMatchers
toEqualJson: (expected) ->
failures = {}
class Failure
constructor: (@path, @actual, @expected) ->
getMessage: ->
"""
#{@path}:
actual: #{@actual}
expected: #{@expected}
"""
... | |
Add promises marking when the containing body is in various stages of completion | ready = $.Deferred()
complete = $.Deferred()
if /^(interactive|complete)$/.test(document.readyState)
ready.resolve()
else
document.addEventListener('DOMContentLoaded', -> ready.resolve())
if 'complete' == document.readyState
complete.resolve()
else
console.log "queuing handler since we're in state #{document.... | |
Add script to convert the data to multiple yaml files | #!/usr/bin/env coffee
#
# Copyright (C) 2015 by EatOutBerlin
#
fs = require 'fs'
yaml = require 'js-yaml'
colors = require 'colors/safe'
path = require 'path'
diff = require 'diff'
mkdirp = require 'mkdirp'
INPUT_FILE = path.join 'data', 'places.json'
OUTPUT_DIR = path.join 'data', 'places'
OUTPUT_FILE = 'place.yaml'... | |
Add a basic build success/failure notifier endpoint | # Description
# Notifies based on the results of xcode builds and controls xcode builds
#
# Dependencies
# None
#
# Configuration
# None
#
# Commands:
# hubot build <bot name> - Start a build for bot named <bot name> UNIMPLEMENTED
#
# Author:
# bmnick
url = require('url')
querystring = require('querystring')... | |
Add menu item for package | 'menu': [
{
'label': 'Packages'
'submenu': [
'label': 'Autosave Onchange'
'submenu': [
{
'label': 'Toggle'
'command': 'autosave-delay:toggle'
}
]
]
}
]
| |
Abort task when view is created | _ = require 'underscore'
module.exports =
projectPaths: null
fuzzyFinderView: null
loadPathsTask: null
activate: (state) ->
rootView.command 'fuzzy-finder:toggle-file-finder', =>
@createView().toggleFileFinder()
rootView.command 'fuzzy-finder:toggle-buffer-finder', =>
@createView().toggleB... | _ = require 'underscore'
module.exports =
projectPaths: null
fuzzyFinderView: null
loadPathsTask: null
activate: (state) ->
rootView.command 'fuzzy-finder:toggle-file-finder', =>
@createView().toggleFileFinder()
rootView.command 'fuzzy-finder:toggle-buffer-finder', =>
@createView().toggleB... |
Create an internationalization module which uses associative array and manage language from url | module.exports = (env, callback) ->
lang_FR = [
'LAB_KEYWORDS' : 'Mots clés',
'LAB_DEMOS' : 'Démos & Projets',
'LAB_MORE' : 'Voir plus',
'LAB_HOME' : 'Accueil',
'LAB_EXPERIENCES' : 'Expériences',
'LAB_COMPETENCES' : 'Compétences',
'LAB_FORMATI... | |
Extend _ with utility functions for type checking |
_.mixin
# Tests if the instance of an object is a subtype of a given class. (Note that this only works for coffeescript classes)
# @param [Object] An instance of an object
# @param [Function] The class to test
# @return [Boolean] true if the object is a subtype of class otherwise false
isKindOf: (object, cl... | |
Add publisher script for Nu.nl | ###
// ==UserScript==
// @name Factlink Publisher Pluging for Nu.nl
// @description Enable Factlink on Nu.nl
// @include http*://*.nu.nl/*
// @version 0.0.1
// @grant unsafeWindow
// ==/UserScript==
###
# Compile this file using: coffee -c <filename>
# Drag the compiled file (<name>.user.js) to chrome://extensions to... | |
Create a new KodingListController instance for InvitationsListController | kd = require 'kd'
remote = require('app/remote').getInstance()
InvitedItemView = require './inviteditemview'
KDNotificationView = kd.NotificationView
KodingListController = require 'app/kodinglist/kodinglistcontroller'
module.exports = class InvitationsListController extend... | |
Add publisher script for Nu.nl | ###
// ==UserScript==
// @name Factlink Publisher Pluging for Nu.nl
// @description Enable Factlink on Nu.nl
// @include http*://*.nu.nl/*
// @version 0.0.1
// @grant unsafeWindow
// ==/UserScript==
###
# Compile this file using: coffee -c <filename>
# Drag the compiled file (<name>.user.js) to chrome://extensions to... | |
Add migration to enable trackChanges for all users | Settings = require "settings-sharelatex"
fs = require("fs")
mongojs = require("mongojs")
ObjectId = mongojs.ObjectId
db = mongojs(Settings.mongo.url, ['users'])
_ = require("underscore")
BSON = db.bson.BSON
handleExit = () ->
console.log('Got signal. Shutting down.')
process.on 'SIGINT', handleExit
process.on 'SI... | |
Add some view specs for set password flow | jade = require 'jade'
path = require 'path'
fs = require 'fs'
cheerio = require 'cheerio'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe "Auth Templates", ->
describe "forgot",... | |
Add spec for download image route | _ = require 'underscore'
Q = require 'bluebird-q'
sinon = require 'sinon'
Backbone = require 'backbone'
request = require 'superagent'
{ fabricate } = require 'antigravity'
routes = require '../routes'
CurrentUser = require '../../../models/current_user'
Artwork = require '../../../models/artwork'
describe 'Artwork ro... | |
Use guest user name if already registered | Meteor.methods
sendMessageLivechat: (message) ->
if s.trim(message.msg) isnt ''
if isNaN(TimeSync.serverOffset())
message.ts = new Date()
else
message.ts = new Date(Date.now() + TimeSync.serverOffset())
message.u =
_id: Meteor.userId()
username: 'visitor'
message.temp = true
# mess... | Meteor.methods
sendMessageLivechat: (message) ->
if s.trim(message.msg) isnt ''
if isNaN(TimeSync.serverOffset())
message.ts = new Date()
else
message.ts = new Date(Date.now() + TimeSync.serverOffset())
message.u =
_id: Meteor.userId()
username: Meteor.user()?.username || 'visitor'
mes... |
Update rule item view when rule is updated. | class EnvironmentRuleItem extends EnvironmentItem
constructor: (options = {}, data) ->
options.cssClass = 'rule'
options.joints = ['right']
options.allowedConnections =
EnvironmentDomainItem : ['left']
super options, data
contextMenuItems: ->
colorSelection = n... | class EnvironmentRuleItem extends EnvironmentItem
constructor: (options = {}, data) ->
options.cssClass = 'rule'
options.joints = ['right']
options.allowedConnections =
EnvironmentDomainItem : ['left']
super options, data
contextMenuItems: ->
colorSelection = n... |
Add keybindings for win32 and linux | # Keybindings require three things to be fully defined: A selector that is
# matched against the focused element, the keystroke and the command to
# execute.
#
# Below is a basic keybinding which registers on all platforms by applying to
# the root workspace element.
# For more detailed documentation see
# https://ato... | # Keybindings require three things to be fully defined: A selector that is
# matched against the focused element, the keystroke and the command to
# execute.
#
# Below is a basic keybinding which registers on all platforms by applying to
# the root workspace element.
# For more detailed documentation see
# https://ato... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.