Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make sure all variables are string before joining | path = require 'path'
{File} = require 'atom'
module.exports =
toExt: (srcPath, ext) ->
srcExt = path.extname srcPath
return path.join(
path.dirname(srcPath),
"#{path.basename(srcPath, srcExt)}.#{ext}"
)
resolvePath: (srcPath) ->
destination = atom.config.get('coffee-compile.destinatio... | path = require 'path'
{File} = require 'atom'
module.exports =
toExt: (srcPath, ext) ->
srcExt = path.extname srcPath
return path.join(
path.dirname(srcPath),
"#{path.basename(srcPath, srcExt)}.#{ext}"
)
resolvePath: (srcPath) ->
destination = atom.config.get('coffee-compile.destinatio... |
Update server example to work with latest Express | express = require "express"
jsdom = require("jsdom").jsdom
$ = require "jquery"
transparency = require "transparency"
# Register transparency as a plugin for the given jQuery instance
transparency.register $
app = express.createServer()
app.configure ->
app.use app.router
app.configure "dev... | express = require "express"
jsdom = require("jsdom").jsdom
$ = require "jquery"
transparency = require "transparency"
# Register transparency as a plugin for the given jQuery instance
transparency.register $
app = express()
app.configure ->
app.use app.router
app.configure "development", ->... |
Update -> method to use _.find. | debug = require('debug')('sphere-product-import-common-utils')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
class CommonUtils
constructor: (@logger) ->
debug "Enum Validator initialized."
uniqueObjectFilter: (objCollection) =>
uniques = []
_.each objCollection, (obj) =>
if not ... | debug = require('debug')('sphere-product-import-common-utils')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
class CommonUtils
constructor: (@logger) ->
debug "Enum Validator initialized."
uniqueObjectFilter: (objCollection) =>
uniques = []
_.each objCollection, (obj) =>
if not ... |
Convert job init from "scrape people" to "scrape rep.." | # Copyright 2013 Matt Farmer
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | # Copyright 2013 Matt Farmer
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
Save pickup time and instructions | angular.module('admin.order_cycles').controller "AdminSimpleCreateOrderCycleCtrl", ($scope, OrderCycle, Enterprise, EnterpriseFee) ->
$scope.enterprises = Enterprise.index (enterprises) =>
enterprise = enterprises[Object.keys(enterprises)[0]]
OrderCycle.addSupplier enterprise.id
OrderCycle.addDistributor ... | angular.module('admin.order_cycles').controller "AdminSimpleCreateOrderCycleCtrl", ($scope, OrderCycle, Enterprise, EnterpriseFee) ->
$scope.enterprises = Enterprise.index (enterprises) =>
enterprise = enterprises[Object.keys(enterprises)[0]]
OrderCycle.addSupplier enterprise.id
OrderCycle.addDistributor ... |
Fix changing args to '' | V = Visualizer
identifyObservable = R.curryN 2, (baseId, observable) ->
rootId = baseId + 'r'
recursionLevel = (rootId.match(/r/g) || []).length - 1
observable.root.args ?= V.Roots[observable.root.type].getDefaultArgs?(recursionLevel)
root: R.assoc('id', rootId, R.pick(['type', 'args'], observable.root))
o... | V = Visualizer
identifyObservable = R.curryN 2, (baseId, observable) ->
rootId = baseId + 'r'
recursionLevel = (rootId.match(/r/g) || []).length - 1
if !observable.root.args?
observable.root.args = V.Roots[observable.root.type].getDefaultArgs?(recursionLevel)
root: R.assoc('id', rootId, R.pick(['type', '... |
Clean up methods order in Selector prefixer | Prefixer = require('./prefixer')
utils = require('./utils')
class Selector extends Prefixer
# Is rule selectors need to be prefixed
check: (rule) ->
rule.selector.indexOf(@name) != -1
# Clone and add prefixes for at-rule
add: (rule, prefix) ->
prefixed = @replace(rule.selector, prefix)
return... | Prefixer = require('./prefixer')
utils = require('./utils')
class Selector extends Prefixer
# Is rule selectors need to be prefixed
check: (rule) ->
rule.selector.indexOf(@name) != -1
# Return prefixed version of selector
prefixed: (prefix) ->
@name.replace(/^([^\w]*)/, '$1' + prefix)
# Lazy lo... |
Add null checking for option argument | TodoStore = require('./stores/todo_store')
TodoActions = require('./actions/todo_actions')
TodoApp = require('./components/TodoApp')
# Invoked in a Rails template with JSON data passed in.
React._initTodoApp = (options) ->
# Instantiates the stores
stores =
TodoStore: new TodoStore(options["todos"])
... | TodoStore = require('./stores/todo_store')
TodoActions = require('./actions/todo_actions')
TodoApp = require('./components/TodoApp')
# Invoked in a Rails template with JSON data passed in.
React._initTodoApp = (options) ->
# Instantiates the stores
stores =
TodoStore: new TodoStore(options["todos"] if ... |
Correct UTM paremeters for branding element. | React = require 'react'
module.exports = React.createClass
displayName: 'MarqueeBranding'
getDefaultProps: -> {
source : global.config?.PUBLICATION_SHORT_NAME
medium : 'MarqueeBranding'
campaign : 'sdk_site'
logo_only : false
}
render: ... | React = require 'react'
module.exports = React.createClass
displayName: 'MarqueeBranding'
getDefaultProps: -> {
source : global.config?.PUBLICATION_SHORT_NAME
medium : 'web'
campaign : 'sdk_site'
content : 'MarqueeBranding'
logo_only ... |
Add tokenizeLines to null grammar | Token = require 'token'
EventEmitter = require 'event-emitter'
_ = require 'underscore'
### Internal ###
module.exports =
class NullGrammar
name: 'Null Grammar'
scopeName: 'text.plain.null-grammar'
getScore: -> 0
tokenizeLine: (line) ->
{ tokens: [new Token(value: line, scopes: ['null-grammar.text.plain'... | Token = require 'token'
EventEmitter = require 'event-emitter'
_ = require 'underscore'
### Internal ###
module.exports =
class NullGrammar
name: 'Null Grammar'
scopeName: 'text.plain.null-grammar'
getScore: -> 0
tokenizeLine: (line) ->
{ tokens: [new Token(value: line, scopes: ['null-grammar.text.plain'... |
Change win/linux key to ctrl-alt-c | # 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... |
Change keymaps and add confirm | # 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... |
Test spec handles mock API requests, very general regex used (/.*/). | 'use strict'
describe 'Controller: MainCtrl', () ->
# load the controller's module
beforeEach module 'appApp'
MainCtrl = {}
scope = {}
# Initialize the controller and a mock scope
beforeEach inject ($controller, $rootScope) ->
scope = $rootScope.$new()
MainCtrl = $controller 'MainCtrl', {
... | 'use strict'
describe 'Controller: MainCtrl', () ->
# load the controller's module
beforeEach module 'appApp'
MainCtrl = {}
scope = {}
# Initialize the controller and a mock scope
beforeEach inject ($injector, $controller, $rootScope) ->
$httpBackend = $injector.get('$httpBackend')
$httpBackend.... |
Clean up error output for cli tool a bit | numeral = require("numeral")
balance = require("./crypto-balance")
module.exports.run = ->
addr = process.argv[2]
unless addr
console.log "Usage: balance <address>"
process.exit 1
balance addr
.then (items) ->
for item in items
if item.status == 'success'
console.log "#{num... | numeral = require("numeral")
_ = require("lodash")
balance = require("./crypto-balance")
module.exports.run = ->
addr = process.argv[2]
unless addr
console.log "Usage: balance <address>"
process.exit 1
balance addr
.then (items) ->
for item in items
if item.status == 'success'
... |
Add to_euler compatibility with turntable camera. Specify rotation order by Blender's nomenclature. | glm = require 'gl-matrix'
glm.quat.to_euler = (out=[0,0,0], quat, order='YZX') ->
if order != 'YZX'
throw new Error "Euler order "+order+" not supported yet."
# It will return YZX euler. TODO: implement other orders
x = quat[0]
y = quat[1]
z = quat[2]
w = quat[3]
test = x*y + z*w;
... | glm = require 'gl-matrix'
glm.quat.to_euler = (out=[0,0,0], quat, order='XZY') ->
if order != 'XZY'
throw new Error "Euler order "+order+" not supported yet."
# It will return XZY euler. TODO: implement other orders
x = quat[0]
y = quat[1]
z = quat[2]
w = quat[3]
test = x*y + z*w;
... |
Use both \ and / in regexes so anymatch OKs Win/POSIX paths | module.exports = config:
files:
javascripts: joinTo:
'libraries.js': /^app\/jquery\.js/
'app.js': /^(?!app\/jquery\.js)/
stylesheets: joinTo: 'app.css'
| module.exports = config:
files:
javascripts: joinTo:
'libraries.js': /^app[\\\/]jquery\.js/
'app.js': /^(?!app[\\\/]jquery\.js)/
stylesheets: joinTo: 'app.css'
|
Revert "Removed unused template helper" | class window.UserStatisticsView extends Backbone.Marionette.ItemView
className: 'statistics'
template: 'users/statistics'
initialize: ->
@listenTo @model, 'change', @render
| class window.UserStatisticsView extends Backbone.Marionette.ItemView
className: 'statistics'
template: 'users/statistics'
templateHelpers: =>
topic: @model.user_topics().first()?.toJSON()
initialize: ->
@listenTo @model, 'change', @render
|
Throw if process stays locked for too long | surveyor = require './lib/surveyor.coffee'
websocket = require './lib/websocket.coffee'
webserver = require './lib/webserver.coffee'
webserver.listen 4001
util = require './lib/util.coffee'
model = require './lib/model.coffee'
lock = false
check = ->
return if lock
lock = true
surveyor.getManifest (err) ->
t... | surveyor = require './lib/surveyor.coffee'
websocket = require './lib/websocket.coffee'
webserver = require './lib/webserver.coffee'
webserver.listen 4001
util = require './lib/util.coffee'
model = require './lib/model.coffee'
lock = false
lockTimer = null
lockTimeout = process.env.LOCKTIMEOUT or 30 * 1000
check = ->... |
Throw division by zero and wrap in try/catch | _ = require 'underscore'
module.exports =
dimensions: (metric = @get('metric')) ->
@get('dimensions')[metric] if metric
# Wrap only X Y/Z; leave X/Y alone
superscriptFractions: (string) ->
string?.replace /(\d+)(?:\s+)(\d+\/\d+)/g, '$1 <sup>$2</sup>'
fractionToDecimal: (string) ->
split = string.s... | _ = require 'underscore'
module.exports =
dimensions: (metric = @get('metric')) ->
@get('dimensions')[metric] if metric
# Wrap only X Y/Z; leave X/Y alone
superscriptFractions: (string) ->
string?.replace /(\d+)(?:\s+)(\d+\/\d+)/g, '$1 <sup>$2</sup>'
fractionToDecimal: (string) ->
split = stri... |
Send verbose output to stderr | fs = require 'fs'
{ diff } = require './index'
module.exports = (argv) ->
options = require('dreamopt') [
"Usage: json-diff [-v] first.json second.json"
"Arguments:"
" first.json Old file #var(file1) #required"
" second.json New file #var(file2) #required"
"General ... | fs = require 'fs'
{ diff } = require './index'
module.exports = (argv) ->
options = require('dreamopt') [
"Usage: json-diff [-v] first.json second.json"
"Arguments:"
" first.json Old file #var(file1) #required"
" second.json New file #var(file2) #required"
"General ... |
Add "open .atom" button to general config view | ConfigPanel = require 'config-panel'
{$$} = require 'space-pen'
$ = require 'jquery'
_ = require 'underscore'
module.exports =
class GeneralConfigPanel extends ConfigPanel
@content: ->
@form id: 'general-config-panel', class: 'form-horizontal', =>
@fieldset =>
@legend "General Settings"
@d... | ConfigPanel = require 'config-panel'
{$$} = require 'space-pen'
$ = require 'jquery'
_ = require 'underscore'
module.exports =
class GeneralConfigPanel extends ConfigPanel
@content: ->
@form id: 'general-config-panel', class: 'form-horizontal', =>
@fieldset =>
@legend "General Settings"
@d... |
Allow login from custom oAuth in accounts meld | orig_updateOrCreateUserFromExternalService = Accounts.updateOrCreateUserFromExternalService
Accounts.updateOrCreateUserFromExternalService = (serviceName, serviceData, options) ->
if serviceName not in ['facebook', 'github', 'gitlab', 'google', 'meteor-developer', 'linkedin', 'twitter']
return
if serviceName is 'm... | orig_updateOrCreateUserFromExternalService = Accounts.updateOrCreateUserFromExternalService
Accounts.updateOrCreateUserFromExternalService = (serviceName, serviceData, options) ->
if serviceName not in ['facebook', 'github', 'google', 'meteor-developer', 'linkedin', 'twitter'] and serviceData._oAuthCustom isnt true
... |
Fix double-submission prevention not working. | App.PreventDoubleSubmission =
disable_buttons: (buttons) ->
setTimeout ->
buttons.each ->
button = $(this)
unless button.hasClass('disabled')
loading = button.data('loading') ? '...'
button.addClass('disabled').attr('disabled', 'disabled')
button.data('text', bu... | App.PreventDoubleSubmission =
disable_buttons: (buttons) ->
setTimeout ->
buttons.each ->
button = $(this)
unless button.hasClass('disabled')
loading = button.data('loading') ? '...'
button.addClass('disabled').attr('disabled', 'disabled')
button.data('text', bu... |
Add comments in memory on click. | ETahi.MessageTaskController = ETahi.TaskController.extend
newCommentBody: ""
actions:
clearMessageContent: -> null
postComment: ->
commentFields =
body: @get('newCommentBody')
newComment = @store.createRecord('comment', commentFields)
| ETahi.MessageTaskController = ETahi.TaskController.extend
newCommentBody: ""
actions:
clearMessageContent: -> null
postComment: ->
userId = Tahi.currentUser.id.toString()
commenter = @store.all('user').findBy('id', userId)
commentFields =
commenter: commenter
messageTask: ... |
Clarify where this is available | Grammar = require './grammar'
# A grammar with no patterns that is always available
module.exports =
class NullGrammar extends Grammar
constructor: (registry) ->
name = 'Null Grammar'
scopeName = 'text.plain.null-grammar'
super(registry, {name, scopeName})
getScore: -> 0
| Grammar = require './grammar'
# A grammar with no patterns that is always available from a {GrammarRegistry}
module.exports =
class NullGrammar extends Grammar
constructor: (registry) ->
name = 'Null Grammar'
scopeName = 'text.plain.null-grammar'
super(registry, {name, scopeName})
getScore: -> 0
|
Make Front-Facing Storylets Retreatable By Default | class Storylet
constructor: (@id, @title, @text, @choices, @frontFacingChoice) ->
Object.freeze @
isVisibleWith: (qualityLibrary) -> frontFacingChoice?.isVisibleWith qualityLibrary
class Choice
constructor: (@title, @text, @visibleReqs, @activeReqs, @next) ->
reqsAreMet = (reqs, qualityLibrary) ->
fo... | class Storylet
constructor: (@id, @title, @text, @choices, @frontFacingChoice) ->
Object.freeze @
isVisibleWith: (qualityLibrary) -> frontFacingChoice?.isVisibleWith qualityLibrary
class Choice
constructor: (@title, @text, @visibleReqs, @activeReqs, @next) ->
reqsAreMet = (reqs, qualityLibrary) ->
fo... |
Make file's paths more subtle in listing | Bacon = require('baconjs')
moment = require('moment')
module.exports = [
{
title: 'Name'
width: 60
cellContent: (item) -> item.relPath
},{
title: 'Date created'
width: 20
cellContent: (item) -> moment(item.stats.birthtime).fromNow()
},{
title: 'Date modified'
width: 20
cellCon... | Bacon = require('baconjs')
moment = require('moment')
h = require('virtual-dom/h')
Path = require('path')
module.exports = [
{
title: 'Name'
width: 60
cellContent: (item) ->
pieces = item.relPath.split(Path.sep)
[
h 'span.text-subtle', [
pieces.slice(0, -1).join(Path.sep)
... |
Fix hawk middleware to only add payload hash when there is a request body | #= require hawk
Marbles.HTTP.Middleware.Hawk = class HawkMiddleware
constructor: (options = {}) ->
options = _.clone(options)
unless options.credentials
throw new Error("HawkMiddleware: credentials member of options is required!")
@credentials = {
id: options.credentials.id,
key: optio... | #= require hawk
Marbles.HTTP.Middleware.Hawk = class HawkMiddleware
constructor: (options = {}) ->
options = _.clone(options)
unless options.credentials
throw new Error("HawkMiddleware: credentials member of options is required!")
@credentials = {
id: options.credentials.id,
key: optio... |
Add feed link to menu | require 'semantic-ui-css/components/icon.css'
require 'semantic-ui-css/components/menu.css'
require 'semantic-ui-css/components/sidebar.css'
require '../../css/menu.css'
React = require 'react'
module.exports = React.createClass
displayName: 'MainMenu'
render: ->
active = (id) =>
if @props... | require 'semantic-ui-css/components/icon.css'
require 'semantic-ui-css/components/menu.css'
require 'semantic-ui-css/components/sidebar.css'
require '../../css/menu.css'
api = require '../backend.coffee'
React = require 'react'
module.exports = React.createClass
displayName: 'MainMenu'
render: ->
act... |
Add budget and change to left menu | class GameState
customers: []
agents: []
requestQueues: {}
chanceOfRequest: 0.005
tickables: []
tick: 0
money: 1000000
reputation: 0.5
agentSpawner: new AgentSpawner()
addAgent: (agent) ->
@agents.push(agent)
@tickables.push(agent)
fireAgent: (agent) ->
@agents.filter((item) ->
... | class GameState
customers: []
agents: []
requestQueues: {}
chanceOfRequest: 0.005
tickables: []
tick: 0
money: 1000000
reputation: 0.5
agentSpawner: new AgentSpawner()
addAgent: (agent) ->
@agents.push(agent)
@tickables.push(agent)
fireAgent: (agent) ->
@agents.filter((item) ->
... |
Reduce wait time for scroll to bottom | templateName = 'commentList'
TemplateClass = Template[templateName]
TemplateClass.created = ->
series = @data?.series
unless series then throw new Error('No series ID provided for comment list.')
@isEditing = new ReactiveVar(false)
# Old subscriptions are retained if we need to view the same series later.
Me... | templateName = 'commentList'
TemplateClass = Template[templateName]
TemplateClass.created = ->
series = @data?.series
unless series then throw new Error('No series ID provided for comment list.')
@isEditing = new ReactiveVar(false)
# Old subscriptions are retained if we need to view the same series later.
Me... |
Fix background mismatch between MenuState, PlayState. | # Defines
# =======
define [], () ->
'use strict'
defines =
# Turn off here to disable entirely (@release).
# Off by default for performance.
debugging: off
# Turn off here to disable entirely (@release).
developing: on
gameW: 416
gameH: 600
artH: 2912
mapH: 3152 # +240
... | # Defines
# =======
define [], () ->
'use strict'
defines =
# Turn off here to disable entirely (@release).
# Off by default for performance.
debugging: off
# Turn off here to disable entirely (@release).
developing: on
gameW: 416
gameH: 600
artH: 2912
mapH: 3136 # +224
... |
Throw error when option value is not valid | class OptionParser
###
* Parse command-line options
* @param {Array} @args
* @param {Object} opts
###
constructor: (@args, opts) ->
options = {}
for opt in opts
short = opt[0]
long = opt[1]
choices = if opt[3]? then opt[3] else null
optName = long.replace('--', '')
... | class OptionParser
###
* Parse command-line options
* @param {Array} @args
* @param {Object} opts
###
constructor: (@args, opts) ->
options = {}
for opt in opts
short = opt[0]
long = opt[1]
choices = if opt[3]? then opt[3] else null
optName = long.replace('--', '')
... |
Handle focus when opening go to line modal | {CompositeDisposable} = require 'event-kit'
{SpacePenDSL} = require 'atom-utils'
module.exports =
class GoToLineElement extends HTMLElement
SpacePenDSL.includeInto(this)
@content: ->
@tag 'atom-text-editor', mini: true, outlet: 'miniEditor'
@div class: 'message', outlet: 'message', """
Enter a cell ro... | {SpacePenDSL} = require 'atom-utils'
module.exports =
class GoToLineElement extends HTMLElement
SpacePenDSL.includeInto(this)
@content: ->
@tag 'atom-text-editor', mini: true, outlet: 'miniEditor'
@div class: 'message', outlet: 'message', """
Enter a cell row:column to go to. The column can be either ... |
Move withinTolerance() into Kona.Trigger to be overriden in derived classes for checking activation conditions | # A generic class representing a node that activates a callback
# when intersecting with a designated `collector entity`
#
# Note that the word 'trigger' here is not connected with
# triggering as defined in the `Kona.Event` interface
#
# TODO: trigger examples
#
class Kona.Trigger extends Kona.Entity
constructor: (o... | # A generic class representing a node that activates a callback
# when intersecting with a designated `collector entity`
#
# Note that the word 'trigger' here is not connected with
# triggering as defined in the `Kona.Event` interface
#
# TODO: trigger examples
#
class Kona.Trigger extends Kona.Entity
constructor: (o... |
Change should.js require to chai.js in spec |
<%= safeSlugname %> = require '../lib/<%= slugname %>'
<% if (testFramework === 'mocha') { %>
assert = require 'should' <% } %>
describe '<%= safeSlugname %>', ->
it 'should be awesome', -> <% if (testFramework === 'jasmine') { %>
expect(<%= safeSlugname %>()).toEqual('awesome')<% } %><% if (testFramework === ... |
<%= safeSlugname %> = require '../lib/<%= slugname %>'
<% if (testFramework === 'mocha') { %>
should = require('chai').should() <% } %>
describe '<%= safeSlugname %>', ->
it 'should be awesome', -> <% if (testFramework === 'jasmine') { %>
expect(<%= safeSlugname %>()).toEqual('awesome')<% } %><% if (testFramew... |
Add neccessary route for debugging | module.exports = (match) ->
match '', 'home#index'
match 'u/6045251/shiny-wight/index.html', 'home#index'
match 'shiny-wight/index.html', 'home#index'
| module.exports = (match) ->
match '', 'home#index'
match 'index.html', 'home#index'
match 'u/6045251/shiny-wight/index.html', 'home#index'
match 'shiny-wight/index.html', 'home#index'
|
Set properties to null before they are used to create new user | App.UsersNewRoute = App.AuthenticatedRoute.extend
setupController: (controller, model)->
controller.set "domains", @store.find("domain")
| App.UsersNewRoute = App.AuthenticatedRoute.extend
setupController: (controller)->
controller.setProperties
"firstName": null
"lastName": null
"email": null
"password": null
"role": null
|
Use array to avoid beginning of subsequent IPs be merged with the end of preceding IPs | # The SplitStr component receives a string in the in port, splits it by
# string specified in the delimiter port, and send each part as a separate
# packet to the out port
noflo = require "noflo"
class SplitStr extends noflo.Component
constructor: ->
@delimiterString = "\n"
@string = ""
@... | # The SplitStr component receives a string in the in port, splits it by
# string specified in the delimiter port, and send each part as a separate
# packet to the out port
noflo = require "noflo"
class SplitStr extends noflo.Component
constructor: ->
@delimiterString = "\n"
@strings = []
... |
Fix videoLoader. Run `load` for HTMLElement instead jQuery el. | {
jQuery: $
} = uploadcare
uploadcare.namespace 'utils', (ns) ->
trackLoading = (image, src) ->
def = $.Deferred()
if src
image.src = src
if image.complete
def.resolve(image)
else
$(image).one 'load', =>
def.resolve(image)
$(image).one 'error', =>
def.reje... | {
jQuery: $
} = uploadcare
uploadcare.namespace 'utils', (ns) ->
trackLoading = (image, src) ->
def = $.Deferred()
if src
image.src = src
if image.complete
def.resolve(image)
else
$(image).one 'load', =>
def.resolve(image)
$(image).one 'error', =>
def.reje... |
Add current env to child env, if child env is specified | childProcess = require 'child_process'
path = require 'path'
command = "node #{path.resolve __dirname, '../../bin/iced.js'}"
module.exports = (args...) ->
args[0] = "#{command} #{args[0]}"
childProcess.exec.apply childProcess, args
| childProcess = require 'child_process'
path = require 'path'
command = "node #{path.resolve __dirname, '../../bin/iced.js'}"
module.exports = (args...) ->
args[0] = "#{command} #{args[0]}"
if typeof args[1] is 'object' and args[1].env?
newEnv = process.env
newEnv[key] = value for key, value of args[1].env
... |
Fix keyboard resize for android devices | if Meteor.isCordova
document.addEventListener 'deviceready', ->
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
window.addEventListener 'native.keyboardshow', ->
$('.main-content').css 'height', window.innerHeight
window.addEventListener 'native.keyboard... | if Meteor.isCordova
if device.platform.toLowerCase() isnt 'android'
document.addEventListener 'deviceready', ->
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
window.addEventListener 'native.keyboardshow', ->
$('.main-content').css 'height', window.... |
Implement Collision Check Temporary Table. | _ = require "underscore"
Promise = require "bluebird"
TemporaryTable = require "./TemporaryTable"
class CollisionCheckTemporaryTable extends TemporaryTable
insert: (externalObject) ->
@checkIfExists externalObject
.then (exists) ->
if not exists
super
else
console.warn "Primary k... | _ = require "underscore"
Promise = require "bluebird"
TemporaryTable = require "./TemporaryTable"
class CollisionCheckTemporaryTable extends TemporaryTable
insert: (externalObject) ->
@checkIfExists externalObject
.then (exists) ->
if not exists
super(externalObject)
else
console... |
Change tab length in GFM. | "*":
"autocomplete-plus":
confirmCompletion: "enter"
fileBlacklist: [
"*.md"
"*.txt"
]
core:
telemetryConsent: "limited"
editor:
softTabs: false
tabLength: 4
"exception-reporting":
userId: "2c613f71-39b8-42c5-bef0-f61d264be689"
"git-diff":
showIconsInEditorGutter: t... | "*":
"autocomplete-plus":
confirmCompletion: "enter"
fileBlacklist: [
"*.md"
"*.txt"
]
core:
telemetryConsent: "limited"
editor:
softTabs: false
tabLength: 4
"exception-reporting":
userId: "2c613f71-39b8-42c5-bef0-f61d264be689"
"git-diff":
showIconsInEditorGutter: t... |
Improve how we inject test data for e2e testing purposes | util = require 'util'
module.exports = (app, mongoose, options) ->
models = require('./models')(mongoose)
controllers = require('./controllers')(models)
auth = require('./authentication')(app, models, options)
require('./routes')(app, auth, controllers)
app.configure 'test', ->
console.log 'in... | util = require 'util'
module.exports = (app, mongoose, options) ->
models = require('./models')(mongoose)
controllers = require('./controllers')(models)
auth = require('./authentication')(app, models, options)
require('./routes')(app, auth, controllers)
resetTestDb = ->
app.configure 'test', ->
... |
Make the markdown editor behave more like a normal input | # @cjsx React.DOM
React = require 'react'
Markdown = require './markdown'
module.exports = React.createClass
displayName: 'MarkdownEditor'
getInitialState: ->
previewing: false
value: @props.defaultValue ? ''
render: ->
previewing = @props.previewing ? @state.previewing
<div className={['mark... | # @cjsx React.DOM
React = require 'react'
Markdown = require './markdown'
alert = require '../lib/alert'
NOOP = Function.prototype
module.exports = React.createClass
displayName: 'MarkdownEditor'
getDefaultProps: ->
placeholder: ''
value: ''
onChange: NOOP
getInitialState: ->
previewing: fals... |
Add description for config setting | PackageGeneratorView = require './package-generator-view'
module.exports =
config:
createInDevMode:
default: false
type: 'boolean'
activate: ->
@view = new PackageGeneratorView()
deactivate: ->
@view?.destroy()
| PackageGeneratorView = require './package-generator-view'
module.exports =
config:
createInDevMode:
default: false
type: 'boolean'
description: 'When disabled, generated packages are linked into Atom in both normal mode and dev mode. When enabled, generated packages are linked into Atom only in... |
Update to use getPaths() instead of getPath() | {View} = require 'atom-space-pen-views'
path = require 'path'
module.exports =
class ProjectManagerAddView extends View
projectManager: null
@content: ->
@div class: 'project-manager', =>
@div class: 'editor-container', outlet: 'editorContainer', =>
@div =>
@input outlet:'editor', clas... | {View} = require 'atom-space-pen-views'
path = require 'path'
module.exports =
class ProjectManagerAddView extends View
projectManager: null
@content: ->
@div class: 'project-manager', =>
@div class: 'editor-container', outlet: 'editorContainer', =>
@div =>
@input outlet:'editor', clas... |
Change api urls in client side | window.coviolations ?=
views: {}
models: {}
plotting: {}
push: {}
$ ->
app = window.coviolations
class app.models.UserProject extends Backbone.Model
### User project model ###
urlRoot: '/api/v1/userprojects/'
class app.models.UserProjectCollection extends Backbone.Collect... | window.coviolations ?=
views: {}
models: {}
plotting: {}
push: {}
$ ->
app = window.coviolations
class app.models.UserProject extends Backbone.Model
### User project model ###
urlRoot: '/api/v1/projects/project/'
class app.models.UserProjectCollection extends Backbone.Col... |
Return proper Ember.RSVP.Promise to avoid troubles on browsers | Route = Ember.Route.extend
model: ->
# return the current user as the model if authenticated, otherwise a blank object
new Promise (resolve, reject) =>
promise = $.ajax
url: '/api/me'
dataType: 'json'
promise.done (result) =>
user = Ember.Object.create(result)
if re... | Route = Ember.Route.extend
model: ->
# return the current user as the model if authenticated, otherwise a blank object
new Ember.RSVP.Promise (resolve, reject) =>
promise = $.ajax
url: '/api/me'
dataType: 'json'
promise.done (result) =>
user = Ember.Object.create(result)
... |
Add support for Ruby bang and question methods | {Task} = require 'atom'
ctags = require 'ctags'
fs = require 'fs-plus'
handlerPath = require.resolve('./load-tags-handler')
module.exports =
getTagsFile: ->
tagsFile = atom.project.resolve("tags")
return tagsFile if fs.isFileSync(tagsFile)
tagsFile = atom.project.resolve(".tags")
return tagsFile if... | {Task} = require 'atom'
ctags = require 'ctags'
fs = require 'fs-plus'
handlerPath = require.resolve('./load-tags-handler')
module.exports =
getTagsFile: ->
tagsFile = atom.project.resolve("tags")
return tagsFile if fs.isFileSync(tagsFile)
tagsFile = atom.project.resolve(".tags")
return tagsFile if... |
Add 'X-Ledger-Environment' in HTTP requests header | ledger.api ?= {}
class ledger.api.HttpClient extends @HttpClient
constructor: () -> super
authenticated: -> ledger.api.authenticated(@_baseUrl)
class ledger.api.RestClient
@API_BASE_URL: ledger.config.restClient.baseUrl
@singleton: () -> @instance ||= new @()
http: () ->
@_client ||= @_httpClientFact... | ledger.api ?= {}
class ledger.api.HttpClient extends @HttpClient
constructor: () -> super
authenticated: -> ledger.api.authenticated(@_baseUrl)
class ledger.api.RestClient
@API_BASE_URL: ledger.config.restClient.baseUrl
@singleton: () -> @instance ||= new @()
http: () ->
@_client ||= @_httpClientFact... |
Fix wrong way to force currency symbol after the amount | Darkswarm.filter "localizeCurrency", (currencyConfig)->
# Convert number to string currency using injected currency configuration.
(amount) ->
# Set country code (eg. "US").
currency_code = if currencyConfig.display_currency then " " + currencyConfig.currency else ""
# Set decimal points, 2 or 0 if hid... | Darkswarm.filter "localizeCurrency", (currencyConfig)->
# Convert number to string currency using injected currency configuration.
(amount) ->
# Set country code (eg. "US").
currency_code = if currencyConfig.display_currency then " " + currencyConfig.currency else ""
# Set decimal points, 2 or 0 if hide... |
Allow overriding of elasticsearch config via environment | 'use strict';
util = require 'util'
{EventEmitter} = require 'events'
elasticsearch = require 'elasticsearch'
_ = require 'lodash'
debug = require('debug')('meshblu-elasticsearch')
request = require 'request'
MESSAGE_SCHEMA =
type: 'object'
properties:
exampleBoolean:
typ... | 'use strict';
util = require 'util'
{EventEmitter} = require 'events'
elasticsearch = require 'elasticsearch'
_ = require 'lodash'
debug = require('debug')('meshblu-elasticsearch')
request = require 'request'
MESSAGE_SCHEMA =
type: 'object'
properties:
exampleBoolean:
typ... |
Make focusout handling compatible with React editor | {$} = require 'atom'
module.exports =
configDefaults:
enabled: false
activate: ->
atom.workspaceView.on 'focusout', ".editor:not(.mini)", (event) =>
editor = event.targetView()?.getModel()
@autosave(editor)
atom.workspaceView.on 'pane:before-item-destroyed', (event, paneItem) =>
@au... | {$} = require 'atom'
module.exports =
configDefaults:
enabled: false
activate: ->
atom.workspaceView.on 'focusout', ".editor:not(.mini)", (event) =>
editor = $(event.target).closest('.editor').view()?.getModel()
@autosave(editor)
atom.workspaceView.on 'pane:before-item-destroyed', (event,... |
Detach custom list window even if downloading fails | {$, EditorView, View} = require 'atom'
utils = require './Utils'
module.exports=
class PackageListCustomListView extends View
@content: ->
@div class: 'overlay from-top', =>
@subview 'gistUrl', new EditorView(mini: true, placeholderText: 'ID of Gist with packages list.')
@div class: 'block', =>
... | {$, EditorView, View} = require 'atom'
utils = require './Utils'
module.exports=
class PackageListCustomListView extends View
@content: ->
@div class: 'overlay from-top', =>
@subview 'gistUrl', new EditorView(mini: true, placeholderText: 'ID of Gist with packages list.')
@div class: 'block', =>
... |
Enable search in users table | window.UsersComponent = class UsersComponent
@initialize: ->
@addEventListeners()
@addEventListeners: ->
@userDetailsTooltip()
@userDetailsTooltip: ->
tooltipClass = '.information-tooltip'
$(document).on('click', "#{tooltipClass}-trigger", (ev) ->
ev.preventDefault()
$this = $(@)
... | window.UsersComponent = class UsersComponent
@initialize: ->
@addEventListeners()
@addEventListeners: ->
@userDetailsTooltip()
#Enables search through users table
enableSearch()
@userDetailsTooltip: ->
tooltipClass = '.information-tooltip'
$(document).on('click', "#{tooltipClass}-trigger... |
Refactor parser specs to gain one expectation per spec | Walrus = require '../lib/walrus'
describe 'Walrus.Parser', ->
it 'should be defined', -> expect( Walrus.Parser ).toBeDefined( )
describe '#parse', ->
it 'should be defined', -> expect( Walrus.Parser.parse ).toBeDefined( )
it 'should parse all examples correctly', ->
fs = require 'fs'
pat... | Walrus = require '../lib/walrus'
describe 'Walrus.Parser', ->
it 'should be defined', -> expect( Walrus.Parser ).toBeDefined( )
describe '#parse', ->
it 'should be defined', -> expect( Walrus.Parser.parse ).toBeDefined( )
fs = require 'fs'
path = require 'path'
specs = './spec/examples'
... |
Update smoke test with latest API | require('./spec_helper')
spy = require('through2-spy')
describe 'smoke test', ->
createFS = require('../index')
coffee = require('gulp-coffee')
it 'should mock gulp', (done) ->
fs = createFS
src:
coffee:
'sample.coffee': """
console.log 'Hello world'
... | require('./spec_helper')
spy = require('through2-spy')
describe 'smoke test', ->
createFS = require('../index')
coffee = require('gulp-coffee')
it 'should mock gulp', (done) ->
fs = createFS
src:
coffee:
'sample.coffee': """
console.log 'Hello world'
... |
Speed up test suite more | describe "Welcome", ->
editor = null
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage("welcome")
waitsFor ->
editor = atom.workspace.getActiveTextEditor()
describe "when activated for the first time", ->
it "shows the welcome buffer", ->
expect(editor.getText()).toMat... | describe "Welcome", ->
editor = null
beforeEach ->
spyOn(atom.workspace, 'open').andCallThrough()
waitsForPromise ->
atom.packages.activatePackage("welcome")
waitsFor ->
editor = atom.workspace.getActiveTextEditor()
describe "when activated for the first time", ->
it "shows the wel... |
Fix issue of initial placement of items | Crafty.c 'ViewportRelativeMotion',
init: ->
remove: ->
viewportRelativeMotion: ({ x, y, speed }) ->
@_startLocation = { x, y }
@_speed = speed
@_initialViewport =
x: (Crafty.viewport.width / 4)
@_location =
sx: x + ((x - @_initialViewport.x) * (@_speed - 1))
sy: y
dx: @dx... | Crafty.c 'ViewportRelativeMotion',
init: ->
remove: ->
viewportRelativeMotion: ({ x, y, speed }) ->
@_startLocation = { x, y }
@_speed = speed
@_initialViewport =
x: (Crafty.viewport.width / 4)
@_location =
sx: x + ((x - @_initialViewport.x) * (@_speed - 1))
sy: y
dx: @dx... |
Add node version to version command output | packageJSON = require('../../package.json')
exports.version =
signature: 'version'
description: 'output the version number'
action: ->
console.log(packageJSON.version)
| packageJSON = require('../../package.json')
exports.version =
signature: 'version'
description: 'output the version number'
action: ->
console.log("#{packageJSON.name}: #{packageJSON.version}")
console.log("node: #{process.version}")
|
Configure sass to use libsass | exports.config =
# See http://brunch.readthedocs.org/en/latest/config.html for documentation.
paths:
public: 'public'
files:
javascripts:
joinTo:
'js/app.js': /^app/
stylesheets:
joinTo:
'ss/app.css': /^app\/styles/
| exports.config =
# See http://brunch.readthedocs.org/en/latest/config.html for documentation.
paths:
public: 'public'
files:
javascripts:
joinTo:
'js/app.js': /^app/
stylesheets:
joinTo:
'ss/app.css': /^app\/styles/
plugins:
sass:
mode: 'native'
|
Add wsClient listener by default in browser. More robust way to enable chalk in browser | ###
| Storyboard
| (c) Guillermo Grau Panea 2016
| License: MIT
###
k = require './constants'
# Enable chalk colors in the browser (we'll handle the conversion)
if k.IS_BROWSER
process.env.COLORTERM = true
hub = require './hub'
stories = require './stories'
consoleListener = require './listeners/console'
mainStory... | ###
| Storyboard
| (c) Guillermo Grau Panea 2016
| License: MIT
###
k = require './constants'
# Chalk is disabled by default in the browser. Override
# this default (we'll handle ANSI code conversion ourselves
# when needed)
chalk = require 'chalk'
chalk.enabled = true
mainStory = require './stories'
hub = require '.... |
Add info to compiled summon file about editing/commiting it. | module.exports = (grunt) ->
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-chmod'
grunt.initConfig
meta:
shebang: '#!/usr/bin/env node'
coffee:
default:
options:
bare: true
files:
'summon': '... | module.exports = (grunt) ->
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-chmod'
grunt.initConfig
meta:
shebang: '#!/usr/bin/env node'
hacking: """
// Please don't edit this file directly. It is compiled from the CoffeeScri... |
Create "dev" grunt task and set "default" as alias | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
meta:
banner: '/*! <%= pkg.name %> <%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> | <%= pkg.license %> License */\n'
coffee:
compile:
... | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
meta:
banner: '/*! <%= pkg.name %> <%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> | <%= pkg.license %> License */\n'
coffee:
compile:
... |
Set also placeholder when adding a fact relation | class window.FactRelation extends Backbone.Model
defaults:
evidence_type: 'FactRelation'
setOpinion: (type) ->
$.ajax
url: @url() + "/opinion/" + type
success: (data) =>
mp_track "Evidence: opinionate",
type: type
evidence_id: @id
@set data
type: "po... | class window.FactRelation extends Backbone.Model
defaults:
evidence_type: 'FactRelation'
opinions:
formatted_relevance: "?"
setOpinion: (type) ->
$.ajax
url: @url() + "/opinion/" + type
success: (data) =>
mp_track "Evidence: opinionate",
type: type
evidenc... |
Return silently if no WebSockets support | reloadStylesheets = ->
queryString = '?reload=' + new Date().getTime()
el.href = el.href.replace(/\?.*|$/, queryString) for el in document.querySelectorAll('link[rel="stylesheet"]')
connect = (opts={}) ->
# if user is running mozilla then use it's built-in WebSocket
window.WebSocket ||= window.MozWebSocket
... | reloadStylesheets = ->
queryString = '?reload=' + new Date().getTime()
el.href = el.href.replace(/\?.*|$/, queryString) for el in document.querySelectorAll('link[rel="stylesheet"]')
connect = (opts={}) ->
# if user is running mozilla then use it's built-in WebSocket
WebSocket = window.WebSocket || window.MozWe... |
Revert "Revert "Add root node to POST contributions/"" | `// @ngInject`
angular.module('cobudget').config (RestangularProvider, config) ->
RestangularProvider.setBaseUrl(config.apiEndpoint)
RestangularProvider.setDefaultHttpFields
withCredentials: true
RestangularProvider.setDefaultHeaders
Accept: "application/json"
RestangularProvider.setResponseInterceptor... | `// @ngInject`
angular.module('cobudget').config (RestangularProvider, config) ->
RestangularProvider.setBaseUrl(config.apiEndpoint)
RestangularProvider.setDefaultHttpFields
withCredentials: true
RestangularProvider.setDefaultHeaders
Accept: "application/json"
RestangularProvider.setResponseInterceptor... |
Remove unused local var in event stream actions | ETahi.EventStreamActions = {
created: (esData) ->
Ember.run =>
if esData.task
phaseId = esData.task.phase_id
taskId = esData.task.id
@store.pushPayload('task', esData)
task = @store.findTask(taskId)
phase = @store.getById('phase', phaseId)
phase.get('tasks').a... | ETahi.EventStreamActions = {
created: (esData) ->
Ember.run =>
if esData.task
phaseId = esData.task.phase_id
taskId = esData.task.id
@store.pushPayload('task', esData)
task = @store.findTask(taskId)
phase = @store.getById('phase', phaseId)
phase.get('tasks').a... |
Include only nodes being part of ways | require('./styles/index.scss')
require('leaflet/dist/leaflet.css')
require('leaflet')
findClosestTo = (origin, parsed) ->
minDistance = 1000
found = null
for element in parsed.elements
elemLatLng = new L.LatLng(element.lat, element.lon)
if origin.distanceTo(elemLatLng) < minDistance
found = elemLa... | require('./styles/index.scss')
require('leaflet/dist/leaflet.css')
require('leaflet')
overpass_query = (latlng) ->
lat = latlng.lat
lng = latlng.lng
"""
[out:json];
way(around:100,#{lat},#{lng})->.ways;
node(around:100,#{lat},#{lng})->.nodes;
.ways >->.way_nodes;
node.nodes.way_nodes;
out;
"""
fi... |
Fix broken media view when not logged in | angular.module 'module.media', [
'restangular'
'ui.router'
'service.auth'
'service.overlay'
'module.common'
]
.config [
'$stateProvider',
($stateProvider) ->
$stateProvider
.state 'media',
url: '/m/:hash'
templateUrl: 'modules/media/media.tpl.html'
... | angular.module 'module.media', [
'restangular'
'ui.router'
'service.auth'
'service.overlay'
'module.common'
]
.config [
'$stateProvider',
($stateProvider) ->
$stateProvider
.state 'media',
url: '/m/:hash'
templateUrl: 'modules/media/media.tpl.html'
... |
Remove obsolete module require statement | kd = require 'kd'
globals = require 'globals'
isLoggedIn = require './isLoggedIn'
trackEligible = ->
return analytics? and globals.config.logToExternal
# Access control wrapper around segmentio object.
module.exports = exports = (args...) ->
return unless trackEligible()
# send event#action as event for GA
... | globals = require 'globals'
isLoggedIn = require './isLoggedIn'
trackEligible = ->
return analytics? and globals.config.logToExternal
# Access control wrapper around segmentio object.
module.exports = exports = (args...) ->
return unless trackEligible()
# send event#action as event for GA
if args.length >... |
Document baseURL and set it for tasks | settings =
# # set/comment in to use actual BE
# baseUrl: 'http://localhost:3001'
endpoints:
'exercise.*.send.save':
url: 'api/steps/{id}'
method: 'PATCH'
completedEvent: 'exercise.{id}.receive.save'
'exercise.*.send.complete':
url: 'api/steps/{id}/completed'
method: 'PUT'
... | settings =
# to customize, set environmental var BASE_URL when building or running webpack-dev-server
# Currently is set on an endpoint by endpoint basis until all are implemented by BE
# baseUrl: process?.env?.BASE_URL
endpoints:
'exercise.*.send.save':
url: 'api/steps/{id}'
method: 'PATCH'
... |
Support for optional number of arguments. |
async = require 'async'
{Boutique} = require './lib/boutique'
{serializers} = require './lib/serializers'
{selectFormat} = require './lib/formatselection'
formats =
'application/json':
lib: require './lib/formats/json'
serialize: serializers.json
represent = (ast, contentType, options, cb) ->
key = se... |
async = require 'async'
{Boutique} = require './lib/boutique'
{serializers} = require './lib/serializers'
{selectFormat} = require './lib/formatselection'
formats =
'application/json':
lib: require './lib/formats/json'
serialize: serializers.json
represent = (ast, contentType, options, cb) ->
if typeo... |
Use regex lookahead to sort out the issue with breaking words. | Cloudsdale.MessageController = Ember.Controller.extend
content: null
text: ( () ->
text = @content.get('content') || ""
text = text.replace(/\s/g, ' ')
text = text.replace(/(\\r\\n|\\n|\\r)/g, '<br/>')
return text
).property('content.content')
avatar: ( () ->
@content.get('author').g... | Cloudsdale.MessageController = Ember.Controller.extend
content: null
text: ( () ->
text = @content.get('content') || ""
text = text.replace(/\s(?=\s)/g, ' ')
text = text.replace(/(\\r\\n|\\n|\\r)/g, '<br/>')
return text
).property('content.content')
avatar: ( () ->
@content.get('auth... |
Remove call to setACL method when survey is activated | ###
Toggles the activation state of a survey based on the 'active' ReactiveVar
on the instance
@param [Object] instance, Blaze instance
###
activate = (instance) ->
activeState = instance.active
activeState.set not activeState.get()
props =
active: activeState.get()
instance.data.survey.save(props)
... | ###
Toggles the activation state of a survey based on the 'active' ReactiveVar
on the instance
@param [Object] instance, Blaze instance
###
activate = (instance) ->
activeState = instance.active
activeState.set not activeState.get()
props =
active: activeState.get()
instance.activating.set true
inst... |
Improve Table of Contents nested list handling | # *************************************
#
# Application
# -> Compendium
#
# *************************************
# -------------------------------------
# Vendor
# -------------------------------------
#= require jquery
#= require jquery.tokeninput
#= require jquery_ujs
#= require moment
# -------------------... | # *************************************
#
# Application
# -> Compendium
#
# *************************************
# -------------------------------------
# Vendor
# -------------------------------------
#= require jquery
#= require jquery.tokeninput
#= require jquery_ujs
#= require moment
# -------------------... |
Delete data.type once it's used to transform batch data | # # Kissmetrics Batch
class BatchKissmetricsClient
@HOST: 'api.kissmetrics.com'
constructor: (@queue) ->
@_validate_queue @queue
add: (timestamp, data) ->
data.timestamp = timestamp
@_transformData data
@queue.add data
get: ->
@queue.get()
process: ->
queue = @get()
_transform... | # # Kissmetrics Batch
class BatchKissmetricsClient
@HOST: 'api.kissmetrics.com'
constructor: (@queue) ->
@_validate_queue @queue
add: (timestamp, data) ->
data.timestamp = timestamp
@_transformData data
@queue.add data
get: ->
@queue.get()
process: ->
queue = @get()
_transform... |
Add back Atom `pane-layout-plus` package | packages: [
"atom-beautify"
"atomic-chrome"
"close-tags"
"date"
"file-icons"
"git-history"
"git-plus"
"git-time-machine"
"language-eco"
"language-elixir"
"language-haml"
"language-rspec"
"linter"
"linter-write-good"
"merge-conflicts"
"package-sync"
"rails-snippets"
"rails-transporter... | packages: [
"atom-beautify"
"atomic-chrome"
"close-tags"
"date"
"file-icons"
"git-history"
"git-plus"
"git-time-machine"
"language-eco"
"language-elixir"
"language-haml"
"language-rspec"
"linter"
"linter-write-good"
"merge-conflicts"
"package-sync"
"pane-layout-plus"
"rails-snippets"... |
Update statistics when model changes | class window.UserStatisticsView extends Backbone.Marionette.ItemView
className: 'statistics'
template: 'users/statistics'
| class window.UserStatisticsView extends Backbone.Marionette.ItemView
className: 'statistics'
template: 'users/statistics'
initialize: ->
@listenTo @model, 'change', @render
|
Add tabindex attr to table rows after table is loaded | Template.reactiveTable.onRendered ->
if @data.settings.keyboardFocus
attrs = tabindex: '0'
@$('tbody > tr').attr(attrs)
Template.reactiveTable.events
'click tbody > tr': (event, instance) ->
instance.$(event.currentTarget).blur()
| Template.reactiveTable.onRendered ->
if @data.settings.keyboardFocus
@autorun =>
if @context.ready.get()
Meteor.defer =>
@$('tbody > tr').attr(tabindex: '0')
Template.reactiveTable.events
'click tbody > tr': (event, instance) ->
instance.$(event.currentTarget).blur()
|
Change /invite to use addUserToRoom instead joinRoom | ###
# Invite is a named function that will replace /invite commands
# @param {Object} message - The message object
###
class Invite
constructor: (command, params, item) ->
if command isnt 'invite' or not Match.test params, String
return
username = params.trim()
if username is ''
return
username = user... | ###
# Invite is a named function that will replace /invite commands
# @param {Object} message - The message object
###
class Invite
constructor: (command, params, item) ->
if command isnt 'invite' or not Match.test params, String
return
username = params.trim()
if username is ''
return
username = user... |
Replace deep-pluck with keyfinder module |
_ = require 'lodash'
request = require 'request'
deepPluck = require 'deep-pluck'
isError = (errorCode) ->
if errorCode? and errorCode.toString() isnt '0' then true else false
createErrorMsg = (body, codeKey, msgKey) ->
[code, msg] = [deepPluck(body, codeKey)[0], deepPluck(body, msgKey)[0]]
if isError(co... |
_ = require 'lodash'
request = require 'request'
keyfinder = require 'keyfinder'
isError = (errorCode) ->
if errorCode? and errorCode.toString() isnt '0' then true else false
createErrorMsg = (body, codeKey, msgKey) ->
[code, msg] = [keyfinder(body, codeKey)[0], keyfinder(body, msgKey)[0]]
if isError... |
Add spine require to toolbox to make it pass tests on linux |
class Toolbox extends Spine.Controller
events:
'click .tool' : 'selection'
'click .remove-tools': 'clearDashboard'
constructor: ->
super
render: =>
@html require('views/toolbox')(@) if @el.html
clearDashboard: (e) =>
@trigger 'remove-all-tools'
selection: (e) =>
e.preventDef... | Spine = require 'spine'
class Toolbox extends Spine.Controller
events:
'click .tool' : 'selection'
'click .remove-tools': 'clearDashboard'
constructor: ->
super
render: =>
@html require('views/toolbox')(@) if @el.html
clearDashboard: (e) =>
@trigger 'remove-all-tools'
selection:... |
Reset command input on successful commands | angular.module("grumbles")
.controller "FormCtrl", ($http, Output) ->
@submit = ->
return unless @command
split_command = @command.split " "
verb = split_command[0]
entity = split_command[1]
other_entity = split_command[2]
path = "/#{verb}/#{entity}"
pat... | angular.module("grumbles")
.controller "FormCtrl", ($http, Output) ->
@submit = ->
return unless @command
split_command = @command.split " "
verb = split_command[0]
entity = split_command[1]
other_entity = split_command[2]
path = "/#{verb}/#{entity}"
pat... |
Set datepicker start weekday to Monday | $ ->
window.initPickers = ->
base_options =
format: "yyyy-mm-dd hh:ii"
autoclose: true
todayBtn: true
viewSelect: 'month'
minView: 'day'
language: I18n.locale
search_form_options = _.defaults({pickerPosition: "bottom-left datetimepicker-bottom-left-custom"}, base_options)
... | $ ->
window.initPickers = ->
base_options =
format: "yyyy-mm-dd hh:ii"
autoclose: true
todayBtn: true
viewSelect: 'month'
minView: 'day'
language: I18n.locale
weekStart: 1
search_form_options = _.defaults({pickerPosition: "bottom-left datetimepicker-bottom-left-custo... |
Implement a scrollbar width detector | FactlinkJailRoot.on 'modalOpened', ->
document.documentElement.setAttribute('data-factlink-suppress-scrolling', '')
FactlinkJailRoot.on 'modalClosed', -> document.documentElement.removeAttribute('data-factlink-suppress-scrolling')
| scrollbarWidth = 0
FactlinkJailRoot.loaded_promise.then ->
# Create the measurement nod; see http://davidwalsh.name/detect-scrollbar-width
scrollDiv = document.createElement("div");
$(scrollDiv).css(
width: "100px"
height: "100px"
overflow: "scroll"
position: "absolute"
top: "-9999px"
)
do... |
Add dev reset storage button. | goog.provide 'app.react.pages.Home'
class app.react.pages.Home
###*
@param {app.Routes} routes
@param {app.songs.Store} songsStore
@param {app.react.Touch} touch
@constructor
###
constructor: (routes, songsStore, touch) ->
{div,ul,li} = React.DOM
{a} = touch.scroll 'a'
@create = Rea... | goog.provide 'app.react.pages.Home'
class app.react.pages.Home
###*
@param {app.Routes} routes
@param {app.songs.Store} songsStore
@param {app.react.Touch} touch
@constructor
###
constructor: (routes, songsStore, touch) ->
{div,ul,li,br} = React.DOM
{a,button} = touch.scroll 'a', 'button... |
Update project paths for File-Icons | [
{
title: ".atom"
icon: "atom-icon"
paths: [
"~/.atom"
]
devMode: true
}
{
title: ".files"
icon: "terminal-icon"
paths: [
"~/.files"
]
devMode: true
}
{
title: "language-roff"
icon: "manpage-icon"
paths: [
"~/Labs/language-roff"
]
devMode: true
}
{
title: "file-icons"
... | [
{
title: ".atom"
icon: "atom-icon"
paths: [
"~/.atom"
]
devMode: true
}
{
title: ".files"
icon: "terminal-icon"
paths: [
"~/.files"
]
devMode: true
}
{
title: "language-roff"
icon: "manpage-icon"
paths: [
"~/Labs/language-roff"
]
devMode: true
}
{
title: "file-icons"
... |
Use query string to select game | #
# main.coffee
#
# Role: start the app
#
# Responsibility:
# * load top-level modules
# * initalize game based on query string
# * render and append to body of HTML
# * run tests if local
#
# Preamble
# TODO: server-side include underscore, underscore.string, jquery
{my} = require './my'
sys = require 'sys'
if not ... | #
# main.coffee
#
# Role: start the app
#
# Responsibility:
# * load top-level modules
# * initalize game based on query string
# * render and append to body of HTML
# * run tests if local
#
# Preamble
# TODO: server-side include underscore, underscore.string, jquery
{my} = require './my'
sys = require 'sys'
queryStr... |
Remove access for pingdom for normal sys info call | "use strict"
os = require 'os'
exports.info = (req, res, next) ->
return res.status(403).end() if req.usr not in ['DNT', 'Pingdom']
res.json 200,
app:
uptime: process.uptime()
memory: process.memoryUsage()
os:
uptime: os.uptime()
loadavg: os.loadavg()
totalmem: os.totalmem()... | "use strict"
os = require 'os'
exports.info = (req, res, next) ->
return res.status(403).end() if req.usr isnt 'DNT'
res.json 200,
app:
uptime: process.uptime()
memory: process.memoryUsage()
os:
uptime: os.uptime()
loadavg: os.loadavg()
totalmem: os.totalmem()
freemem:... |
Add make-runner package to Atom | "*":
editor:
showIndentGuide: true
fontFamily: "Inconsolata"
invisibles: {}
scrollPastEnd: true
softWrap: true
softWrapAtPreferredLineLength: true
preferredLineLength: 100
core:
ignoredNames: [
".bundle"
".git"
"log"
"repositories"
"tmp"
"vendor"
... | "*":
editor:
showIndentGuide: true
fontFamily: "Inconsolata"
invisibles: {}
scrollPastEnd: true
softWrap: true
softWrapAtPreferredLineLength: true
preferredLineLength: 100
core:
ignoredNames: [
".bundle"
".git"
"log"
"repositories"
"tmp"
"vendor"
... |
Move created record to the top of the stack | Base = require './base.coffee'
Backbone = require 'backbone'
Backbone.LocalStorage = require 'backbone.localstorage'
Block = require '../models/block.coffee'
module.exports = class RecentConnections extends Backbone.Collection
model: Block
localStorage: new Backbone.LocalStorage RecentConnections
shove: (model... | Base = require './base.coffee'
Backbone = require 'backbone'
Backbone.LocalStorage = require 'backbone.localstorage'
Block = require '../models/block.coffee'
module.exports = class RecentConnections extends Backbone.Collection
model: Block
localStorage: new Backbone.LocalStorage RecentConnections
shove: (model... |
Check that legIndex isn't empty. | define ['backbone', 'utils', 'backboneAnalytics'], (Backbone, Utils) ->
Backbone.Router.extend
initialize: () ->
@route '', 'homeView'
@route /([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?(?:\/([^\/]+))?\/?/, 'routesView'
homeView: () =>
Reitti.Event.trigger 'home'
r... | define ['backbone', 'utils', 'backboneAnalytics'], (Backbone, Utils) ->
Backbone.Router.extend
initialize: () ->
@route '', 'homeView'
@route /([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?(?:\/([^\/]+))?\/?/, 'routesView'
homeView: () =>
Reitti.Event.trigger 'home'
r... |
Tweak test command for Windows | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
coffee:
glob_to_multiple:
expand: true
cwd: 'src'
src: ['*.coffee']
dest: 'lib'
ext: '.js'
coffeelint:
options:
max_line_length:
level: 'ignore'
... | module.exports = (grunt) ->
grunt.initConfig
pkg: grunt.file.readJSON('package.json')
coffee:
glob_to_multiple:
expand: true
cwd: 'src'
src: ['*.coffee']
dest: 'lib'
ext: '.js'
coffeelint:
options:
max_line_length:
level: 'ignore'
... |
Fix conflicto con alt + cursor | # Hay que bindear tanto cuando se carga la página como cuando turbolinks la
# pide (el page:change)
bindearTodo = ->
# mejora el estilo default de los file uploaders
$("form.carta :file").filestyle(
buttonText: 'Subir',
classText: 'span9 filestyle',
classButton: 'span3 filestyle'
)
$(document)
.on ... | # Hay que bindear tanto cuando se carga la página como cuando turbolinks la
# pide (el page:change)
bindearTodo = ->
# mejora el estilo default de los file uploaders
$("form.carta :file").filestyle(
buttonText: 'Subir',
classText: 'span9 filestyle',
classButton: 'span3 filestyle'
)
$(document)
.on ... |
Make the stepped animation finish closer together | # 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/
roundUpBy = (value, round_to) ->
return round_to * Math.ceil(value / round_to)
$ ->
animateMetric = $("... | # 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/
roundUpBy = (value, round_to) ->
return round_to * Math.ceil(value / round_to)
$ ->
animateMetric = $("... |
Declare options for --help usage. | fs = require 'fs'
path = require 'path'
yeoman = require 'yeoman-generator'
semver = require 'semver'
module.exports = class SlideGenerator extends yeoman.generators.NamedBase
files: ->
appPath = process.cwd()
fullPath = path.join appPath, '/slides/list.json'
list = require fullPath
... | fs = require 'fs'
path = require 'path'
yeoman = require 'yeoman-generator'
semver = require 'semver'
module.exports = class SlideGenerator extends yeoman.generators.NamedBase
constructor: (args, options, config) ->
super args, options, config
@option 'notes',
desc: 'Include speaker not... |
Fix deprecated selectors in keymap | '.platform-darwin .editor':
'ctrl-shift-u': 'encoding-selector:show'
'.platform-win32 .editor':
'ctrl-shift-u': 'encoding-selector:show'
'.platform-linux .editor':
'ctrl-u': 'encoding-selector:show'
| '.platform-darwin atom-text-editor':
'ctrl-shift-u': 'encoding-selector:show'
'.platform-win32 atom-text-editor':
'ctrl-shift-u': 'encoding-selector:show'
'.platform-linux atom-text-editor':
'ctrl-u': 'encoding-selector:show'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.