Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Use new runas API for grunt install on Windows. | path = require 'path'
module.exports = (grunt) ->
{cp, mkdir, rm, spawn} = require('./task-helpers')(grunt)
grunt.registerTask 'install', 'Install the built application', ->
installDir = grunt.config.get('atom.installDir')
shellAppDir = grunt.config.get('atom.shellAppDir')
if process.platform is 'win3... | path = require 'path'
runas = null
module.exports = (grunt) ->
{cp, mkdir, rm} = require('./task-helpers')(grunt)
grunt.registerTask 'install', 'Install the built application', ->
installDir = grunt.config.get('atom.installDir')
shellAppDir = grunt.config.get('atom.shellAppDir')
if process.platform is... |
Use self instead of hacky eval | eval("window = {};")
eval("attachEvent = function(){};")
eval("console = {};")
console.warn = ->
self.postMessage
type: 'warn'
details: arguments
console.log = ->
self.postMessage
type: 'log'
details: arguments
self.addEventListener 'message', (event) ->
switch event.data.type
when 'start'
... | self.window = {}
self.attachEvent = ->
self.console =
warn: ->
self.postMessage
type: 'warn'
details: arguments
log: ->
self.postMessage
type: 'log'
details: arguments
self.addEventListener 'message', (event) ->
switch event.data.type
when 'start'
window.resourcePath = e... |
Add possibility to remember/forget Harvest credentials. | # Description:
# Allows Hubot to interact with Harvest's (http://harvestapp.com) time-tracking
# service.
#
# Dependencies:
# None
# Configuration:
# HUBOT_HARVEST_SUBDOMAIN
# The subdomain you access the Harvest service with, e.g.
# if you have the Harvest URL http://yourcompany.harvestapp.com
# yo... | |
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 KSS javascript to handle CSS pseudo classes | # Scans stylesheets for pseudo classes, then inserts a new CSS rule with the
# same properties, but named 'psuedo-class-{{name}}'.
#
# Supported pseudo classes: hover, disabled, active, visited, focus, checked.
#
# Example:
#
# a:hover { color: blue; }
# => a.pseudo-class-hover { color: blue; }
pseudos = /(\:hover... | |
Add task to log loop returns | path = require 'path'
module.exports = (grunt) ->
grunt.registerTask 'output-for-loop-returns', 'Log methods that end with a for loop', ->
appDir = grunt.config.get('atom.appDir')
jsPaths = []
grunt.file.recurse path.join(appDir, 'src'), (absolutePath, rootPath, relativePath, fileName) ->
jsPaths.... | |
Define new TabHandleView for ui changes. | kd = require 'kd'
KDTabHandleView = kd.TabHandleView
module.exports = class BranchTabHandleView extends KDTabHandleView
constructor: (options = {}, data) ->
options.closable or= no
options.closeHandle ?= null
super options, data
partial: ->
{ pane, title } = @getOptions()
... | |
Simplify WebSocket reconnects and guard against opening multiple connections | # Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.
class Cable.Connection
constructor: (@consumer) ->
@open()
send: (data) ->
if @isOpen()
@webSocket.send(JSON.stringify(data))
true
else
false
open: ->
r... | # Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.
class Cable.Connection
constructor: (@consumer) ->
@open()
send: (data) ->
if @isOpen()
@webSocket.send(JSON.stringify(data))
true
else
false
open: ->
i... |
Add sample proportion class and basic methods | class App.SampleProportion
SD_TO_GRAPH = 5
constructor: (@participants, @conversions) ->
@p = @conversions / @participants
@sd = this.getStdDev()
getStdDev: ->
Math.sqrt @p * (1 - @p) / @participants
getXAxisRange: ->
new App.Range @p - SD_TO_GRAPH * @sd, @p + SD_TO_GRAPH * @sd | |
Use JANKY_SIGNTOOL env var to sign | path = require 'path'
module.exports = (grunt) ->
{spawn} = require('./task-helpers')(grunt)
grunt.registerTask 'codesign', 'Codesign the app', ->
done = @async()
if process.platform is 'darwin' and process.env.XCODE_KEYCHAIN
unlockKeychain (error) ->
if error?
done(error)
... | path = require 'path'
module.exports = (grunt) ->
{spawn} = require('./task-helpers')(grunt)
grunt.registerTask 'codesign', 'Codesign the app', ->
done = @async()
if process.platform is 'darwin' and process.env.XCODE_KEYCHAIN
unlockKeychain (error) ->
if error?
done(error)
... |
Add tests for the AppRouter | describe "AppRouter specs", ->
describe "Initialise", ->
it "should set the correct properties", ->
pm = jasmine.createSpyObj("PageManager", ["on"])
pp = jasmine.createSpyObj("ParameterParser", ["on"])
router = new AppEngine.Routers.AppRouter({
pageManager: pm,
parameterParser: ... | |
Add assert for null value when no next match | {OnigScanner} = require '../lib/oniguruma'
describe "OnigScanner", ->
it "returns the index of the matching pattern", ->
scanner = new OnigScanner(["a", "b", "c"])
expect(scanner.findNextMatch("xxaxxbxxc", 0).index).toBe 0
expect(scanner.findNextMatch("xxaxxbxxc", 4).index).toBe 1
expect(scanner.find... | {OnigScanner} = require '../lib/oniguruma'
describe "OnigScanner", ->
it "returns the index of the matching pattern", ->
scanner = new OnigScanner(["a", "b", "c"])
expect(scanner.findNextMatch("x", 0)).toBe null
expect(scanner.findNextMatch("xxaxxbxxc", 0).index).toBe 0
expect(scanner.findNextMatch("... |
Include release stage in campfire notification | NotificationPlugin = require "../../notification-plugin"
class Campfire extends NotificationPlugin
@receiveEvent: (config, event, callback) ->
# Build the message
message = "#{event.trigger.message} in #{event.project.name}!"
if event.error
message += " #{event.error.exceptionClass}" if event.error... | NotificationPlugin = require "../../notification-plugin"
class Campfire extends NotificationPlugin
@receiveEvent: (config, event, callback) ->
# Build the message
message = "#{event.trigger.message} in #{event.error.releaseStage} from #{event.project.name}!"
if event.error
message += " #{event.erro... |
Add tests to ensure common interface. | describe "ImageViewer", ->
viewer = $('#ImageViewer').imageViewer
beforeEach ->
loadFixtures 'image_viewer_index'
$('#ImageViewer').imageViewer(["/assets/test_image_1.jpeg"])
it "implements zoom", ->
expect(typeof(viewer.rotate) == "function").toBe(true)
it "implements rotate", ->
expect(typ... | |
Add spec coverage for channel.js.coffee | describe 'WebSocketRails.Channel:', ->
beforeEach ->
@dispatcher =
new_message: -> true
dispatch: -> true
trigger_event: (event) -> true
state: 'connected'
connection_id: 12345
@channel = new WebSocketRails.Channel('public',@dispatcher)
sinon.spy @dispatcher, 'trigger_event'
... | |
Add jasmine tests to check measure calculation (in progress) | #= require map_editor
beforeEach ->
@map = new L.Map(document.createElement('div')).setView [0, 0], 15
describe 'L.Draw.Polyline.ReactiveMeasure', ->
beforeEach ->
@geod = GeographicLib.Geodesic.WGS84
@drawnItems = new L.FeatureGroup().addTo(@map)
@edit = new L.EditToolbar.Edit @map,
featureGroup... | |
Add CoffeeScript for the bar chart diagram | #=require d3
$ ->
margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
}
width = 960 - margin.left - margin.right
height = 500 - margin.top - margin.bottom
formatPercent = d3.format(".0%")
x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.1, 1)
y = d3.scale.linear()
... | |
Use logger from lib for eventual testing | app = require "./app/app"
logger = require "./app/libs/logger"
server = app.listen app.get("port"), ->
logger.info "Server listening on port " + server.address().port | |
Create JS unit test for choose_metric | #= require spec_helper
#= require metric_collector
describe "MetricCollector", ->
describe 'choose_metric', ->
before ->
sinon.stub(window, "$")
@metric_code = 'acc'
@metric_code_field = sinon.stub()
@metric_code_field.val = sinon.stub().withArgs(@metric_code)
@metric_collector_na... | |
Add shortcut for removing powerbuild's cache file | fs = require 'fs'
path = require 'path'
_ = require 'lodash'
module.exports = (grunt) ->
grunt.registerTask 'delete-powerbuild-cache', 'Deletes the cache file that powerbuild messes up occasionally.', ->
success = @async()
file = path.join 'node_modules', 'powerbuild', 'powerbuild-cache'
i... | |
Add basic test for File Source | FileSource = $src "sources/file"
MasterStream = $src "master/stream"
Logger = $src "logger"
STREAM1 =
key: "test1"
source_password: "abc123"
root_route: true
seconds: 60*60*4
format: "mp3"
mp3 = $file "mp3/mp3-44100-64-s.mp3"
descr... | |
Work with cocoon gem better | # When we add a cocoon element, it copies a static template into the DOM
# We have to update this template to have a unique ID
$(document).on 'cocoon:before-insert', (event, item) ->
return true if item.find('.asset-box-uploader').length == 0
html = item.html()
item.find('.asset-box-uploader').each (index, elem... | |
Add markdow editor on channel edit | Neighborly.Channels ?= {}
Neighborly.Channels.Profiles ?= {}
Neighborly.Channels.Profiles.Edit =
init: Backbone.View.extend
el: '.edit-channel-page'
initialize: ->
this.$('#profile_how_it_works').markItUp(Neighborly.markdownSettings)
| |
Use @@ in example snippet | # If you want some example snippets, check out:
# - https://raw.githubusercontent.com/atom/language-coffee-script/master/snippets/language-coffee-script.cson
'.source.__package-name__':
'If':
'prefix': 'if'
'body': 'if ${1:condition}\n ${0:# body...}'
| # If you want some example snippets, check out:
# - https://raw.githubusercontent.com/atom/language-coffee-script/master/snippets/language-coffee-script.cson
'.source.__package-name__':
'Method documentation':
'prefix': 'doc'
'body': '@@ ${1:method} - ${2:description}'
|
Implement ButtonViewWithProgressBar for built-in progress button usages | kd = require 'kd'
KDButtonView = kd.ButtonView
KDProgressBarView = kd.ProgressBarView
KDLoaderView = kd.LoaderView
KDCustomHTMLView = kd.CustomHTMLView
module.exports = class ButtonViewWithProgressBar extends KDCustomHTMLView
constructor: (options = {}, data) ->
super options, data
... | |
Add an integration test for images from mobile | faker = require 'faker'
fs = require 'fs-extra'
path = require 'path'
should = require 'should'
Cozy = require '../helpers/integration'
Files = require '../helpers/files'
# Images imported from cozy-mobile are special because they have no checksum
describe 'Image from mobile', ->
@slow 1000
@timeout ... | |
Add menu item to "Add a folder" | 'menu': [
{
'label': 'View'
'submenu': [
'label': 'Toggle Treeview'
'command': 'tree-view:toggle'
]
}
{
'label': 'Packages'
'submenu': [
'label': 'Tree View'
'submenu': [
{ 'label': 'Toggle', 'command': 'tree-view:toggle' }
{ 'label': 'Reveal Active File... | 'menu': [
{
'label': 'View'
'submenu': [
'label': 'Toggle Treeview'
'command': 'tree-view:toggle'
]
}
{
'label': 'Packages'
'submenu': [
'label': 'Tree View'
'submenu': [
{ 'label': 'Toggle', 'command': 'tree-view:toggle' }
{ 'label': 'Reveal Active File... |
Rebuild the cordova index when change the Site Url | if Meteor.isServer
url = Npm.require('url')
RocketChat.settings.get 'Site_Url', (key, value) ->
if value?.trim() isnt ''
__meteor_runtime_config__.ROOT_URL = value
__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL = value
if Meteor.absoluteUrl.defaultOptions?.rootUrl?
Meteor.absoluteUrl.defaultOptions.ro... | if Meteor.isServer
url = Npm.require('url')
RocketChat.settings.get 'Site_Url', (key, value) ->
if value?.trim() isnt ''
__meteor_runtime_config__.ROOT_URL = value
__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL = value
if Meteor.absoluteUrl.defaultOptions?.rootUrl?
Meteor.absoluteUrl.defaultOptions.ro... |
Add initial tests for portal lights | noflo = require 'noflo'
device = "simulator://"
#device = "serial:///dev/ttyACM0"
Runtime = require 'noflo-runtime/src/RemoteSubGraph'
describe 'MicroFlo Portal Lights', ->
runtime = null
before (done) ->
done()
after (done) ->
done()
describe 'Remote subgraph', ->
def =
label: "Ingress T... | |
Remove unnecessary 'if x then true else false's | Utils = require '../../../utils'
FormField = React.createClass
render: ->
<input
className = {classNames 'form-control', @props.prop.customClass}
placeholder = {@props.prop.placeholder}
type = {@props.prop.inputType}
id = {@props.id}
onChange = ... | Utils = require '../../../utils'
FormField = React.createClass
render: ->
<input
className = {classNames 'form-control', @props.prop.customClass}
placeholder = {@props.prop.placeholder}
type = {@props.prop.inputType}
id = {@props.id}
onChange = ... |
Use string interpolation for error message | module.exports =
class GitRepository
constructor: (path) ->
unless repo = $git.getRepository(path)
throw new Error("No Git repository found searching path: " + path)
repo.constructor = GitRepository
repo.__proto__ = GitRepository.prototype
return repo
getHead: $git.getHead
getPath: $git.get... | module.exports =
class GitRepository
constructor: (path) ->
unless repo = $git.getRepository(path)
throw new Error("No Git repository found searching path: #{path}")
repo.constructor = GitRepository
repo.__proto__ = GitRepository.prototype
return repo
getHead: $git.getHead
getPath: $git.get... |
Add script for current playing song in Last.fm | # Last (or current) played song by a user in Last.fm
#
# hubot <what's playing> someone - Returns song name and artist
#
module.exports = (robot) ->
robot.respond /what's playing (.*)/i, (msg) ->
user = escape(msg.match[1])
apiKey = process.env.HUBOT_LASTFM_APIKEY
msg.http('http://ws.audioscrobbler.com/2... | |
Create JS to upload images with dropzone | Neighborly.Images = {} if Neighborly.Images is undefined
Neighborly.Images.New =
init: Backbone.View.extend
el: '.new-image-page'
initialize: ->
dropzone = new this.DragDropUploader { el: '.new-image-upload-dropzone' }
DragDropUploader: Backbone.View.extend
events:
'mouseenter': 'mo... | |
Fix initSelection of variant autocomplete. | # variant autocompletion
$(document).ready ->
if $("#variant_autocomplete_template").length > 0
window.variantTemplate = Handlebars.compile($("#variant_autocomplete_template").text())
window.variantStockTemplate = Handlebars.compile($("#variant_autocomplete_stock_template").text())
window.variantLineItemT... | # variant autocompletion
$(document).ready ->
if $("#variant_autocomplete_template").length > 0
window.variantTemplate = Handlebars.compile($("#variant_autocomplete_template").text())
window.variantStockTemplate = Handlebars.compile($("#variant_autocomplete_stock_template").text())
window.variantLineItemT... |
Test for new squad button. | require = patchRequire global.require
common = require './common'
common.setup()
casper.test.begin "New squad", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Rookie Pilot'
upgrades: [
... | |
Create a task which builds an installer | fs = require 'fs'
path = require 'path'
module.exports = (grunt) ->
{spawn} = require('./task-helpers')(grunt)
grunt.registerTask 'create-installer', 'Create the Windows installer', ->
if process.platform is not 'win32'
return
done = @async()
buildDir = grunt.config.get('atom.buildDir')
at... | |
Implement DOM node children list | 'use strict'
List = require '../nodes/list'
module.exports = class ChildrenList extends List
constructor: (@element) ->
setValue: (elementList) ->
while (el = @element.lastChild)?
@element.removeChild(el)
for el in elementList
@element.appendChild(el)
return this
get: ->
@el... | |
Add stupid simple concept for unannoying install prompt | ###!
wai
Version 0.1.0
(c) 2014 tofumatt, MIT License
###
"use strict"
# What kind of app install process are we dealing with?
mozApps = @navigator.mozApps
# Use localStorage to set install info.
store = @localStorage # or window.localStorage
Wai =
install: (options) =>
return if !mozApps or store._waiAt... | |
Add test script using brain | module.exports = (robot) ->
robot.hear /tired/, (msg) ->
robot.brain.data.count = 0 unless robot.brain.data.count
robot.brain.data.count += 1
robot.brain.save
if robot.brain.data.count < 3 then msg.send "Let's take a short break." else msg.send "You must take a break."
robot.hear /fine/, (msg) ->
... | |
Add effector plugin spec document. | # nwdrome-effector-plugin spec
# Copyright 2014, Ragg(@_ragg_)
###
# Nwdrome effector plugin specification
## Register plugin
Call `nwdrome.plugin.addEffector` with `factory function`
Factory function given plugin config object.
Below Plugin config object properties.
- appUrl :string Application(nwdrome) root pa... | |
Add simple RDFa context to JSON tool | jsdom = require 'jsdom'
RDFaJSON = require "../js/rdfa-json"
path = "http://www.w3.org/2011/rdfa-context/rdfa-1.1.html"
#"http://www.w3.org/2011/rdfa-context/xhtml-rdfa-1.1"
#"http://www.w3.org/2011/rdfa-context/html-rdfa-1.1"
jsdom.env path, [], (errs, window) ->
data = RDFaJSON.extract(window.document).data
ctxt ... | |
Implement simple DSL for scripting | Component = require 'core/Component'
Result = require 'core/Result'
###
###
module.exports = class Scriptable extends Component
constructor: (owner) ->
super
@_tasks = []
@owner.addListener 'update', @_scriptable_update
_scriptable_update: =>
# get current task
task = @_tasks[0]
if task... | Component = require 'core/Component'
Result = require 'core/Result'
###
###
module.exports = class Scriptable extends Component
constructor: (owner) ->
super
@_tasks = []
@owner.addListener 'update', @_scriptable_update
_scriptable_update: =>
# get current task
task = @_tasks[0]
if task... |
Move Queue over from alac.js | class Queue
constructor: (@name) ->
@highwaterMark = 256
@lowwaterMark = 64
@finished = false
@buffering = true
@onHighwaterMark = null
@onLowwaterMark = null
@buffers = []
@inputs = {
contents:
... | |
Add simple spec for routes. | describe "Application routes", ->
beforeEach module("myApp")
beforeEach inject ($httpBackend) ->
for partial in ["views/main.html", "views/other.html"]
$httpBackend.whenGET(partial).respond({})
beforeEach inject ($location, $rootScope) ->
@navigateTo = (path) ->
$location.path(path)
$... | |
Add integration test for question interpreter | describe 'Question to HTML', ->
@timeout 0
interpreter = SwanKiosk.Interpreters.Question
layout = SwanKiosk.Layout
question =
title: 'Gender',
why: 'This helps us better extimate your health risks'
select: {M: 'Male', F: 'Female', other: 'Other'}
beforeEach ->
built = (new interpreter... | |
Add utility lib to help with color conversions | App.Utils =
hexToRgb: (hex) ->
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec hex;
if result
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
else
null
| |
Add a unit test for GitRepositoryProvider. | 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... | |
Implement an alternative for easyXDM | msgPrefix = 'FL$msg*)k`dC:'
window.Factlink || window.Factlink = {}
Factlink.createFrameProxy = (target_window) -> (method_name) -> (args...) ->
console.log window.location.href + " sending " + method_name, args, target_window
message = msgPrefix + JSON.stringify([method_name, args])
target_window.postMessage me... | |
Add Coffeescript version of extract.js | ###
Extract text from a webpage using CSS selectors to include or exclude elements
By @westonruter
###
# Trim whitespace around an element and normalize the whitespace inside
# @param {String} s
# @returns {String}
trim = (s) ->
s.replace(/\s+/g, ' ').replace(/^\s+/, '').replace(/\s+$/, '')
presetSelectors =
... | |
Split page shell into separate file | React = require 'react'
BS = require 'react-bootstrap'
_ = require 'underscore'
LoadableItem = require '../loadable-item'
ReferenceBookPage = require './page'
{Invalid} = require '../index'
{ReferenceBookPageActions, ReferenceBookPageStore} = require '../../flux/reference-book-page'
ReferenceBookPageShell = React.c... | |
Use window.location.protocol to choose between ws:// and wss:// shcheme. | ###
WebSocket Interface for the WebSocketRails client.
###
class WebSocketRails.WebSocketConnection
constructor: (@url,@dispatcher) ->
@url = "ws://#{@url}" unless @url.match(/^wss?:\/\//)
@message_queue = []
@_conn = new WebSocket(@url)
@_conn.onmessage = @on_message
@_co... | ###
WebSocket Interface for the WebSocketRails client.
###
class WebSocketRails.WebSocketConnection
constructor: (@url,@dispatcher) ->
if window.location.protocol == 'http:'
@url = "ws://#{@url}"
else
@url = "wss://#{@url}"
@message_queue = []
@_conn ... |
Add Notification bongo model to social worker | Bongo = require "bongo"
{Relationship} = require "jraphical"
request = require 'request'
KodingError = require '../../error'
{secure, race, signature, Base} = Bongo
{uniq} = require 'underscore'
module.exports = class SocialNotification extends Base
@share()
@trait __dirname, '../../traits/pro... | |
Monitor file events in pathwatcher spec. | assert = require 'assert'
fs = require 'fs'
path = require 'path'
temp = require 'temp'
describe 'third-party module', ->
fixtures = path.join __dirname, 'fixtures'
temp.track()
describe 'runas', ->
it 'can be required in renderer', ->
require 'runas'
it 'can be required in node binary', ... | assert = require 'assert'
fs = require 'fs'
path = require 'path'
temp = require 'temp'
describe 'third-party module', ->
fixtures = path.join __dirname, 'fixtures'
temp.track()
describe 'runas', ->
it 'can be required in renderer', ->
require 'runas'
it 'can be required in node binary', ... |
Define has "Managed VMs" stack utility | kd = require 'kd'
isManagedVMStack = require './isManagedVMStack'
module.exports = ->
{ stacks } = kd.singletons.computeController
count = stacks.filter(isManagedVMStack).length
return count > 0
| |
Add a command to create a command to prettify | window.prettifyJsCommand = ->
urls = $('script').map (_, script) ->
$(script).attr('src')
jsUrls = _.filter (urls), (url) ->
(url.indexOf("slack-edge")!= -1) && (url.lastIndexOf("js") == url.length - 2)
console.log jsUrls
commands = jsUrls.map (url) ->
fields = url.split("/")
basename = fields... | |
Fix SmoothScroll - Update hash in the end of animation | # USE
# Add smooth-scroll attribute to the element with anchors link.
# The target elements must have the id or name with the same value of the anchor's href
class @Components.Utils.SmoothScroll
@autoInit: ->
$('[smooth-scroll]').each (i, nav) => new @($(nav))
constructor: (@nav) ->
@scrollOnClick()
@s... | # USE
# Add smooth-scroll attribute to the element with anchors link.
# The target elements must have the id or name with the same value of the anchor's href
class @Components.Utils.SmoothScroll
@autoInit: ->
$('[smooth-scroll]').each (i, nav) => new @($(nav))
constructor: (@nav) ->
@scrollOnClick()
@s... |
Make markdown preview ctrl-m, since meta-m *minimizes* :poop: | window.keymap.bindKeys '.editor',
'meta-m': 'markdown-preview:toggle'
window.keymap.bindKeys '.markdown-preview',
'meta-m': 'markdown-preview:toggle'
| window.keymap.bindKeys '.editor',
'ctrl-m': 'markdown-preview:toggle'
window.keymap.bindKeys '.markdown-preview',
'ctrl-m': 'markdown-preview:toggle'
|
Add test for validation of document input | treeSitter = require "tree-sitter"
assert = require "assert"
compiler = require ".."
describe "Document", ->
document = null
parser = null
before ->
grammar = compiler.grammar
name: "test"
rules:
stuff: -> "stuff"
parser = compiler.compileAndLoad(grammar)
beforeEach ->
docume... | |
Fix not yet ready bookyt/table_select JS inclusion. | # This is a manifest file that'll be compiled into including all the files listed below.
# Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
# be included in the compiled file accessible from http://example.com/assets/application.js
# It's not advisable to add code directly he... | # This is a manifest file that'll be compiled into including all the files listed below.
# Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
# be included in the compiled file accessible from http://example.com/assets/application.js
# It's not advisable to add code directly he... |
Add tests for creating a directory. | _ = require 'underscore'
path = require 'path'
Promise = require 'bluebird'
CreateDir = require '../lib/createdir'
{ExtendedLogger} = require 'sphere-node-utils'
Config = require '../config'
describe 'CreateDir', ->
beforeEach ->
@testPath = path.join(__dirname,'../exports')
@logger = new ExtendedLogger
... | |
Make modals not hide when clicking on greyed out background | $ ->
$(".topbar-wrapper").dropdown()
$ ->
$(".alert-message").alert()
| $ ->
$(".topbar-wrapper").dropdown()
$ ->
$(".alert-message").alert()
$ ->
$(".modal").modal
show: false
backdrop: "static" |
Add Me Gusta face meme | # Happiness in image form
#
# me gusta - Display "Me Gusta" face when heard
#
module.exports = (robot) ->
robot.hear /me gusta/i, (msg) ->
msg.send "http://s3.amazonaws.com/kym-assets/entries/icons/original/000/002/252/me-gusta.jpg" | |
Handle keyboard navigation with hidden selections better | $ ->
$(document).on 'keydown', (event) ->
active = $(document.activeElement)
if active.is('.group-dropdown-search, .selector-link')
switch event.which
when 40 # select next group with down arrow
target = active.parent().next('.group-item').find('.selector-link')
target = $('#... | $ ->
$(document).on 'keydown', (event) ->
active = $(document.activeElement)
if active.is('.group-dropdown-search, .selector-link')
switch event.which
when 40 # select next group with down arrow
target = active.parent().next('.group-item:visible').find('.selector-link')
targe... |
Add Hubot scripts to serach open Github pull requests | # Show open pull requests from a Github repository.
#
# You need to set the following variables:
# HUBOT_GITHUB_TOKEN ="<oauth token>"
# HUBOT_GITHUB_USER ="<user name>"
#
# HUBOT_GITHUB_USER is optional, but if you set it, you can ask `show me hubot pulls`
# instead of `show me github/hubot pulls`.
#
# You can fur... | |
Create custom authenticator and authorizer for simple-auth | Dashboard.CustomAuthenticator = SimpleAuth.Authenticators.Devise.extend
restore: (properties) ->
new Ember.RSVP.Promise((resolve, reject) ->
if not Ember.isEmpty(properties.access_token)
resolve properties
else
reject()
return
)
authenticate: (credentials) ->
_this = t... | |
Support (or don't fail on) Web Sockets | DNS = require("dns")
HTTP = require("http")
ProxyRequest = require("./proxy")
Replay = require("./replay")
# Route HTTP requests to our little helper.
HTTP.request = (options, callback)->
request = new ProxyRequest(options, Replay.chain.start)
if callback
request.once "response", (r... | DNS = require("dns")
HTTP = require("http")
ProxyRequest = require("./proxy")
Replay = require("./replay")
httpRequest = HTTP.request
# Route HTTP requests to our little helper.
HTTP.request = (options, callback)->
# WebSocket request: pass through to Node.js library
if options && opt... |
Update fixture path 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... |
Use the configured REFLECTION_URL instead of hardcoding | fs = require 'graceful-fs'
request = require 'superagent'
{ resolve } = require 'path'
cache = require '../../../lib/cache'
module.exports = class Reflection
url: ->
"http://artsy-reflection.s3.amazonaws.com/__reflection/forceartsynet#{@path}"
constructor: ({ @path }) -> #
request: ->
request.get(@url(... | fs = require 'graceful-fs'
request = require 'superagent'
{ resolve } = require 'path'
cache = require '../../../lib/cache'
{ REFLECTION_URL } = require '../../../config'
module.exports = class Reflection
url: ->
REFLECTION_URL + @path
constructor: ({ @path }) -> #
request: ->
request.get(@url()).type(... |
Add configuration for editor global menu | 'menu': [
{
'label': 'Packages'
'submenu': [
{
'label': 'Python Isort'
'submenu': [
{
'label': 'Sort Python Imports'
'command': 'python-isort:run'
}
]
}
]
}
]
| |
Add markdown editor to channel admin | Neighborly.Admin.Channels ?= {}
Neighborly.Admin.Channels ?= {}
Neighborly.Admin.Channels.New =
init: Backbone.View.extend
el: '.admin'
initialize: ->
this.$('#channel_how_it_works').markItUp(Neighborly.markdownSettings)
Neighborly.Admin.Channels.Edit =
modules: -> [Neighborly.Admin.Channels.New]
| |
Add tests for palette methods | Color = require '../lib/color'
Palette = require '../lib/palette'
describe 'Palette', ->
[colors, palette] = []
beforeEach ->
colors =
red: new Color '#ff0000'
green: new Color '#00ff00'
blue: new Color '#0000ff'
redCopy: new Color '#ff0000'
palette = new Palette(colors)
descri... | |
Fix Relative path on og:image meta tag results in broken preview image | getTitle = (self) ->
if not self.meta?
return
return self.meta.ogTitle or self.meta.twitterTitle or self.meta.title or self.meta.pageTitle
getDescription = (self) ->
if not self.meta?
return
description = self.meta.ogDescription or self.meta.twitterDescription or self.meta.description
if not description?
... | getTitle = (self) ->
if not self.meta?
return
return self.meta.ogTitle or self.meta.twitterTitle or self.meta.title or self.meta.pageTitle
getDescription = (self) ->
if not self.meta?
return
description = self.meta.ogDescription or self.meta.twitterDescription or self.meta.description
if not description?
... |
Allow using the data-disable-with attribute on any button. | # jquery-ujs can disable buttons if they have an attribute data-disable-with
# this only works if the button is within a form and the form is submitted
# this snippet adds that feature to any button with that data attribute.
$(document).on('click', 'button[data-disable-with]', ->
$(this)
.html($(this).data('disa... | |
Add a version to make debugging easier. | @spendflowPrecision = 2
# TODO: Allow changing accounting.js settings from a UI
accounting.settings.currency.symbol = ""
accounting.settings.currency.precision = 2
accounting.settings.number.precision = 2
| @SPENDFLOW_VERSION = '1.7.9-pre'
@spendflowPrecision = 2
# TODO: Allow changing accounting.js settings from a UI
accounting.settings.currency.symbol = ""
accounting.settings.currency.precision = 2
accounting.settings.number.precision = 2
|
Watch menu item initial commit | class IDE.ChatHeadWatchItemView extends KDCustomHTMLView
constructor: (options = {}, data) ->
options.partial = 'Watch'
super options, data
{ isWatching, nickname } = @getOptions()
@addSubView @toggle = new KodingSwitch
cssClass : 'tiny'
defaultValue : isWatching
callback ... | |
Remove obsolete test instance AMI identifiers | module.exports =
current: 'ami-5dd50436'
# Ordered by creation date
list: [
'ami-a7986fcc'
'ami-b920d7d2'
'ami-9b02f0f0'
'ami-e7a05a8c'
'ami-5dd50436'
]
| module.exports =
current: 'ami-5dd50436'
# Ordered by creation date
list: [
'ami-5dd50436'
]
|
Use new sign in class for sign in area in sidebar | window.ReactSidebarLogin = React.createBackboneClass
displayName: 'ReactSidebarLogin'
mixins: [ UpdateOnSignInOrOutMixin ]
render: ->
if !currentSession.signedIn()
ReactSigninLinks()
else
_span []
| |
Add a simple launcher that helps to play with scriptscript | # # TODO figure out better name & place & API for such script
# # TODO add shebang & make executable
require 'fy'
if !process.argv[2]?
perr "Usage: iced run.coffee [input]"
process.exit 1
## -v 0
# me = require "."
# await me.go process.argv[2], {}, defer err, res
# throw err if err
# p res
## -v 2
p "Input:", pro... | |
Add hide functionality similar to Bootstrap's data-dismiss, but hides the element instead of remove it. | # Works like data-dismiss in Bootstrap, but instead of removing
# the parent element, it just hides it.
$ ->
$("[data-hide]").on "click", (event)->
$parent = $(@).closest("." + $(@).attr("data-hide"))
$parent.removeClass("in")
if $.support.transition && $parent.hasClass('fade')
$parent.on $.support.... | |
Add Grunt configuration for building/watching package | module.exports = (grunt) ->
# Grunt configuration
grunt.initConfig
coffee:
source:
expand: true
cwd: './'
src: ['index.coffee', 'test/test.coffee']
dest: './'
ext: '.js'
watch:
backend:
files: ['index.coffee', 'test/test.coffee']
tasks: ['... | |
Add Bookmarklet that works on Github only | if document.URL.indexOf("https://github.com/") == 0
open("http://knight.dev/repos/" + document.URL.split("/").slice(3).join("/"))
else
alert("Please use this bookmarklet on a URL like https://github.com/rails/rails")
###
javascript:(function() {
if (document.URL.indexOf("https://github.com/") === 0) {
ope... | |
Put my name on the emails. | @spendflowAutomaticNotes = "Managed automatically"
| @spendflowAutomaticNotes = "Managed automatically"
Accounts.emailTemplates.from = "Kevin at Spendflow <kevin@spendflow.co>"
|
Add menu items to move to next/previous diffs | 'menu': [
{
'label': 'Packages'
'submenu': [
'label': 'Git Diff'
'submenu': [
{ 'label': 'Move to Next Diff', 'command': 'git-diff:move-to-next-diff' }
{ 'label': 'Move to Previous Diff', 'command': 'git-diff:move-to-previous-diff' }
]
]
}
]
| |
Add directive based on jQuery animation API. | define [
"base"
], (App) ->
App.directive "reviewPanelCollapseHeight", ($parse) ->
return {
restrict: "A",
link: (scope, element, attrs) ->
scope.$watch (() -> $parse(attrs.reviewPanelCollapseHeight)(scope)), (shouldCollapse) ->
neededHeight = element.prop("scrollHeight")
if neededHeight > 0
... | |
Update git specs for latest libgit2 build | Git = require 'git'
describe "Git", ->
describe "getPath()", ->
it "returns the repository path for a working directory file path", ->
repo = new Git(require.resolve('fixtures/git/nohead.git/HEAD'))
expect(repo.getPath()).toBe require.resolve('fixtures/git/nohead.git') + '/'
repo = new Git(req... | Git = require 'git'
describe "Git", ->
describe "getPath()", ->
it "returns the repository path for a .git directory path", ->
repo = new Git(require.resolve('fixtures/git/master.git/HEAD'))
expect(repo.getPath()).toBe require.resolve('fixtures/git/master.git') + '/'
it "returns the repository ... |
Clean up comments on filter defintions. | ###
Route Filters
Filters for managing user access to application routes.
###
# Define Filters
# Check if a User is Logged In
# If a user is not logged in and attempts to go to an authenticated route,
# re-route them to the login screen.
checkUserLoggedIn = ->
if not Meteor.loggingIn() or Meteor.user()
... | ###
Route Filters
Filters for managing user access to application routes.
###
# Define Filters
###
Filter: Check if a User is Logged In
If a user is not logged in and attempts to go to an authenticated route,
re-route them to the login screen.
###
checkUserLoggedIn = ->
if not Meteor.loggingIn... |
Introduce app.react.Layout to fix SRP violation. | goog.provide 'app.react.Layout'
class app.react.Layout
###*
PATTERN(steida): Here we can choose mobile/tablet/desktop layout.
@param {app.Routes} routes
@param {app.react.Header} header
@param {app.react.Footer} footer
@constructor
###
constructor: (routes, header, footer) ->
{div} = Re... | |
Check if select content was already initialized. | `import Em from "vendor/ember"`
Component = Em.Component.extend
initializeValue: Em.on "init", ->
prompt = @get "content.prompt"
if prompt
options = @get "content.options"
options.unshift
label: prompt
value: ""
else
option... | `import Em from "vendor/ember"`
Component = Em.Component.extend
initializeValue: Em.on "init", ->
prompt = @get "content.prompt"
if prompt
options = @get "content.options"
if prompt isnt options[0].label
options.unshift
label: prompt
... |
Remove redundant assignment, handled below | class Teaspoon.Jasmine1.Fixture extends Teaspoon.fixture
window.fixture = @
@load: ->
args = arguments
throw "Teaspoon can't load fixtures outside of describe." unless @env().currentSuite || @env().currentSpec
if @env().currentSuite
@env().beforeEach => fixture.__super__.constructor.load.apply(@... | class Teaspoon.Jasmine1.Fixture extends Teaspoon.fixture
@load: ->
args = arguments
throw "Teaspoon can't load fixtures outside of describe." unless @env().currentSuite || @env().currentSpec
if @env().currentSuite
@env().beforeEach => fixture.__super__.constructor.load.apply(@, args)
@env().a... |
Add enum for media keys on Win32 | module.exports =
APPCOMMAND_BROWSER_BACKWARD: 1
APPCOMMAND_BROWSER_FORWARD: 2
APPCOMMAND_BROWSER_REFRESH: 3
APPCOMMAND_BROWSER_STOP: 4
APPCOMMAND_BROWSER_SEARCH: 5
APPCOMMAND_BROWSER_FAVORITES: ... | |
Refactor registrar to use separate definition files | _ = require "underscore"
AWS = require "aws-sdk"
Match = require "mtr-match"
Promise = require "bluebird"
module.exports = (options) ->
Match.check options, Match.ObjectIncluding
accessKeyId: String
secretAccessKey: String
region: String
Promise.promisifyAll new AWS.SWF _.extend
apiVersion: "2012-0... | |
Test the session detail page. | _ = require 'lodash'
expect = require('./helpers/expect')()
Page = require('./helpers/page')()
class SessionDetailPage extends Page
# @returns a promise resolving to a
# {download: button, display: button} object
scanFirstImageButtons: ->
div = element(By.repeater('image in session.scan.images').row(0))
... | |
Add unit tests for keyword arguments | sh = require "../index.js"
echo = sh "echo", "-n"
describe "keyword arguments", ->
describe "expanding key-value pairs", ->
it "happens when the values are strings", (done) ->
echo key: "value", (err, res) ->
res.should.equal "--key=value"
done()
it "c... | |
Add a couple of basic tests for SlackTextMessage | {SlackTextMessage, SlackRawMessage, SlackBotMessage, SlackRawListener, SlackBotListener} = require '../index'
should = require 'should'
class ClientMessage
ts = 0
constructor: (fields = {}) ->
@type = 'message'
@ts = (ts++).toString()
@[k] = val for own k, val of fields
getBody: ->
@text ? ""
... | |
Add initial browser process startup benchmark | #!/usr/bin/env coffee
{spawn, exec} = require 'child_process'
os = require 'os'
path = require 'path'
_ = require 'underscore-plus'
temp = require 'temp'
directoryToOpen = temp.mkdirSync('browser-process-startup-')
socketPath = path.join(os.tmpdir(), 'atom.sock')
numberOfRuns = 10
launchAtom = (callback) ->
cmd = ... | |
Check value existence to determine return value | _ = require 'underscore'
traverse = require 'traverse'
KONFIG = {}
do ->
unless 'first' of Array.prototype
Object.defineProperty Array.prototype, 'first',
get: -> this[0]
unless 'last' of Array.prototype
Object.defineProperty Array.prototype, 'last',
get: -> this[this.length - 1]
try
modu... | _ = require 'underscore'
traverse = require 'traverse'
KONFIG = {}
do ->
unless 'first' of Array.prototype
Object.defineProperty Array.prototype, 'first',
get: -> this[0]
unless 'last' of Array.prototype
Object.defineProperty Array.prototype, 'last',
get: -> this[this.length - 1]
try
modu... |
Add some basic indie specs | describe 'Indie', ->
Validate = require('../lib/validate')
Indie = require('../lib/indie')
indie = null
beforeEach ->
indie?.dispose()
indie = new Indie({})
describe 'Validations', ->
it 'just cares about a name', ->
linter = {}
Validate.linter(linter, true)
expect(linter.name)... | |
Create a script for connecting UIComponent iframes with their parents | # Register the port recieved from the parent window, and stop listening for messages on the window object.
window.addEventListener "message", (event) ->
return unless event.source == window.parent
currentFunction = arguments.callee
# Check event.data against iframeMessageSecret so we can determine that this mess... | |
Fix function name to be consistent with convention | fs = require 'fs-plus'
path = require 'path'
ipc = require 'ipc'
module.exports =
class AtomPortable
@getPortableAtomHomePath: ->
execDirectoryPath = path.dirname(process.execPath)
path.join(execDirectoryPath, '..', '.atom')
@isPortableInstall: (platform, environmentAtomHome, defaultHome) ->
return fa... | fs = require 'fs-plus'
path = require 'path'
ipc = require 'ipc'
module.exports =
class AtomPortable
@getPortableAtomHomePath: ->
execDirectoryPath = path.dirname(process.execPath)
path.join(execDirectoryPath, '..', '.atom')
@isPortableInstall: (platform, environmentAtomHome, defaultHome) ->
return fa... |
Update beatmap icon with new font classes | ###*
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public ... | ###*
* Copyright 2015 ppy Pty. Ltd.
*
* This file is part of osu!web. osu!web is distributed with the hope of
* attracting more community contributions to the core ecosystem of osu!.
*
* osu!web is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.