Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Update settings, add Command testing | _ = require "underscore"
module.exports = (target, source) ->
_.extend {}, target, _.pick(source, [
"commandId"
"stepId"
"userId"
"avatarId"
]) | _ = require "underscore"
module.exports = (target, source) ->
_.defaults {}, target, _.pick(source, [
"commandId"
"stepId"
"userId"
"avatarId"
])
|
Use app package.json file in spec | 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... | 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... |
Test also that error is passed to onError handler | # build-dependencies: bus
describe "EventStream.doError", ->
it "calls function before sending error to listeners", ->
called = []
bus = new Bacon.Bus()
s = bus.flatMap((x) -> new Bacon.Error(1)).doError((x) -> called.push(x))
s.onValue(->)
s.onError(->)
bus.push(1)
expect(called).to.deep.... | # build-dependencies: bus
describe "EventStream.doError", ->
it "calls function before sending error to listeners", ->
called = []
bus = new Bacon.Bus()
s = bus.flatMap((x) -> new Bacon.Error(1)).doError((x) -> called.push(x))
s.onValue(->)
s.onError((x) -> called.push(x+1))
bus.push(1)
ex... |
Create a model factory fot angular js | 'use strict'
describe 'ngDatabase model', ->
$model = null
beforeEach ->
module 'ngDatabase'
return
beforeEach ->
inject ($injector) ->
$model = $injector.get '$model'
return
return
it 'Should have findAll method', ->
expect(typeof $mod... | |
Add wrapper class for analytics. | ###
This class's function parameters are inspired by Segment.io. It's a light wrapper for it in case I decide to
switch analytics providers.
###
class @SpendflowStats
analyticsEnabled = false
Meteor.startup =>
if analytics? and Meteor.isClient then analyticsEnabled = true
SpendflowStats.isEnabled = ->
analyti... | |
Add an action that implies '.txt' at the end of a URL. | staticHandler= require('../static_handler')
mimeWrapper= require('../mime_wrapper')
hasAnExtension = require('../utilities').hasAnExtension
extensions= ['.txt']
# if adding .txt to the end of the path finds a file, serve the contents of that file
module.exports= implicitTextFileAction= (req,res,next) ->
try
ful... | |
Add JavaScript for Courses Listing Scroll | $ ->
# handle updating the width for scrolling through courses
width = 0
$(".courses-listing .course").each ->
width += $(this).outerWidth(true)
width += $(".courses-listing .course").outerWidth(true) / 3
$(".courses-listing").css "width", width + "px"
| |
Add menu item to jump to matching bracket | 'menu': [
{
'label': 'Packages'
'submenu': [
'label': 'Bracket Matcher'
'submenu': [
{ 'label': 'Go To Matching Bracket', 'command': 'bracket-matcher:go-to-matching-bracket' }
]
]
}
]
| |
Add pluggable performance measurement logger | load_moments = []
last_sorted = 0
add_timing_event = (name) ->
add_existing_timing_event name, new Date().getTime()
add_existing_timing_event = (name, time) ->
load_moments.push(Object.freeze(name:name, time: time, idx: load_moments.length))
get_sorted_moments = ->
if(load_moments.length > last_sorted)
loa... | |
Set useragent on api requests to github | NotificationPlugin = require "../../notification-plugin"
class GithubIssue extends NotificationPlugin
BASE_URL = "https://api.github.com"
stacktraceLines = (stacktrace) ->
("#{line.file}:#{line.lineNumber} - #{line.method}" for line in stacktrace when line.inProject)
markdownBody = (event) ->
"""
#... | NotificationPlugin = require "../../notification-plugin"
class GithubIssue extends NotificationPlugin
BASE_URL = "https://api.github.com"
stacktraceLines = (stacktrace) ->
("#{line.file}:#{line.lineNumber} - #{line.method}" for line in stacktrace when line.inProject)
markdownBody = (event) ->
"""
#... |
Expand things like merlin: and merlin-lax: to message the correct people. | # Expands a message to a named group of people into their individual names
#
# merlin: <your message>
merlin_remote_members = [
"Cliff Dickerson",
"michael.ivey",
]
merlin_lax_members = [
"Jesse Howarth",
"Josiah Kiehl",
"mmatsumura",
"Jamie Winsor"
]
merlin_members = merlin_remote_members.concat merlin_... | |
Add unit tests for metadata functions | should = require "should"
metadata = require "../../lib/api/metadata"
describe "Metadata Functions", ->
describe ".removeProperties", ->
it "should return an object with _id and __v removed from all objects in the object", (done) ->
object = {
_id: "11111",
__v: "test",
someProp: ... | |
Add initial 'who's turn' script | # Who's turn to do something ?
#
# who <does something> : <someone>, <someone>, <someone> ? - Returns who does !
#
module.exports = (robot) ->
robot.respond /(who|qui) (.+) : (.+) \?/i, (msg) ->
action = msg.match[2]
member = msg.random msg.match[3].split /[\s]*,[\s]*/
msg.send membe... | |
Add JS specs for Array extensions | #= require extensions/array
describe 'Array extensions', ->
describe 'first', ->
it 'returns the first item', ->
arr = [0, 1, 2, 3, 4, 5]
expect(arr.first()).toBe(0)
describe 'last', ->
it 'returns the last item', ->
arr = [0, 1, 2, 3, 4, 5]
expect(arr.last()).toBe(5)
| |
Move language information deducing functionality to workspace utils | {Point} = require('atom')
path = require('path')
languageRegistry = require('./language-registry').getInstance()
# ------------------------------------------------------------------------------
module.exports =
## Constants -----------------------------------------------------------------
... | |
Add a test for display of attribution_class on desktop | _ = require 'underscore'
jade = require 'jade'
cheerio = require 'cheerio'
path = require 'path'
fs = require 'fs'
{ fabricate } = require 'antigravity'
sinon = require 'sinon'
render = ->
filename = path.resolve __dirname, "../../index.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
... | |
Upgrade indicator selector to diorama 0.2.0 | window.Backbone ||= {}
window.Backbone.Views ||= {}
class Backbone.Views.IndicatorSelectorView extends Backbone.Diorama.NestingView
template: Handlebars.templates['indicator_selector.hbs']
className: 'modal indicator-selector'
events:
"click .close": "close"
"click .indicators li .info": "selectIndicato... | window.Backbone ||= {}
window.Backbone.Views ||= {}
class Backbone.Views.IndicatorSelectorView extends Backbone.Diorama.NestingView
template: Handlebars.templates['indicator_selector.hbs']
className: 'modal indicator-selector'
events:
"click .close": "close"
"click .indicators li .info": "selectIndicato... |
Add failing test getting non-existant attribute in continue tree | chai = require 'chai' unless chai
Choice = require '../lib/Choice'
Root = require '../lib/Root'
describe 'Subtrees', ->
describe 'non-existent attribute lookup in tree', ->
it 'should return null', (done) ->
direct = (orig, data) ->
subtree = orig.tree 'directcalc'
subtree.deliver data
... | |
Use working directory instead of project path | path = require 'path'
fs = require 'fs-plus'
FuzzyFinderView = require './fuzzy-finder-view'
module.exports =
class GitStatusView extends FuzzyFinderView
toggle: ->
if @hasParent()
@cancel()
else if atom.project.getRepo()?
@populate()
@attach()
getEmptyMessage: (itemCount) ->
if item... | path = require 'path'
fs = require 'fs-plus'
FuzzyFinderView = require './fuzzy-finder-view'
module.exports =
class GitStatusView extends FuzzyFinderView
toggle: ->
if @hasParent()
@cancel()
else if atom.project.getRepo()?
@populate()
@attach()
getEmptyMessage: (itemCount) ->
if item... |
Use presenter for rendering overlay decorations | module.exports =
class OverlayManager
constructor: (@container) ->
@overlays = {}
render: (props) ->
{presenter, editor, overlayDecorations} = props
lineHeight = presenter.getLineHeight()
existingDecorations = null
for markerId, {headPixelPosition, tailPixelPosition, decorations} of overlayDec... | module.exports =
class OverlayManager
constructor: (@container) ->
@overlayNodesById = {}
render: (props) ->
{presenter} = props
for decorationId, {pixelPosition, item} of presenter.state.content.overlays
@renderOverlay(presenter, decorationId, item, pixelPosition)
for id, overlayNode of @o... |
Add comment about filter permission | checkToken = require('../lib/token').checkToken
errors = require '../middlewares/errors'
module.exports.checkDevice = (req, res, next) ->
auth = req.header('authorization')
[err, isAuthenticated, name] = checkToken auth
if err or not isAuthenticated or not name
next errors.notAuthorized()
else
... | checkToken = require('../lib/token').checkToken
errors = require '../middlewares/errors'
module.exports.checkDevice = (req, res, next) ->
auth = req.header('authorization')
[err, isAuthenticated, name] = checkToken auth
# Device authorization is not necessary because filter name ensure
# permissions fo... |
Add a script for getting Captain Quail from Hubot. | # Description:
# The Adventures of Captain Quail, now in you chat!
#
# Dependencies:
# "htmlparser": "1.7.6"
# "soupselect": "0.2.0"
#
# Configuration:
# None
#
# Commands:
# hubot cq - The latest Adventures of Captain Quail
#
# Author:
# phildini
htmlparser = require "htmlparser"
Select = require("soupsel... | |
Make focus state distinct until changed on Focusable objects | Mixin = require 'mixto'
module.exports =
class Focusable extends Mixin
@included: ->
@property 'focusContext'
@behavior 'focused', ->
@$focusContext
.flatMapLatest((context) -> context?.$focusedObject)
.map((focusedObject) => focusedObject is this)
focus: ->
throw new Error("Obje... | Mixin = require 'mixto'
module.exports =
class Focusable extends Mixin
@included: ->
@property 'focusContext'
@behavior 'focused', ->
@$focusContext
.flatMapLatest((context) -> context?.$focusedObject)
.map((focusedObject) => focusedObject is this)
.distinctUntilChanged()
foc... |
Sort installed packages by name | ConfigPanel = require 'config-panel'
PackageConfigView = require 'package-config-view'
### Internal ###
module.exports =
class InstalledPackagesConfigPanel extends ConfigPanel
@content: ->
@div class: 'installed-packages'
initialize: ->
for pack in atom.getLoadedPackages()
@append(new PackageConfig... | _ = require 'underscore'
ConfigPanel = require 'config-panel'
PackageConfigView = require 'package-config-view'
### Internal ###
module.exports =
class InstalledPackagesConfigPanel extends ConfigPanel
@content: ->
@div class: 'installed-packages'
initialize: ->
for pack in _.sortBy(atom.getLoadedPackages... |
Add rough outline for UI interaction test suite | describe "UI interactions", ->
describe "Tags", ->
say "I click on a tag", ->
it "should show up in the tag list", ->
it "should only show stories with that matching tag", ->
also "I click on an active tag in a story", ->
it "should do nothing", ->
also "I click on an active... | |
Add test for plugins.on|off overrides | rewire = require 'rewire'
helpers = rewire '../src/helpers'
describe 'helpers', ->
describe 'replaceConfigSlashes()', ->
it 'should replace slashes with backslashes in config', ->
helpers.__set__ 'isWindows', true
unix = require './fixtures/unix_config'
win = require './fixtures/win_config'
... | rewire = require 'rewire'
helpers = rewire '../src/helpers'
describe 'helpers', ->
describe 'replaceConfigSlashes()', ->
it 'should replace slashes with backslashes in config', ->
helpers.__set__ 'isWindows', true
unix = require './fixtures/unix_config'
win = require './fixtures/win_config'
... |
Add initial test for list view | Helper = require './spec-helper'
ProjectsListView = require '../lib/projects-list-view'
Project = require '../lib/project'
{$} = require 'atom-space-pen-views'
describe "List View", ->
[listView, workspaceElement, list, filterEditorView] = []
projects = ->
array = []
for key, setting of Helper.projects
... | |
Support more browsers with indexOf | require('backbone').$ = $
$ ->
if location.pathname is '/2016-year-in-art'
require('../apps/editorial_features/components/eoy/client.coffee').init
else if location.pathname.includes('/venice-biennale')
require('../apps/editorial_features/components/venice_2017/client.coffee').init() | require('backbone').$ = $
$ ->
if location.pathname is '/2016-year-in-art'
require('../apps/editorial_features/components/eoy/client.coffee').init
else if location.pathname.indexOf('/venice-biennale') > -1
require('../apps/editorial_features/components/venice_2017/client.coffee').init() |
Add tests for the registerTemplates function | chai = require 'chai'
chai.should()
cp = require 'child_process'
pack = require '../package.json'
csv_template_specified = 'node bin/autometa.js -r templates/test.csv'
ejs_template_specified = 'node bin/autometa.js -r templates/test.ejs'
csv_and_ejs_template_specified =
'node bin/autometa.js -r templates/test.csv te... | |
Make pause delete and unpause work | Model = require './model'
class Request extends Model
url: => "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/requests/request/#{ @get('id') }"
deletePaused: =>
$.ajax
url: "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/requests/request/#{ @get('requestId') }/paused"
type... | Model = require './model'
class Request extends Model
url: => "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/requests/request/#{ @get('id') }"
deletePaused: =>
$.ajax
url: "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/requests/request/#{ @get('id') }/paused"
type: 'DELE... |
Create component to convert canvas to buffers async | noflo = require 'noflo'
# @runtime noflo-nodejs
# @name CanvasToBuffer
exports.getComponent = ->
c = new noflo.Component
c.description = 'Convert a canvas to a buffer'
c.icon = 'picture-o'
c.inPorts.add 'canvas',
datatype: 'object'
description: 'Canvas to be converted'
c.outPorts.add 'buffer',
... | |
Introduce new specs for latexmk util | latexmk = require "../lib/latexmk"
describe "latexmk", ->
describe "run", ->
xit "...", ->
return
describe "constructArgs", ->
xit "...", ->
return
describe "constructPath", ->
beforeEach ->
spyOn(atom.config, "get").andReturn("$PATH:/usr/texbin")
it "reads `latex.texPath` as... | |
Add two tests regarding crashes in context switching. | assert = require 'assert'
fs = require 'fs'
describe 'contexts', ->
describe 'setTimeout in fs callback', ->
it 'does not crash', (done) ->
fs.readFile __filename, ->
setTimeout done, 0
describe 'throw error in node context', ->
it 'get caught', (done) ->
error = new Error('boo!')
... | |
Add a node.js coffeescript version | #!/usr/bin/env coffee
http = require 'http'
server = http.createServer (req, resp) ->
req.setEncoding('utf-8')
console.log "#{req.method} #{req.url} HTTP/#{req.httpVersion}"
for k, v of req.headers
console.log "#{k.replace(/^\w|-\w/g, (s) -> s.toUpperCase())}: #{v}"
console.log ''
req.on('data', con... | |
Add test for unlocalize currency filter | describe 'convert string to number with configurated currency', ->
filter = null
beforeEach ->
module 'ofn.admin'
inject ($filter) ->
filter = $filter('unlocalizeCurrency')
describe "with point as decimal separator for I18n service", ->
beforeEach ->
spyOn(I18n, "toCurrency").and.retur... | |
Add Comment-Section Module (Use Disqus) | commentSection = angular.module("EventricDocs.Directive.CommentSection", [])
.directive "commentSection", ($window, $location) ->
restrict: "E"
scope:
disqus_shortname: "@disqusShortname"
disqus_identifier: "@disqusIdentifier"
disqus_title: "@disqusTitle"
disqus_url: "@disqusUrl"
template: "<div... | |
Use JS to set active class on product nav | jQuery ($) ->
$(document).ready ->
unless $('dl.tabs dd').hasClass('active')
setActive()
$('dl.tabs dd').on('click', setActive)
setActive = (item) ->
console.log(item)
$('dl.tabs dd').removeClass('active')
$('div.tabs-content div').removeClass('active')
if ! item
$('dl.tabs dd').first().addC... | |
Add unit tests for Trix.MutationObserver | {assert, defer, test, testGroup} = Trix.TestHelpers
observer = null
element = null
summaries = []
install = (html) ->
element = document.createElement("div")
element.innerHTML = html if html
observer = new Trix.MutationObserver element
observer.delegate =
elementDidMutate: (summary) ->
summaries.pus... | |
Add local sub-collections to ConceptCollection | define ['../core', './field'], (c, field) ->
class ConceptModel extends c.Backbone.Model
parse: (resp) ->
@fields = []
# Parse and attach field model instances to concept
for attrs in resp.fields
@fields.push(new field.FieldModel attrs, parse: true)
... | define ['../core', './field'], (c, field) ->
class ConceptModel extends c.Backbone.Model
parse: (resp) ->
@fields = []
# Parse and attach field model instances to concept
for attrs in resp.fields
@fields.push(new field.FieldModel attrs, parse: true)
... |
Make the display of the results a bit nicer | $ ->
updateDisplay = ->
if localStorage.lastSyncTime?
$('.sync-stats').html "You last synced on #{localStorage.lastSyncTime}"
$('.collection-num').html localStorage.num
$('.collection-total').html localStorage.total
if JSON.parse(localStorage.releases).length > 0
$('.search').html localSto... | $ ->
updateDisplay = ->
if localStorage.lastSyncTime?
$('.sync-stats').html "You last synced on #{localStorage.lastSyncTime}"
$('.collection-num').html localStorage.num
$('.collection-total').html localStorage.total
$('.search').html ''
releases = JSON.parse(localStorage.releases)
if rel... |
Add custom script for Arnie quotes | # Description:
# Listens for words and sometimes replies with an Arnie quote
#
# Dependencies:
# None
#
# Commands:
# None
#
# Author:
# Casey Lawrence <cjlaw@users.noreply.github.com>
#
odds = [1...100]
arnie_quotes = [
'GET TO THE CHOPPA! :arnold:',
'Your clothes, give them to me, now! :arnold:',
... | |
Remove throttle breaking object orientedness | SocketIOThrottle = require './SocketIOThrottle'
class Limiter
constructor: (@socket) ->
throttle: (@callback=->) =>
@throttled
throttled: =>
originalArguments = arguments
new SocketIOThrottle().throttle @socket, =>
@callback.apply this, originalArguments
module.exports = Limiter
| SocketIOThrottle = require './SocketIOThrottle'
class Limiter
constructor: (@socket) ->
throttle: (callback=->) =>
->
originalArguments = arguments
new SocketIOThrottle().throttle @socket, =>
callback.apply this, originalArguments
module.exports = Limiter
|
Add CoffeeScript for uploads and progress display. | uploadFile = (fileField) ->
form = fileField.parent()
fileInput = document.getElementById("file")
file = fileInput.files[0]
$.ajax
type: "GET"
url: "/signatures/new"
success: (response) ->
formData = new FormData()
xhr = new XMLHttpRequest()
endpoint = response.endpoint
for... | |
Write dummy states for articles and people | angular.module("hyperadmin")
.config ($locationProvider, $stateProvider, $urlRouterProvider) ->
$locationProvider.html5Mode true
$stateProvider
.state "list_articles",
url: "/admin/articles"
templateUrl: "/admin/articles.html"
.state "new_article",
url: "/admin/articles/ne... | |
Use path.join for test command | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
coffee:
glob_to_multiple:
expand: true
cwd: '.'
src: ['index.coffee']
dest: 'tasks'
ext: '.js'
coffeelint:
options:
no_empty_param_list:
level: 'err... | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
coffee:
glob_to_multiple:
expand: true
cwd: '.'
src: ['index.coffee']
dest: 'tasks'
ext: '.js'
coffeelint:
options:
no_empty_param_list:
level: 'err... |
Bring the lulz from bukk.it | # 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()
... | |
Use object for tempting within haml-coffee | root = exports ? this
root.team =
paul:
name: "Paul Bigger"
role: "Founder"
github: "pbiggar"
email: "paul@circleci.com"
bio: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam at eros non dui sollicitudin mattis. Pellentesque habitant morbi tristique senectus et netus et malesuada f... | |
Update traceur and other stuff | nconf = require("nconf")
host = nconf.get("host")
hostEsc = host.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
plunkRe = new RegExp("^([0-9a-zA-Z]+)\.plunk\.#{hostEsc}$")
previewRe = new RegExp("^([0-9a-zA-Z]+)\.#{hostEsc}$")
recapitalize = (id) ->
id.replace /([a-z]/, ""
module.exports.middleware = (config... | |
Refactor changeSection to avoid extra arguments | if window.location.pathname.match(/\/apply$/)
$ ->
changeSection = (e, noscroll)->
hash = window.location.hash
sectionId = hash.substring 1
$('.section').each ()->
section = $ @
if section.attr('id') is sectionId
section.toggleClass 'hide', false
else
... | if window.location.pathname.match(/\/apply$/)
$ ->
changeSection = ->
hash = window.location.hash
sectionId = hash.substring 1
$('.section').each ()->
section = $ @
if section.attr('id') is sectionId
section.toggleClass 'hide', false
else
section.togg... |
Add new user celebration script | # Description:
# Create a party when a new user appear
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# new user - Create a party when a new user appear
#
# Author:
# PiXeL16
emojis = [
":tada::tada::smile::tada::tada:",
":confetti_ball::tada::smile::tada::confetti_ball:",
":tada::tada:... | |
Index viewing test via casper.js | casper = require('casper').create()
d = ->
console.log arguments...
casper.start 'http://func', ->
this.test.assertHttpStatus 200
casper.run()
| |
Add initial spec to very grammar parses | describe "perl grammar", ->
grammar = null
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage("language-perl")
runs ->
grammar = atom.grammars.grammarForScopeName("source.perl")
it "parses the grammar", ->
expect(grammar).toBeDefined()
expect(grammar.scopeName).toBe "sou... | |
Create comment box on the right location if there are already comments for this line. | # 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://coffeescript.org/
window.merge_requests = ->
# Click to add a comment
$("td > div.add-comment").on 'click', (event) ->
... | # 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://coffeescript.org/
window.merge_requests = ->
# Click to add a comment
$("td > div.add-comment").on 'click', (event) ->
... |
Write file using grunt API | fs = require 'fs'
path = require 'path'
_ = require 'underscore-plus'
module.exports = (grunt) ->
{spawn} = require('./task-helpers')(grunt)
fillTemplate = (filePath, data) ->
template = _.template(String(fs.readFileSync("#{filePath}.in")))
filled = template(data)
outputPath = path.join(grunt.config.... | fs = require 'fs'
path = require 'path'
_ = require 'underscore-plus'
module.exports = (grunt) ->
{spawn} = require('./task-helpers')(grunt)
fillTemplate = (filePath, data) ->
template = _.template(String(fs.readFileSync("#{filePath}.in")))
filled = template(data)
outputPath = path.join(grunt.config.... |
Add the execution manager singleton class | {Emitter} = require('atom')
# ------------------------------------------------------------------------------
class ExecutionManager
## Construction --------------------------------------------------------------
constructor: ->
@emitter = new Emitter
## Event subscription ---------------------------------... | |
Stop passing link separately to DemandVisualizer constructor | # The view class for each link child item in the tree view. Each child item
# is <li> tag with an anchor surrounding the name.
class window.sirius.TreeChildItemDemandLinkView extends window.sirius.TreeChildItemLinkView
$a = window.sirius
showContext: (e) =>
if !@added_menu_item
@targets[0].get('contextMen... | # The view class for each link child item in the tree view. Each child item
# is <li> tag with an anchor surrounding the name.
class window.sirius.TreeChildItemDemandLinkView extends window.sirius.TreeChildItemLinkView
$a = window.sirius
showContext: (e) =>
if !@added_menu_item
@targets[0].get('contextMen... |
Add ember and angular skeletons to suggestions. | 'use strict'
initSkeleton = require 'init-skeleton'
sysPath = require 'path'
watch = require './watch'
logger = require 'loggy'
create = (skeleton, path = '.') ->
unless skeleton
logger.error '''
You must specify skeleton (boilerplate) from which brunch will initialize new app:
brunch new --skeleton <path-... | 'use strict'
initSkeleton = require 'init-skeleton'
sysPath = require 'path'
watch = require './watch'
logger = require 'loggy'
create = (skeleton, path = '.') ->
unless skeleton
logger.error '''
You must specify skeleton (boilerplate) from which brunch will initialize new app.
You can specify directory on... |
Allow theme's package.cson to leave off stylesheet extension | fs = require 'fs-utils'
Theme = require 'theme'
CSON = require 'cson'
module.exports =
class AtomTheme extends Theme
loadStylesheet: (stylesheetPath)->
@stylesheets[stylesheetPath] = window.loadStylesheet(stylesheetPath)
load: ->
if fs.extension(@path) in ['.css', '.less']
@loadStylesheet(@path)
... | fs = require 'fs-utils'
Theme = require 'theme'
CSON = require 'cson'
module.exports =
class AtomTheme extends Theme
loadStylesheet: (stylesheetPath)->
@stylesheets[stylesheetPath] = window.loadStylesheet(stylesheetPath)
load: ->
if fs.extension(@path) in ['.css', '.less']
@loadStylesheet(@path)
... |
Use Consolas font in Atom | 'exception-reporting':
'userId': '3ba70428-f782-5321-e73a-7b678f36511c'
'release-notes':
'viewedVersion': '0.94.0'
'welcome':
'showOnStartup': false
'metrics':
'userId': '9e20623847c7c22109bc7b34e71c459485f8781a'
'editor':
'showInvisibles': true
'fontFamily': 'Monaco'
'showIndentGuide': true
'softTabs':... | 'exception-reporting':
'userId': '3ba70428-f782-5321-e73a-7b678f36511c'
'release-notes':
'viewedVersion': '0.94.0'
'welcome':
'showOnStartup': false
'metrics':
'userId': '9e20623847c7c22109bc7b34e71c459485f8781a'
'editor':
'showInvisibles': true
'fontFamily': 'Consolas'
'showIndentGuide': true
'softTabs... |
Add first spec about event order | describe 'Custom Element Base', ->
registerCustomElement = require('../base.min.js')
{getCustomElement} = require('./helper')
it 'fires the events in order', ->
lastRan = null
element = new (registerCustomElement(getCustomElement({
name: 'x-custom-element'
created: -> lastRan = 'created'
... | |
Add Github Issue Link Generator | # Github issue link looks for #nnn and links to that issue for your default repo. Eg. "Hey guys check out #273"
# Requires vars HUBOT_GITHUB_REPO, and HUBOT_GITHUB_TOKEN to be set.
#
# Listens for #nnn and links to the issue for your default repo on github
module.exports = (robot) ->
robot.hear /.*(#(\d+)).*/, (msg)... | |
Implement custom serverside filter according to the API filters structure | Backbone = require 'backbone'
Backgrid = require 'backgrid'
Filter = require 'backgrid-filter'
CustomServerSideFilter = Backgrid.Extension.ServerSideFilter.extend
showClearButtonMaybe: () ->
$clearButton = @clearButton()
hasFilter = @collection.hasQueryFilter @name
searchTerms = this.searchBox().... | |
Delete is on selection now, not editor | _ = require 'underscore'
class NumericPrefix
count: null
complete: null
operatorToRepeat: null
constructor: (@count) ->
@complete = false
isComplete: -> @complete
compose: (@operatorToRepeat) ->
@complete = true
if @operatorToRepeat.setCount?
@operatorToRepeat.setCount @count
@co... | _ = require 'underscore'
class NumericPrefix
count: null
complete: null
operatorToRepeat: null
constructor: (@count) ->
@complete = false
isComplete: -> @complete
compose: (@operatorToRepeat) ->
@complete = true
if @operatorToRepeat.setCount?
@operatorToRepeat.setCount @count
@co... |
Add message for chrome users about scrolling select boxes | ###
Chrome version 32 changed how scroll bars work.
This is causing problems with some select fields
with many options. There's no way
to click on the scroll bar. Suggest
an alternative of using keys or the scroll wheel
until it is fixed.
###
#
$ ->
is_chrome = /chrome/.test navigator.userAgent.toLowerCase()
... | |
Fix spec now that `Theme.load` returns a theme instead of an array | $ = require 'jquery'
fs = require 'fs'
Theme = require 'theme'
describe "@load(name)", ->
themes = null
beforeEach ->
$("#jasmine-content").append $("<div class='editor'></div>")
afterEach ->
theme.deactivate() for theme in themes
describe "TextMateTheme", ->
it "applies the theme's stylesheet t... | $ = require 'jquery'
fs = require 'fs'
Theme = require 'theme'
describe "@load(name)", ->
theme = null
beforeEach ->
$("#jasmine-content").append $("<div class='editor'></div>")
afterEach ->
theme.deactivate()
describe "TextMateTheme", ->
it "applies the theme's stylesheet to the current window"... |
Add render process check for ATOM_HOME | # Like sands through the hourglass, so are the days of our lives.
require './window'
Atom = require './atom'
window.atom = Atom.loadOrCreate('editor')
atom.initialize()
atom.startEditorWindow()
# Workaround for focus getting cleared upon window creation
windowFocused = ->
window.removeEventListener('focus', windowF... | # Ensure ATOM_HOME is always set before anything else is required
unless process.env.ATOM_HOME
if process.platform is 'win32'
home = process.env.USERPROFILE
else
home = process.env.HOME
atomHome = path.join(home, '.atom')
try
atomHome = require('fs').realpathSync(atomHome)
process.env.ATOM_HOME = ... |
Create user controller using searchable mixins | Dashboard.UsersTabController = Ember.ArrayController.extend Dashboard.SearchableBaseController,
baseRouteName: 'users'
defaultSearchFields:
query: null
Dashboard.UsersSearchController = Dashboard.UsersTabController.extend Dashboard.SearchableController,
baseRouteName: 'users'
| |
Sort by name when type count is the same | path = require 'path'
module.exports = (grunt) ->
grunt.registerTask 'output-build-filetypes', 'Log counts for each filetype in the built application', ->
shellAppDir = grunt.config.get('atom.shellAppDir')
types = {}
grunt.file.recurse shellAppDir, (absolutePath, rootPath, relativePath, fileName) ->
... | path = require 'path'
module.exports = (grunt) ->
grunt.registerTask 'output-build-filetypes', 'Log counts for each filetype in the built application', ->
shellAppDir = grunt.config.get('atom.shellAppDir')
types = {}
grunt.file.recurse shellAppDir, (absolutePath, rootPath, relativePath, fileName) ->
... |
Add --extension option to log out all found paths | asar = require 'asar'
path = require 'path'
module.exports = (grunt) ->
grunt.registerTask 'output-build-filetypes', 'Log counts for each filetype in the built application', ->
shellAppDir = grunt.config.get('atom.shellAppDir')
types = {}
registerFile = (filePath) ->
extension = path.extname(fileP... | asar = require 'asar'
path = require 'path'
module.exports = (grunt) ->
grunt.registerTask 'output-build-filetypes', 'Log counts for each filetype in the built application', ->
shellAppDir = grunt.config.get('atom.shellAppDir')
types = {}
registerFile = (filePath) ->
extension = path.extname(fileP... |
Add function to figure out amount. | @getPayableAmount = (expense = {}, income = {}) ->
if expense.amountRemaining and income.amountRemaining
# Logic is simple here: we want the smallest number. This should work
# even if they are the same. e.g. if 500 in income and 1000 in expense,
# it will choose 500. The other way around and it will stil... | |
Test public API. h/t @mikestone | module "public API"
test "strftime", ->
datetime = "2013-11-12T12:13:00Z"
time = new Date Date.parse datetime
format = "%B %e, %Y %l:%M%P"
results = LocalTime.strftime time, format
ok results
datetimeParsed = moment datetime
localParsed = moment results, "MMMM D, YYYY h:mma"
ok datetimeParsed.isVali... | |
Rename season variable to CSON for consistency | fs = require 'fs-plus'
path = require 'path'
Keymap = require 'atom-keymap'
season = require 'season'
Keymap::loadBundledKeymaps = ->
@loadKeyBindings(path.join(@resourcePath, 'keymaps'))
@emit('bundled-keymaps-loaded')
Keymap::getUserKeymapPath = ->
if userKeymapPath = season.resolve(path.join(@configDirPath, ... | fs = require 'fs-plus'
path = require 'path'
Keymap = require 'atom-keymap'
CSON = require 'season'
Keymap::loadBundledKeymaps = ->
@loadKeyBindings(path.join(@resourcePath, 'keymaps'))
@emit('bundled-keymaps-loaded')
Keymap::getUserKeymapPath = ->
if userKeymapPath = CSON.resolve(path.join(@configDirPath, 'key... |
Add a vote click handler stub | $ ->
$('.vote').on 'click', (event) ->
do event.preventDefault
return unless (comicID = $(this).data 'id')
$counter = $('.number-of-votes')
count = parseInt $counter.text()
count = 0 if isNaN(count)
console.log "Vote on: #{comicID} with #{count} votes so far"
# TODO: Make a call, then on... | |
Add start of a unit test for ActivityTableRow component | require '../../testHelper'
ActivityTableRow = require '../../../app/assets/javascripts/components/activity/activity_table_row'
describe 'ActivtyTableRow', ->
TestRow = ReactTestUtils.renderIntoDocument(
<table>
<ActivityTableRow
rowId=675818536
title='Selfie'
articleUrl='https://en.wikipedi... | |
Remove caching on auction lots until we can get headers working correctly | _ = require 'underscore'
Artist = require '../../models/artist'
AuctionLots = require '../../collections/auction_lots'
@artist = (req, res) ->
artist = null
auctionLots = null
currentPage = parseInt req.query.page || 1
sort = req.query.sort
render = _.after 2, ->
res.render... | _ = require 'underscore'
Artist = require '../../models/artist'
AuctionLots = require '../../collections/auction_lots'
@artist = (req, res) ->
artist = null
auctionLots = null
currentPage = parseInt req.query.page || 1
sort = req.query.sort
render = _.after 2, ->
res.render... |
Define route handler of stacks app | kd = require 'kd'
lazyrouter = require 'app/lazyrouter'
handleSection = (path, callback)->
{ appManager, router, groupsController } = kd.singletons
unless appManager.getFrontApp()
appManager.once 'AppIsBeingShown', ->
router.handleRoute path
router.handleRoute '/IDE'
else
gro... | |
Call upnp module with MediaServer configuration | upnp = require 'upnp'
config =
app:
name: 'Bragi'
version: '0.0.1'
url: 'http://'
device:
type: 'MediaServer'
version: '1.0'
upnp.start config, ->
console.log 'Bragi running! :-)'
| |
Add duration > 0 check | dbm = require("db-migrate")
async = require 'async'
_ = require 'underscore'
type = dbm.dataType
table = "time_entries"
constraint = "positive_duration"
exports.up = (db, callback) ->
r = [
"""
add CONSTRAINT #{constraint} CHECK ( "duration" > 0 )
"""
]
r = _.map r, (s) -> "alter table #{table} #... | |
Hide resource selection for roles other than team leader | do($ = jQuery) ->
$ ->
resource_select = $('#user_role_resource')
if resource_select.length
do ->
role_select = $('#user_role_role')
role_changed = () ->
resource_select.closest('div.row')[if role_select.val() == 'team_leader' then 'show' else 'hide']()
role_changed()
... | |
Clean up. First simple step (download files from AWS). | fs = require 'fs'
Q = require 'q'
knox = require 'knox'
_ = require('underscore')._
class Client
constructor: (key, secret, bucket) ->
@client = knox.createClient
key: key
secret: secret
bucket: bucket
list: (args) ->
Q.ninvoke @client, 'list', args
getFile: (file) ->
Q.ninvoke @c... | |
Consolidate all test data into one object | import enUSAmount from './en-us.amount.coffee'
import enUSCheque from './en-us.cheque.coffee'
import enUSNumber from './en-us.number.coffee'
import zhTWAmount from './zh-tw.amount.coffee'
import zhTWCheque from './zh-tw.cheque.coffee'
import zhTWNumber from './zh-tw.number.coffee'
import zhCNAmount from './zh-cn.amount... | |
Add support for loading titles, and removing ellipsis if needed. eg: title="Title and..." selftext="...rest of joke" gets changed into "Title and rest of joke" | # 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... | # 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... |
Add custom html view tests | should = require 'should'
KDCustomHTMLView = require '../../lib/core/customhtmlview'
describe 'KDCustomHTMLView', ->
it 'exists', ->
KDCustomHTMLView.should.exist
describe 'constructor', ->
it 'should instantiate without error', ->
router = new KDCustomHTMLView
router.should.exist
| |
Add test skeleton for ObjectExpression fix | 'use strict'
expect = require('chai').expect
escope = require '..'
describe 'object expression', ->
it 'doesn\'t require property type', ->
# Hardcoded AST
ast =
type: 'Program'
body: [{
type: 'VariableDeclaration'
declarations: [{
type: 'VariableDeclarator'
i... | |
Add flat theme coffee file (same as future) | $ = jQuery
spinner_template = '''
<div class="messenger-spinner">
<span class="messenger-spinner-side messenger-spinner-side-left">
<span class="messenger-spinner-fill"></span>
</span>
<span class="messenger-spinner-side messenger-spinner-side-right">
<span class="me... | |
Fix the over creation of AudioContexts when record audio message. | @AudioRecorder = new class
start: (cb) ->
window.AudioContext = window.AudioContext or window.webkitAudioContext
navigator.getUserMedia = navigator.getUserMedia or navigator.webkitGetUserMedia
window.URL = window.URL or window.webkitURL
@audio_context = new AudioContext
ok = (stream) =>
@startUserMedia(... | @AudioRecorder = new class
start: (cb) ->
window.AudioContext = window.AudioContext or window.webkitAudioContext
navigator.getUserMedia = navigator.getUserMedia or navigator.webkitGetUserMedia
window.URL = window.URL or window.webkitURL
window.audioContext = new AudioContext
ok = (stream) =>
@startUserM... |
Add spec for Command::spawn calling back only once | Command = require '../lib/command'
describe "Command", ->
describe "::spawn", ->
it "only calls the callback once if the spawned program fails", ->
exited = false
callbackCount = 0
command = new Command
child = command.spawn "thisisafakecommand", [], ->
callbackCount++
chil... | |
Fix navigation to use spine routes | Spine = require 'spine'
MyGalaxies = require 'controllers/interactive/my_galaxies'
Graph = require 'controllers/interactive/graph'
Home = require 'controllers/interactive/interactive'
class Navigator extends Spine.Stack
el: '#navigator'
controllers:
myGalaxies: MyGalaxies
graph: Graph
home: Home
de... | |
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... |
Tweak the modal styling for register modals | Darkswarm.directive "ofnRegistrationLimitModal", (Navigation, $modal, Loading) ->
restrict: 'A'
link: (scope, elem, attr)->
scope.modalInstance = $modal.open
templateUrl: 'registration/limit_reached.html'
windowClass: "login-modal large"
backdrop: 'static'
scope.modalInstance.result.then ... | Darkswarm.directive "ofnRegistrationLimitModal", (Navigation, $modal, Loading) ->
restrict: 'A'
link: (scope, elem, attr)->
scope.modalInstance = $modal.open
templateUrl: 'registration/limit_reached.html'
windowClass: "login-modal register-modal xlarge"
backdrop: 'static'
scope.modalInsta... |
Fix keybindings to work with Nordic OS-X keyboards | # 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://a... | # 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://a... |
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: '... |
Create classes for media-related stuff | class SublimeVideo.Media.ImagePreloader
constructor: (imageUrl, callback, options = {}) ->
@callback = callback
@imageSrc = imageUrl
@options = options
@problem = false
this.preload()
preload: ->
@image = new Image()
@image['onload'] = this.didComplete
@image['onerror'] = this.d... | |
Add specs for display logic in artist header | jade = require 'jade'
path = require 'path'
fs = require 'fs'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Artist = require '../../../models/artist'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.... | |
Handle null incision date time better | ###*
@namespace scoping into the hquery namespace
###
this.hQuery ||= {}
# =require core.coffee
###*
This represents all interventional, surgical, diagnostic, or therapeutic procedures or
treatments pertinent to the patient.
@class
@augments hQuery.CodedEntry
@exports Procedure as hQuery.Procedure
###
class hQuery.... | ###*
@namespace scoping into the hquery namespace
###
this.hQuery ||= {}
# =require core.coffee
###*
This represents all interventional, surgical, diagnostic, or therapeutic procedures or
treatments pertinent to the patient.
@class
@augments hQuery.CodedEntry
@exports Procedure as hQuery.Procedure
###
class hQuery.... |
Add new data update tool | "use strict"
rand = (min, max) -> Math.floor(Math.random() * (max - min + 1)) + min
MongoClient = require('mongodb').MongoClient
MongoClient.connect "mongodb://localhost:27017/test", (err, db) ->
throw err if err
console.log 'Database is connected...'
users = [
{
id: 1234
navn: 'Ola Nordmann'
... | |
Add an acceptance test for registration and login | expect = require("chai").expect
async = require("async")
User = require "./helpers/User"
request = require "./helpers/request"
settings = require "settings-sharelatex"
redis = require "./helpers/redis"
# Expectations
expectProjectAccess = (user, projectId, callback=(err,result)->) ->
# should have access to project... | |
Remove snake-case variable names in tests. | path = require 'path'
{Directory} = require 'pathwatcher'
GitRepository = require '../src/git-repository'
GitRepositoryProvider = require '../src/git-repository-provider'
describe "GitRepositoryProvider", ->
describe ".repositoryForDirectory(directory)", ->
describe "when specified a Directory with a Git reposi... | path = require 'path'
{Directory} = require 'pathwatcher'
GitRepository = require '../src/git-repository'
GitRepositoryProvider = require '../src/git-repository-provider'
describe "GitRepositoryProvider", ->
describe ".repositoryForDirectory(directory)", ->
describe "when specified a Directory with a Git reposi... |
Add script to expire existing DocOps lists | Settings = require "settings-sharelatex"
rclient = require("redis-sharelatex").createClient(Settings.redis.documentupdater)
keys = Settings.redis.documentupdater.key_schema
async = require "async"
RedisManager = require "./app/js/RedisManager"
getKeysFromNode = (node, pattern, callback) ->
cursor = 0 # redis iterato... | |
Add StateService for cleaner state handling using promises | angular.module('kassa').factory('StateService', [
->
STATE_ERROR = 0
STATE_SUCCESS = 1
STATE_CHANGING = 2
STATE_DEFAULT = 3
class StateHandler
__isInState: (matchState)=> @currentState == matchState
__setToState: (state)=> @currentState = state
isError: -> @__isInState(STATE_ERR... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.