Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Set cache headers for statics | express = require 'express'
compress = require 'compression'
hbs = require 'hbs'
config = require '../config'
passport = require '../lib/auth'
User = require '../models/user'
module.exports = app = express()
hbs.registerHelper 'json', (context) ->
new hbs.handlebars.SafeString JSON.stringify(context)
app.set 'vie... | express = require 'express'
compress = require 'compression'
hbs = require 'hbs'
config = require '../config'
passport = require '../lib/auth'
User = require '../models/user'
module.exports = app = express()
hbs.registerHelper 'json', (context) ->
new hbs.handlebars.SafeString JSON.stringify(context)
app.set 'vie... |
Fix JS translations not be object but string | @RailsAdmin ||= {}
@RailsAdmin.I18n = class Locale
@init: (@locale, @translations)->
moment.locale(@locale)
@t:(key) ->
humanize = key.charAt(0).toUpperCase() + key.replace(/_/g, " ").slice(1)
@translations[key] || humanize
| @RailsAdmin ||= {}
@RailsAdmin.I18n = class Locale
@init: (@locale, @translations)->
moment.locale(@locale)
if typeof(@translations) == "string"
@translations = JSON.parse(@translations)
@t:(key) ->
humanize = key.charAt(0).toUpperCase() + key.replace(/_/g, " ").slice(1)
@translations[key] ||... |
Add initial createdAt date when saving comment. | ETahi.MessageOverlayController = ETahi.TaskController.extend ETahi.ControllerParticipants,
newCommentBody: ""
message: true
_clearNewMessage: ->
@set('newCommentBody', "")
commentSort: ['createdAt:asc']
sortedComments: Ember.computed.sort('comments', 'commentSort')
actions:
clearMessageContent: ... | ETahi.MessageOverlayController = ETahi.TaskController.extend ETahi.ControllerParticipants,
newCommentBody: ""
message: true
_clearNewMessage: ->
@set('newCommentBody', "")
commentSort: ['createdAt:asc']
sortedComments: Ember.computed.sort('comments', 'commentSort')
actions:
clearMessageContent: ... |
Reorganize specs by public method. | describe 'HashParams', ->
describe 'given foreground and background', ->
params = null
beforeEach ->
params = new HashParams(
new HashParams.scalar('foreground'),
new HashParams.scalar('background'))
it 'initializes values.foreground and .backgroun... | describe 'HashParams', ->
describe 'initial state', ->
describe 'given foreground and background', ->
params = null
beforeEach ->
params = new HashParams(
new HashParams.scalar('foreground'),
new HashParams.scalar('background'))... |
Fix require in binary test for coffeescript | Binary = require('./example');
describe 'binary', ->
it '1 is decimal 1', ->
expect(1).toEqual new Binary('1').toDecimal()
xit '10 is decimal 2', ->
expect(2).toEqual new Binary('10').toDecimal()
xit '11 is decimal 3', ->
expect(3).toEqual new Binary('11').toDecimal()
xit '100 is decimal 4', ->... | Binary = require('./binary');
describe 'binary', ->
it '1 is decimal 1', ->
expect(1).toEqual new Binary('1').toDecimal()
xit '10 is decimal 2', ->
expect(2).toEqual new Binary('10').toDecimal()
xit '11 is decimal 3', ->
expect(3).toEqual new Binary('11').toDecimal()
xit '100 is decimal 4', ->
... |
Add wait time for scrolling to annotations on hover | Template.incidentTable.events
'mouseover .incident-table tbody tr': (event, instance) ->
if not instance.data.scrollToAnnotations
return
$annotation = $("span[data-incident-id=#{@_id}]")
$("span[data-incident-id]").removeClass('viewing')
appHeaderHeight = $('header nav.navbar').outerHeight()
... | SCROLL_WAIT_TIME = 500
Template.incidentTable.onCreated ->
@scrollToAnnotation = (id) =>
intervalTime = 0
@interval = setInterval =>
if intervalTime >= SCROLL_WAIT_TIME
@stopScrollingInterval()
$annotation = $("span[data-incident-id=#{id}]")
$("span[data-incident-id]").removeCla... |
Throw error if format option is not string |
_ = require 'lodash'
typeOf = require 'type-of'
err = require './errors'
{ availableKeys, availableFormats } = require './api_config'
RealtimeInformation = require './services/realtime'
LocationLookup = require './services/location'
TripPlanner = require './services/trip'
TrafficSituation ... |
_ = require 'lodash'
typeOf = require 'type-of'
err = require './errors'
{ availableKeys, availableFormats } = require './api_config'
RealtimeInformation = require './services/realtime'
LocationLookup = require './services/location'
TripPlanner = require './services/trip'
TrafficSituation ... |
Remove invariant check for callbacks on controlled components | # react-controllables
# ===================
invariant = require 'react/lib/invariant'
getControllableValue = (name, state, props) -> props[name] ? state[name]
capFirst = (str) -> "#{ str[...1].toUpperCase() }#{ str[1...] }"
callbackName = (prop) -> "on#{ capFirst prop }Change"
ControllablesMixin =
getInitialStat... | # react-controllables
# ===================
invariant = require 'react/lib/invariant'
getControllableValue = (name, state, props) -> props[name] ? state[name]
capFirst = (str) -> "#{ str[...1].toUpperCase() }#{ str[1...] }"
callbackName = (prop) -> "on#{ capFirst prop }Change"
ControllablesMixin =
getInitialStat... |
Modify dialogs when waiting for secure screen validation | class @WalletSendPreparingDialogViewController extends @DialogViewController
view:
spinnerContainer: '#spinner_container'
onAfterRender: ->
super
@view.spinner = ledger.spinners.createLargeSpinner(@view.spinnerContainer[0])
account = Account.find(index: 0).first()
# fetch amount
ledger.wa... | class @WalletSendPreparingDialogViewController extends @DialogViewController
view:
spinnerContainer: '#spinner_container'
onAfterRender: ->
super
@view.spinner = ledger.spinners.createLargeSpinner(@view.spinnerContainer[0])
account = Account.find(index: 0).first()
# fetch amount
ledger.wa... |
Add the same test for Linter validation. | Helpers = require '../lib/helpers'
describe "The Results Validation Helper", ->
it "should throw an exception when nothing is passed.", ->
expect( -> Helpers.validateResults()).toThrow()
it "should throw an exception when a String is passed.", ->
expect( -> Helpers.validateResults('String')).toThrow()
| Helpers = require '../lib/helpers'
describe "The Results Validation Helper", ->
it "should throw an exception when nothing is passed.", ->
expect( -> Helpers.validateResults()).toThrow()
it "should throw an exception when a String is passed.", ->
expect( -> Helpers.validateResults('String')).toThrow()
des... |
Add alive ivar to light Model | Grim = require 'grim'
if Grim.includeDeprecations
module.exports = require('theorist').Model
return
PropertyAccessors = require 'property-accessors'
nextInstanceId = 1
module.exports =
class Model
PropertyAccessors.includeInto(this)
@resetNextInstanceId: -> nextInstanceId = 1
constructor: (params) ->
... | Grim = require 'grim'
if Grim.includeDeprecations
module.exports = require('theorist').Model
return
PropertyAccessors = require 'property-accessors'
nextInstanceId = 1
module.exports =
class Model
PropertyAccessors.includeInto(this)
@resetNextInstanceId: -> nextInstanceId = 1
alive: true
constructor: ... |
Use new bulk spell-checking method in task handler | SpellChecker = require 'spellchecker'
wordRegex = /(?:^|[\s\[\]"'])([a-zA-Z]+([a-zA-Z']+[a-zA-Z])?)(?=[\s\.\[\]:,"']|$)/g
module.exports = ({id, text}) ->
row = 0
misspellings = []
for line in text.split('\n')
while matches = wordRegex.exec(line)
word = matches[1]
continue if word in ['GitHub', ... | SpellChecker = require 'spellchecker'
module.exports = ({id, text}) ->
misspelledCharacterRanges = SpellChecker.checkSpelling(text)
row = 0
rangeIndex = 0
characterIndex = 0
misspellings = []
while characterIndex < text.length and rangeIndex < misspelledCharacterRanges.length
lineBreakIndex = text.ind... |
Refactor of most of the math library pulling components out | # a number of jasmine-jquery helpers / extensions
# it totally used to do this natively, but now doesn't...
jasmine.getFixtures().findContainer = ->
$(document.body).find("##{@containerId}")
jasmine.getFixtures().getContainer = ->
cont = @findContainer()
if cont.length == 0
@createContainer_("")
cont = ... | # a number of jasmine-jquery helpers / extensions
# it totally used to do this natively, but now doesn't...
jasmine.getFixtures().findContainer = ->
$(document.body).find("##{@containerId}")
jasmine.getFixtures().getContainer = ->
cont = @findContainer()
if cont.length == 0
@createContainer_("")
cont = ... |
Clear undo stack of the demo after creation |
module.exports =
config:
undefinedDisplay:
type: 'string'
default: ''
activate: (state) ->
atom.workspaceView.command 'table-edit:demo', => @openDemo()
@openDemo()
deactivate: ->
serialize: ->
openDemo: ->
Table = require './table'
TableView = require './table-view'
... |
module.exports =
config:
undefinedDisplay:
type: 'string'
default: ''
activate: (state) ->
atom.workspaceView.command 'table-edit:demo', => @openDemo()
@openDemo()
deactivate: ->
serialize: ->
openDemo: ->
Table = require './table'
TableView = require './table-view'
... |
Update language select class name | define (require) ->
settings = require('settings')
FooterTabView = require('cs!../inherits/tab/tab')
template = require('hbs!./metadata-template')
require('less!./metadata')
return class MetadataView extends FooterTabView
template: template
templateHelpers: () ->
model = super()
model.lan... | define (require) ->
settings = require('settings')
FooterTabView = require('cs!../inherits/tab/tab')
template = require('hbs!./metadata-template')
require('less!./metadata')
return class MetadataView extends FooterTabView
template: template
templateHelpers: () ->
model = super()
model.lan... |
Handle the error when the coverage report is not generated | {Range} = require 'atom'
_ = require 'underscore-plus'
fs = require 'fs-plus'
module.exports =
class GocovParser
constructor: (dispatch) ->
@dispatch = dispatch
setDataFile: (file) ->
@dataFile = file
# TODO disgusting - fix this parsing, regex
rangesForFile: (file) ->
# TODO Ensure we have a dat... | {Range} = require 'atom'
_ = require 'underscore-plus'
fs = require 'fs-plus'
module.exports =
class GocovParser
constructor: (dispatch) ->
@dispatch = dispatch
setDataFile: (file) ->
@dataFile = file
# TODO disgusting - fix this parsing, regex
rangesForFile: (file) ->
try
data = fs.readFil... |
Disable hawk auth for now | express = require 'express'
passport = require 'passport'
_ = require 'underscore'
authentication = require './authentication'
info = require './package'
http = require 'http'
require 'express-namespace'
users = require './routes/users'
projects = require './routes/projects'
time_entries = require './routes/time_entr... | express = require 'express'
passport = require 'passport'
_ = require 'underscore'
authentication = require './authentication'
info = require './package'
http = require 'http'
require 'express-namespace'
users = require './routes/users'
projects = require './routes/projects'
time_entries = require './routes/time_entr... |
Use color 0 as default fg color | class AsciiIo.Brush
@cache: {}
@clearCache: ->
@cache = {}
@hash: (brush) ->
"#{brush.fg}_#{brush.bg}_#{brush.bright}_#{brush.underline}_#{brush.italic}_#{brush.blink}"
@create: (options = {}) ->
key = @hash(options)
brush = @cache[key]
if not brush
brush = new AsciiIo.Brush(option... | class AsciiIo.Brush
@cache: {}
@clearCache: ->
@cache = {}
@hash: (brush) ->
"#{brush.fg}_#{brush.bg}_#{brush.bright}_#{brush.underline}_#{brush.italic}_#{brush.blink}"
@create: (options = {}) ->
key = @hash(options)
brush = @cache[key]
if not brush
brush = new AsciiIo.Brush(option... |
Use $http for file upload | @app.factory 'fileUpload', [
'$q', '$rootScope', '$http', 'formData',
($q, $rootScope, $http, formData) ->
fileUpload = (options) ->
xhr = null
deferred = $q.defer()
lastProgressApply = 0
progressHandler = (event) ->
return unless event.lengthComputable
now = Date... | @app.factory 'fileUpload', [
'$q', '$rootScope', '$http', 'formData',
($q, $rootScope, $http, formData) ->
(options) ->
deferred = $q.defer()
timeout = $q.defer()
options.method ?= options.type ? 'POST'
options.data = formData.build(options.data)
options.headers ?= {}
... |
Change default value for validateOnSave | validator = require "./validator"
module.exports = HtmlValidation =
config:
validateOnSave:
type: "boolean"
default: no
title: "Validate on save"
description: "Make a validation each time you save an HTML file."
validateOnChange:
type: "bo... | validator = require "./validator"
module.exports = HtmlValidation =
config:
validateOnSave:
type: "boolean"
default: yes
title: "Validate on save"
description: "Make a validation each time you save an HTML file."
validateOnChange:
type: "b... |
Adjust row counter to also work with bigger chunks. | _ = require 'underscore'
__ = require 'highland'
fs = require 'fs'
csv = require 'csv'
transform = require 'stream-transform'
ImportMapping = require './importmapping'
Streaming = require '../streaming'
Promise = require 'bluebird'
class Importer
constructor: (@logger, options = {}) ->
@streaming = new Streamin... | _ = require 'underscore'
__ = require 'highland'
fs = require 'fs'
csv = require 'csv'
transform = require 'stream-transform'
ImportMapping = require './importmapping'
Streaming = require '../streaming'
Promise = require 'bluebird'
class Importer
constructor: (@logger, options = {}) ->
@streaming = new Streamin... |
Add selector generation to Product Component | class ProductComponent
bindProductEvent: (name, handler, productIdIndex = 0) =>
$(window).on name, (evt, args...) =>
return unless @productId is args[productIdIndex]
handler(evt, args...)
root = window || exports
root.ProductComponent = ProductComponent | class ProductComponent
bindProductEvent: (name, handler, productIdIndex = 0) =>
$(window).on name, (evt, args...) =>
return unless @productId is args[productIdIndex]
handler(evt, args...)
generateSelectors: (selectors) =>
for k, v of selectors
@["find#{k}"] = do(v) => => @element.find(v)
@["show#{k}"... |
Comment imports for broken backend libs on Travis | ---
---
dl = require('datalib')
evalexpr = require('expr-eval')
{% include coffee/essential.coffee %}
{% include coffee/main.coffee %}
{% include coffee/vega_extra.coffee %}
{% include coffee/simulation.coffee %}
{% include coffee/uploads.coffee %}
{% include coffee/benchmark_table.coffee %}
{% include coffee/result_... | ---
---
# dl = require('datalib')
# evalexpr = require('expr-eval')
{% include coffee/essential.coffee %}
{% include coffee/main.coffee %}
{% include coffee/vega_extra.coffee %}
{% include coffee/simulation.coffee %}
{% include coffee/uploads.coffee %}
{% include coffee/benchmark_table.coffee %}
{% include coffee/res... |
Add three more pending tests. | describe 'Pending', ->
it 'Should test skipHeader option'
it 'Should test initWith option'
it 'Should embed plain JS files'
it 'Should allow setting the source path'
| describe 'Pending', ->
it 'Should test skipHeader option'
it 'Should test initWith option'
it 'Should embed plain JS files'
it 'Should allow setting the source path'
it 'Should allow setting the lib path'
it 'Should allow setting the tmp path'
it 'Should allow setting the out path'
|
Remove expected block comment from test | editorModule "Installation process", template: "editor_html"
editorTest "element.editorController", ->
ok getEditorController() instanceof Trix.EditorController
editorTest "creates a contenteditable element", ->
ok getDocumentElement()
editorTest "loads the initial document", ->
equal getDocumentElement().text... | editorModule "Installation process", template: "editor_html"
editorTest "element.editorController", ->
ok getEditorController() instanceof Trix.EditorController
editorTest "creates a contenteditable element", ->
ok getDocumentElement()
editorTest "loads the initial document", ->
equal getDocumentElement().text... |
Add tables to CKEditor toolbar | window.Tahi = {}
Tahi.papers =
init: ->
$('#add_author').on 'click', (e) ->
e.preventDefault()
$('<li class="author">').appendTo $('ul.authors')
$(document).ready ->
if $("[contenteditable]").length > 0
for elementId in ['body_editable', 'abstract_editable']
CKEDITOR.inline elementId,
... | window.Tahi = {}
Tahi.papers =
init: ->
$('#add_author').on 'click', (e) ->
e.preventDefault()
$('<li class="author">').appendTo $('ul.authors')
$(document).ready ->
if $("[contenteditable]").length > 0
for elementId in ['body_editable', 'abstract_editable']
CKEDITOR.inline elementId,
... |
Send e-mail on first username set | RocketChat.setUsername = (user, username) ->
username = s.trim username
if not user or not username
return false
if not /^[0-9a-zA-Z-_.]+$/.test username
return false
# User already has desired username, return
if user.username is username
return user
# Check username availability
unless RocketChat.chec... | RocketChat.setUsername = (user, username) ->
username = s.trim username
if not user or not username
return false
if not /^[0-9a-zA-Z-_.]+$/.test username
return false
# User already has desired username, return
if user.username is username
return user
# Check username availability
unless RocketChat.chec... |
Change to process.exit(1) to restart server | Meteor.methods
restart_server: ->
if not Meteor.userId()
throw new Meteor.Error 'invalid-user', "[methods] restart_server -> Invalid user"
unless RocketChat.authz.hasRole( Meteor.userId(), 'admin') is true
throw new Meteor.Error 'not-authorized', '[methods] restart_server -> Not authorized'
Meteor.setTim... | Meteor.methods
restart_server: ->
if not Meteor.userId()
throw new Meteor.Error 'invalid-user', "[methods] restart_server -> Invalid user"
unless RocketChat.authz.hasRole( Meteor.userId(), 'admin') is true
throw new Meteor.Error 'not-authorized', '[methods] restart_server -> Not authorized'
Meteor.setTim... |
Put versions in to generated attribute names, indent generated code | #!/usr/bin/env coffee
http = require 'http'
util = require 'util'
crypto = require 'crypto'
name = process.argv[2]
version = process.argv[3] ? "latest"
deps = []
hash = crypto.createHash 'sha256'
http.get "http://registry.npmjs.org/#{name}", (res) ->
res.setEncoding()
val = ""
res.on 'data', (chunk) ->
v... | #!/usr/bin/env coffee
http = require 'http'
util = require 'util'
crypto = require 'crypto'
name = process.argv[2]
version = process.argv[3] ? "latest"
deps = []
hash = crypto.createHash 'sha256'
http.get "http://registry.npmjs.org/#{name}", (res) ->
res.setEncoding()
val = ""
res.on 'data', (chunk) ->
v... |
Update status finder keybinding to meta-B | 'body':
'meta-t': 'fuzzy-finder:toggle-file-finder'
'meta-b': 'fuzzy-finder:toggle-buffer-finder'
'ctrl-.': 'fuzzy-finder:find-under-cursor'
'meta-T': 'fuzzy-finder:toggle-git-status-finder'
| 'body':
'meta-t': 'fuzzy-finder:toggle-file-finder'
'meta-b': 'fuzzy-finder:toggle-buffer-finder'
'ctrl-.': 'fuzzy-finder:find-under-cursor'
'meta-B': 'fuzzy-finder:toggle-git-status-finder'
|
Put notice on the left, on the right didn't *feel* right (pun intended). | FactlinkJailRoot.showProxyMessage = ->
content = """
<div class="proxy-message">
<strong>Factlink demo page</strong>
<ul>
<li>Get the <a href="https://factlink.com">extension</a> to add discussions on every site
<li>Or <a href="https://factlink.com/p/on-your-site">install</a> Factlink ... | FactlinkJailRoot.showProxyMessage = ->
content = """
<div class="proxy-message">
<strong>Factlink demo page</strong>
<ul>
<li>Get the <a href="https://factlink.com">extension</a> to add discussions on every site
<li>Or <a href="https://factlink.com/p/on-your-site">install</a> Factlink ... |
Add some more hashing functions | module.exports = class
@_addition: (a, b) -> (a + b)
@_multiplication: (a, b) -> (a * b)
@sum: (array) =>
array.reduce(@_addition, 0)
@product: (array) =>
array.reduce(@_multiplication, 0)
| module.exports = class
@_addition: (a, b) -> (a + b)
@_multiplication: (a, b) -> (a * b)
@sum: (array) =>
array.reduce(@_addition, 0)
@reverseSum: (array) =>
array.reverse().reduce(@_addition, 0)
@product: (array) =>
array.reduce(@_multiplication, 0)
@reverseProduct: (array) =>
array.rev... |
Use newBody for attaching portals | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div } from 'react-dom-factories'
import { nextVal } from 'utils/seq'
el = React.createElement
bn = 'noti... | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div } from 'react-dom-factories'
import { nextVal } from 'utils/seq'
el = React.createElement
bn = 'noti... |
Create divs for each section" | # Preamble
_.mixin(_.str.exports())
#rx = require('../../reactive-coffee/src/reactive')
rx = require 'reactive-coffee'
# Dependencies
{my} = require('./my')
{god} = require('./god')
{config} = require('./config')
{draw} = require('./draw')
{test} = require('./test') if my.test
world = god(rx, config)
main = ->
$... | # Preamble
_.mixin(_.str.exports())
#rx = require('../../reactive-coffee/src/reactive')
rx = require 'reactive-coffee'
# Dependencies
{my} = require('./my')
{god} = require('./god')
{config} = require('./config')
{draw} = require('./draw')
{test} = require('./test') if my.test
world = god(rx, config)
div = rx.rxt.... |
Fix forgotten renaming in spec | Lint = require '../lib/lint'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe 'Lint', ->
it 'MUST have specs :)'
| Lint = require '../lib/atom-lint'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe 'atom-lint', ->
it 'MUST have specs :)'
|
Update when impact changes and hide ones without impact | class TopFactEvidenceLayoutView extends Backbone.Marionette.Layout
template: 'evidence/top_fact_evidence_layout'
regions:
contentRegion: '.js-content-region'
templateHelpers:
type_css: ->
switch @type
when 'believe' then 'supporting'
when 'disbelieve' then 'weakening'
when ... | class TopFactEvidenceLayoutView extends Backbone.Marionette.Layout
template: 'evidence/top_fact_evidence_layout'
regions:
contentRegion: '.js-content-region'
templateHelpers:
type_css: ->
switch @type
when 'believe' then 'supporting'
when 'disbelieve' then 'weakening'
when ... |
Remove unused service dependency from assetDisplay | 'use strict'
app.directive 'assetDisplay', [
'constantService', '$timeout',
(constants, $timeout) ->
restrict: 'E'
templateUrl: 'asset/display.html'
scope:
assetFn: '&asset'
link: ($scope) ->
asset = $scope.assetFn()
$scope.asset = asset.inContext()
$scope.readable = $scope.... | 'use strict'
app.directive 'assetDisplay', [
'constantService',
(constants) ->
restrict: 'E'
templateUrl: 'asset/display.html'
scope:
assetFn: '&asset'
link: ($scope) ->
asset = $scope.assetFn()
$scope.asset = asset.inContext()
$scope.readable = $scope.asset.checkPermission(... |
Add defaults to File client model | Model = require 'lib/model'
module.exports = class Template extends Model
urlRoot: '/api/templates'
idAttribute: 'filename'
| Model = require 'lib/model'
module.exports = class Template extends Model
urlRoot: '/api/templates'
idAttribute: 'filename'
defaults:
filename: ''
contents: ''
|
Use _.remove to remove windows from atom.windows array | Keymap = require 'keymap'
$ = require 'jquery'
_ = require 'underscore'
module.exports =
class App
keymap: null
windows: null
tabText: null
constructor: (@loadPath, nativeMethods)->
@windows = []
@setUpKeymap()
@tabText = " "
setUpKeymap: ->
@keymap = new Keymap()
$(document).on 'keydo... | Keymap = require 'keymap'
$ = require 'jquery'
_ = require 'underscore'
require 'underscore-extensions'
module.exports =
class App
keymap: null
windows: null
tabText: null
constructor: (@loadPath, nativeMethods)->
@windows = []
@setUpKeymap()
@tabText = " "
setUpKeymap: ->
@keymap = new Ke... |
Store a global reference to File-Icons package | # I love this program.
#
# Atom will evaluate this file each time a new window is opened. It is run
# after packages are loaded/activated and after the previous editor state
# has been restored.
#
# An example hack to log to the console when each text editor is saved.
#
# atom.workspace.observeTextEditors (editor) ->
#... | # I love this program.
#
# Atom will evaluate this file each time a new window is opened. It is run
# after packages are loaded/activated and after the previous editor state
# has been restored.
#
# An example hack to log to the console when each text editor is saved.
#
# atom.workspace.observeTextEditors (editor) ->
#... |
Revert "adding in footer tests" | {expect} = require 'chai'
# For some reason, this navbar component test will have warnings about setting
# state when component is unmounted if it's after some of the other specs.
# The tests still run and progress just fine despite the warnings, but for now,
# I'm leaving this test here.
# TODO figure out why.
requir... | {expect} = require 'chai'
# For some reason, this navbar component test will have warnings about setting
# state when component is unmounted if it's after some of the other specs.
# The tests still run and progress just fine despite the warnings, but for now,
# I'm leaving this test here.
# TODO figure out why.
requir... |
Fix missing time formatting on receiving update | $(document).on 'turbolinks:load', ->
page_id = $('.content').data('page-id')
if page_id
App.updates = App.cable.subscriptions.create { channel: "PageUpdateChannel", page_id: page_id },
connected: ->
# Called when the subscription is ready for use on the server
console.log "Connected to " ... | $(document).on 'turbolinks:load', ->
page_id = $('.content').data('page-id')
if page_id
App.updates = App.cable.subscriptions.create { channel: "PageUpdateChannel", page_id: page_id },
connected: ->
# Called when the subscription is ready for use on the server
console.log "Connected to " ... |
Remove Change Encoding from mini editors | 'menu': [
'label': 'Edit'
'submenu': [
'label': 'Select Encoding'
'command': 'encoding-selector:show'
]
]
'context-menu':
'atom-text-editor': [
'label': 'Change Encoding'
'command': 'encoding-selector:show'
]
| 'menu': [
'label': 'Edit'
'submenu': [
'label': 'Select Encoding'
'command': 'encoding-selector:show'
]
]
'context-menu':
'atom-text-editor:not([mini])': [
'label': 'Change Encoding'
'command': 'encoding-selector:show'
]
|
Fix bug to use correct constructor | # Tub class
YAML = require 'yamljs'
class TubConfig
constructor: (tub, appdir, yml) ->
# body...
@dir = appdir
@tub = tub
@file = "#{@dir}/.jakhu/#{@tub}tub_config.yml"
@yml = yml
@yaml = {}
fs.openSync @file
create: (args) ->
# body...
@yaml.name = @tub
@yaml.language = @yml... | # Tub class
YAML = require 'yamljs'
class TubConfig
constructor: (tub, appdir, yml) ->
# body...
@dir = appdir
@tub = tub
@file = "#{@dir}/.jakhu/#{@tub}tub_config.yml"
@yml = yml
@yaml = {}
fs.openSync @file
create: (args) ->
# body...
@yaml.name = @tub
@yaml.language = @yml... |
Make watch monitor for svg changes too | module.exports = (grunt) ->
# Task definitions
grunt.initConfig({
less:
dist:
files:
"playing-cards.css": "playing-cards.less"
cssmin:
dist:
src: "playing-cards.css"
expand: true
ext: ".min.css"
... | module.exports = (grunt) ->
# Task definitions
grunt.initConfig({
less:
dist:
files:
"playing-cards.css": "playing-cards.less"
cssmin:
dist:
src: "playing-cards.css"
expand: true
ext: ".min.css"
... |
Monitor event loop by looking for skew | seconds = 1000
module.exports = EventLoopMonitor =
monitor: (logger) ->
interval = setInterval () ->
EventLoopMonitor.Delay()
, 1 * seconds
Metrics = require "./metrics"
Metrics.registerDestructor () ->
clearInterval(interval)
Delay: () ->
Metrics = require "./metrics"
t1 = process.hrtime()
setI... | module.exports = EventLoopMonitor =
monitor: (logger, interval = 1000, log_threshold = 100) ->
Metrics = require "./metrics"
previous = Date.now()
intervalId = setInterval () ->
now = Date.now()
offset = now - previous - interval
if offset > log_threshold
logger.warn {offset: offset}, "slow event... |
Read JSON environment file into KONFIG_JSON environment variable | traverse = require 'traverse'
module.exports.create = (KONFIG, options = {}) ->
env = ''
add = (name, value) ->
env += "export #{name}=${#{name}:-#{value}}\n"
traverse.paths(KONFIG).forEach (path) ->
node = traverse.get KONFIG, path
return if typeof node is 'object'
add "KONFIG_#{path.join('_... | traverse = require 'traverse'
module.exports.create = (KONFIG, options = {}) ->
env = ''
add = (name, value) ->
env += "export #{name}=${#{name}:-#{value}}\n"
traverse.paths(KONFIG).forEach (path) ->
node = traverse.get KONFIG, path
return if typeof node is 'object'
add "KONFIG_#{path.join('_... |
Add back directory class to directory view | {View} = require 'space-pen'
FileView = require './file-view'
module.exports =
class DirectoryView extends View
@content: (archivePath, entry) ->
@li class: 'list-nested-item entry', =>
@span class: 'list-item', =>
@span entry.getName(), class: 'icon icon-file-directory'
@ol class: 'list-tree... | {View} = require 'space-pen'
FileView = require './file-view'
module.exports =
class DirectoryView extends View
@content: (archivePath, entry) ->
@li class: 'list-nested-item entry', =>
@span class: 'list-item', =>
@span entry.getName(), class: 'directory icon icon-file-directory'
@ol class: ... |
Remove unnecessary method check for token auth | authenticateToken = (token) ->
env_token = process.env.AUTH_TOKEN
if env_token? && token?
return env_token == token
return false
module.exports = (req, res, next) ->
if _.contains(["POST", "DELETE"], req.method)
unless authenticateToken(req.query.token || null)
return res.send(401, 'Unauthorise... | authenticateToken = (token) ->
env_token = process.env.AUTH_TOKEN
if env_token? && token?
return env_token == token
return false
module.exports = (req, res, next) ->
unless authenticateToken(req.query.token || null)
return res.send(401, 'Unauthorised')
next()
|
Change gist user to JumpeiArashi-blog | 'use strict'
###*
# @ngdoc overview
# @name blogarashikecomApp
# @description
# # blogarashikecomApp
#
# Main module of the application.
###
angular
.module 'arashike-blog', [
'ngAnimate'
'ngAria'
'ngCookies'
'ngMessages'
'ngResource'
'ngRoute'
'ngSanitize'
'ngTouch'
'ngMate... | 'use strict'
###*
# @ngdoc overview
# @name blogarashikecomApp
# @description
# # blogarashikecomApp
#
# Main module of the application.
###
angular
.module 'arashike-blog', [
'ngAnimate'
'ngAria'
'ngCookies'
'ngMessages'
'ngResource'
'ngRoute'
'ngSanitize'
'ngTouch'
'ngMate... |
Define shared machine user add method | bongo = require 'bongo'
{secure} = bongo
JMachine = require './computeproviders/machine'
module.exports = class SharedMachine extends bongo.Base
@share()
setUsers = (client, uid, options, callback) ->
options.permanent = yes
JMachine.shareByUId client, uid, options, callback
| bongo = require 'bongo'
{secure} = bongo
JMachine = require './computeproviders/machine'
module.exports = class SharedMachine extends bongo.Base
@share()
@add = secure (client, uid, target, callback) ->
asUser = yes
options = {target, asUser}
setUsers client, uid, options, callback
setUsers... |
Update yaml content with information. | BaseStackEditorView = require './basestackeditorview'
module.exports = class VariablesEditorView extends BaseStackEditorView
constructor: (options = {}, data) ->
unless options.content
options.content = """
# This is a YAML file which you can define
# key-value pairs like;
#
... | BaseStackEditorView = require './basestackeditorview'
module.exports = class VariablesEditorView extends BaseStackEditorView
constructor: (options = {}, data) ->
unless options.content
options.content = """
# Define custom variables here
# You can define your custom variables, and use the... |
Make namespace optional in log factory | class LoggerFactory
instance = null
@get: ->
instance ?= new LoggerFactory
createLogger: (namespace, defaultLevel = 'info')->
log.debug 'LoggerFactory.createLogger()', arguments
expect(namespace).to.be.a('string').that.is.ok
prefix = namespace + ':'
expect(Loglevel).to.be.a 'functi... | class LoggerFactory
instance = null
@get: ->
instance ?= new LoggerFactory
createLogger: (namespace, defaultLevel = 'info')->
log.debug 'LoggerFactory.createLogger()', arguments
if namespace?
expect(namespace).to.be.a('string')
prefix = namespace + ':'
expect(Loglevel).to.... |
Resolve keybinding conflict with joining lines | '.editor':
'meta-j': 'symbols-view:toggle-file-symbols'
'meta-.': 'symbols-view:go-to-declaration'
'body':
'meta-J': 'symbols-view:toggle-project-symbols'
| '.editor':
'ctrl-j': 'symbols-view:toggle-file-symbols'
'meta-.': 'symbols-view:go-to-declaration'
'body':
'ctrl-J': 'symbols-view:toggle-project-symbols'
|
Convert urls from /content to /contents | define (require) ->
settings = require('cs!settings')
BaseView = require('cs!helpers/backbone/views/base')
template = require('hbs!./latest-template')
require('less!./latest')
return class LatestView extends BaseView
template: template
templateHelpers:
url: () ->
id = @model.get('id').s... | define (require) ->
settings = require('cs!settings')
BaseView = require('cs!helpers/backbone/views/base')
template = require('hbs!./latest-template')
require('less!./latest')
return class LatestView extends BaseView
template: template
templateHelpers:
url: () ->
id = @model.get('id').s... |
Include version numbers in ToC links | define (require) ->
$ = require('jquery')
router = require('cs!router')
analytics = require('cs!helpers/handlers/analytics')
BaseView = require('cs!helpers/backbone/views/base')
template = require('hbs!./leaf-template')
require('less!./leaf')
return class TocNodeView extends BaseView
template: templa... | define (require) ->
$ = require('jquery')
router = require('cs!router')
analytics = require('cs!helpers/handlers/analytics')
BaseView = require('cs!helpers/backbone/views/base')
template = require('hbs!./leaf-template')
require('less!./leaf')
return class TocNodeView extends BaseView
template: templa... |
Add turn off air filter | CronJob = require('cron').CronJob
module.exports = (robot) ->
jobList = [
{ time: '30 10 * * 1-5', msg: '@channel Tea Time!' }
{ time: '00 17 * * 5', msg: '@channel Beer & Pokdeng Time!' }
]
# for job in jobList
# cronJob = new CronJob job.time, =>
# robot.messageRoom '#general', job.msg
# ... | CronJob = require('cron').CronJob
module.exports = (robot) ->
jobList = [
{ time: '30 10 * * 1-5', msg: '@channel Tea Time!' }
{ time: '00 17 * * 5', msg: '@channel Beer & Pokdeng Time!' }
]
# for job in jobList
# cronJob = new CronJob job.time, =>
# robot.messageRoom '#general', job.msg
# ... |
Increase timeouts to decrease server resources consumption | if Meteor.isServer
@Sessions = new Meteor.Collection("session_timeouts")
Meteor.methods( {
session_heartbeat: ->
user_id = Meteor.userId()
return unless user_id
old_session = Sessions.findOne({user_id: user_id})
if old_session?
Sessions.update({user_id: user_i... | if Meteor.isServer
@Sessions = new Meteor.Collection("session_timeouts")
Meteor.methods( {
session_heartbeat: ->
user_id = Meteor.userId()
return unless user_id
old_session = Sessions.findOne({user_id: user_id})
if old_session?
Sessions.update({user_id: user_i... |
Add in null check for user when getting hue in chat | define [
"base"
"ide/colors/ColorManager"
], (App, ColorManager) ->
App.controller "ChatMessageController", ["$scope", "ide", ($scope, ide) ->
$scope.hue = (user) ->
ColorManager.getHueForUserId(user.id)
] | define [
"base"
"ide/colors/ColorManager"
], (App, ColorManager) ->
App.controller "ChatMessageController", ["$scope", "ide", ($scope, ide) ->
$scope.hue = (user) ->
if !user?
return 0
else
return ColorManager.getHueForUserId(user.id)
] |
Upgrade stage hunk file view | {$$, BufferedProcess, SelectListView} = require 'atom'
SelectStageHunks = require './select-stage-hunks-view'
git = require '../git'
module.exports =
class SelectStageHunkFile extends SelectListView
initialize: (items) ->
super
@addClass 'overlay from-top'
@setItems items
atom.workspaceView.append ... | {BufferedProcess} = require 'atom'
{$$, SelectListView} = require 'atom-space-pen-views'
SelectStageHunks = require './select-stage-hunks-view'
git = require '../git'
module.exports =
class SelectStageHunkFile extends SelectListView
initialize: (items) ->
super
@show()
@setItems items
@focusFilterE... |
Add change log entry for 2.0.1 | # The changelog not only lists the significant changes in the interface,
# but provides a mechanism to hook into the tour or display a help menu.
# The changelog is an array of _version_ objects. Each version has a summary
# and an array of changes.
define ->
return [
version: '2.0.0'
changes: [
... | # The changelog not only lists the significant changes in the interface,
# but provides a mechanism to hook into the tour or display a help menu.
# The changelog is an array of _version_ objects. Each version has a summary
# and an array of changes.
define ->
return [
version: '2.0.1'
changes: []
... |
Add font face, bold/italic randomization | window.StrutBuilder ||= {}
StrutBuilder.Textbox = {}
StrutBuilder.Textbox.build = (data, i) ->
{
TextBox: {},
x: 341,
y: 65 * (i+1),
scale: {"x":1, "y":1},
type: "TextBox",
text: "<font data-position=\"" + data.position + "\" data-animation=\"" + data.animation + "\" data-duration=\"" + dat... | window.StrutBuilder ||= {}
StrutBuilder.Textbox = {}
faces = [ 'Lato', 'League Gothic, sans-serif', 'Droid Sans Mono, monospace', 'Ubuntu, sans-serif', 'Abril Fatface, cursive', 'Hammersmith One, sans-serif', 'Fredoka One, cursive', 'Gorditas, cursive', 'Press Start 2P, cursive' ]
randomFace = ->
faces[Math.floor(Ma... |
Move Bower Dependencies Out of scripts/ | gulp = require 'gulp'
del = require 'del'
haml = require 'gulp-haml'
sourcemaps = require 'gulp-sourcemaps'
coffee = require 'gulp-coffee'
serve = require './serve.coffee'
bower = require 'main-bower-files'
SRC = 'src'
DEST = 'out'
gulp.task 'default', ['haml', 'coffee', 'bower']
gul... | gulp = require 'gulp'
del = require 'del'
haml = require 'gulp-haml'
sourcemaps = require 'gulp-sourcemaps'
coffee = require 'gulp-coffee'
serve = require './serve.coffee'
bower = require 'main-bower-files'
SRC = 'src'
DEST = 'out'
gulp.task 'default', ['haml', 'coffee', 'bower']
gul... |
Apply XSS encoding in format quotes utility function | Encoder = require 'htmlencode'
module.exports = (text = '') ->
input = Encoder.htmlDecode text
return text unless (/^>/gm).test input
val = ''
for line in input.split '\n'
line += '\n' if line[0] is '>'
val += "#{line}\n"
return val
| Encoder = require 'htmlencode'
module.exports = (text = '') ->
input = Encoder.htmlDecode text
return text unless (/^>/gm).test input
val = ''
for line in input.split '\n'
line = if line[0] is '>'
then ">#{Encoder.XSSEncode line.substring 1}"
else Encoder.XSSEncode line
val += "#{line}\n... |
Set checked property on togglefield | class Lanes.Components.ToggleField extends Lanes.React.Component
mixins: [ Lanes.Components.Form.FieldMixin ]
formGroupClass: 'toggle'
renderDisplayValue: ->
<Lanes.Vendor.ReactToggle
defaultChecked={!!@props.model[@props.name]}
disabled={true}
/>
handleToggle... | class Lanes.Components.ToggleField extends Lanes.React.Component
mixins: [ Lanes.Components.Form.FieldMixin ]
formGroupClass: 'toggle'
renderDisplayValue: ->
<Lanes.Vendor.ReactToggle
defaultChecked={!!@props.model[@props.name]}
checked={!!@props.model[@props.name]}
... |
Fix undefined error in sign-out route | Router.map ->
@route "entrySignIn",
path: "/sign-in"
onBeforeRun: ->
Session.set('entryError', undefined)
Session.set('buttonText', 'in')
@route "entrySignUp",
path: "/sign-up"
onBeforeRun: ->
Session.set('entryError', undefined)
Session.set('buttonText', 'up')
@route "e... | Router.map ->
@route "entrySignIn",
path: "/sign-in"
onBeforeRun: ->
Session.set('entryError', undefined)
Session.set('buttonText', 'in')
@route "entrySignUp",
path: "/sign-up"
onBeforeRun: ->
Session.set('entryError', undefined)
Session.set('buttonText', 'up')
@route "e... |
Fix bug where every blog author was 'Mystery author' on blog index page | Router.map ->
@route 'blogIndex',
path: '/blog'
before: ->
if Blog.settings.blogIndexTemplate
@template = Blog.settings.blogIndexTemplate
waitOn: ->
Meteor.subscribe 'posts'
data: ->
posts: Post.where published: true
@route 'blogShow',
path: '/blog/:slug'
notFound... | Router.map ->
@route 'blogIndex',
path: '/blog'
before: ->
if Blog.settings.blogIndexTemplate
@template = Blog.settings.blogIndexTemplate
waitOn: ->
[ Meteor.subscribe 'posts'
Meteor.subscribe 'users' ]
data: ->
posts: Post.where published: true
@route 'blogShow',... |
Use current stable version of Sinon.JS, require browser packaged version when using webpack, fix usage of sinon-chai | class WebpackConfig
getDefaultConfiguration: ->
module:
loaders: [
{test: /\.coffee$/i, loader: 'coffee-loader'}
]
resolve:
extensions: ['', '.js', '.coffee']
module.exports = new WebpackConfig | webpackStream = require 'webpack-stream'
NormalModuleReplacementPlugin = webpackStream.webpack.NormalModuleReplacementPlugin
class WebpackConfig
getDefaultConfiguration: ->
module:
loaders: [
{test: /\.coffee$/i, loader: 'coffee-loader'}
]
noParse: [
/node_modules\/sinon\/pkg\... |
Implement deactivate that offs subscription | SpellCheckView = null
module.exports =
configDefaults:
grammars: [
'text.plain'
'source.gfm'
'text.git-commit'
]
createView: (editorView) ->
SpellCheckView ?= require './spell-check-view'
new SpellCheckView(editorView)
activate: ->
atom.workspaceView.eachEditorView (editor... | SpellCheckView = null
module.exports =
configDefaults:
grammars: [
'text.plain'
'source.gfm'
'text.git-commit'
]
activate: ->
@editorSubscription = atom.workspaceView.eachEditorView(addViewToEditor)
deactivate: ->
@editorSubscription?.off()
addViewToEditor = (editorView) ->
... |
Sort party list in descending order | class PartyListView extends Backbone.View
el: $('div.party-list')
el_gov: $('ul.party-list-government')
el_oppo: $('ul.party-list-opposition')
render: ->
@collection.forEach @render_one, @
return @
render_one: (party) ->
if party.get "governing_party"
el = @el_g... | class PartyListView extends Backbone.View
el: $('div.party-list')
el_gov: $('ul.party-list-government')
el_oppo: $('ul.party-list-opposition')
render: ->
@collection.forEach @render_one, @
return @
render_one: (party) ->
if party.get "governing_party"
el = @el_g... |
Create url for avatar download | store = new FS.Store.FileSystem "images",
path: "~/uploads"
fileKeyMaker: (fileObj) ->
filename = fileObj.name()
filenameInStore = fileObj.name({store: 'images'})
return filenameInStore || filename
@Images = new FS.Collection "images",
stores: [store]
@Images.allow
insert: ->
return true
update: ->
re... | uploadPath = "~/uploads"
store = new FS.Store.FileSystem "images",
path: uploadPath
fileKeyMaker: (fileObj) ->
filename = fileObj.name()
filenameInStore = fileObj.name({store: 'images'})
return filenameInStore || filename
@Images = new FS.Collection "images",
stores: [store]
@Images.allow
insert: ->
ret... |
Use atom.commands to register commands | GitHubFile = require './github-file'
module.exports =
configDefaults:
includeLineNumbersInUrls: true
activate: ->
return unless atom.project.getRepo()?
atom.workspaceView.eachPaneView (pane) ->
pane.command 'open-on-github:file', ->
if itemPath = getActivePath()
GitHubFile.fr... | GitHubFile = require './github-file'
module.exports =
configDefaults:
includeLineNumbersInUrls: true
activate: ->
return unless atom.project.getRepo()?
atom.workspace.observePanes (pane) ->
atom.commands.add atom.views.getView(pane),
'open-on-github:file': ->
if itemPath = ge... |
Remove setting count to zero, it makes it cluncky | # 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/
$ ->
animateMetric = $(".metric-box strong").each ->
$this = $(this)
starting_point = 0
$targe... | # 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/
$ ->
animateMetric = $(".metric-box strong").each ->
$this = $(this)
starting_point = 0
$targe... |
Load method for future preloading | # Placeholder Polyfill
# https://github.com/mathiasbynens/jquery-placeholder
$(window).load ->
$("input, textarea").placeholder()
# Sammy
(($) ->
circle = $.sammy("body", ->
# Page
class Page
constructor: (@name, @title) ->
render: ->
document.title = "Circle - " + @title
$("b... | # Placeholder Polyfill
# https://github.com/mathiasbynens/jquery-placeholder
$(window).load ->
$("input, textarea").placeholder()
# Sammy
(($) ->
circle = $.sammy("body", ->
# Page
class Page
constructor: (@name, @title) ->
render: ->
document.title = "Circle - " + @title
$("b... |
Use correct path in error message | path = require 'path'
optimist = require 'optimist'
async = require 'async'
archive = require './ls-archive'
module.exports = ->
files = optimist.usage('Usage: lsa [file ...]') .demand(1).argv._
queue = async.queue (archivePath, callback) ->
do (archivePath) ->
archive.list archivePath, (error, files) ->... | path = require 'path'
optimist = require 'optimist'
async = require 'async'
archive = require './ls-archive'
module.exports = ->
files = optimist.usage('Usage: lsa [file ...]') .demand(1).argv._
queue = async.queue (archivePath, callback) ->
do (archivePath) ->
archive.list archivePath, (error, files) ->... |
Use correct labels for 'Favourite' button | class window.FavouriteTopicButtonView extends ActionButtonView
mini: true
onRender: -> @updateButton()
initialize: ->
@bindTo @model, 'change', @updateButton, @
@user = currentUser
templateHelpers: =>
disabled_label: Factlink.Global.t.follow.capitalize()
disable_label: Factlink.Global.t.unfo... | class window.FavouriteTopicButtonView extends ActionButtonView
mini: true
onRender: -> @updateButton()
initialize: ->
@bindTo @model, 'change', @updateButton, @
@user = currentUser
templateHelpers: =>
disabled_label: Factlink.Global.t.favourite.capitalize()
disable_label: Factlink.Global.t.u... |
Change url for ip route | # Description:
# A simple interaction with the built in HTTP Daemon
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# None
#
# URLS:
# /hubot/version
# /hubot/ping
# /hubot/time
# /hubot/info
# /hubot/ip
spawn = require('child_process').spawn
module.exports = (robot) ->
robot.rou... | # Description:
# A simple interaction with the built in HTTP Daemon
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# None
#
# URLS:
# /hubot/version
# /hubot/ping
# /hubot/time
# /hubot/info
# /hubot/ip
spawn = require('child_process').spawn
module.exports = (robot) ->
robot.rou... |
Make multi-line regex test more strict | Point = require './point'
SpliceArrayChunkSize = 100000
MULTI_LINE_REGEX_REGEX = /[\r\n\[]/
module.exports =
spliceArray: (originalArray, start, length, insertedArray=[]) ->
if insertedArray.length < SpliceArrayChunkSize
originalArray.splice(start, length, insertedArray...)
else
removedValues =... | Point = require './point'
SpliceArrayChunkSize = 100000
MULTI_LINE_REGEX_REGEX = /\r|\n|^\[\^|[^\\]\[\^/
module.exports =
spliceArray: (originalArray, start, length, insertedArray=[]) ->
if insertedArray.length < SpliceArrayChunkSize
originalArray.splice(start, length, insertedArray...)
else
re... |
Remove rouge console.log file from the issues list view | define [
'jquery'
'underscore'
'backbone'
'jade.templates'
'mixen'
'mixens/BaseViewMixen'
'mixens/CollectionViewMixen'
], ($, _, Backbone, jade, Mixen, BaseView, CollectionView) ->
class IssuesListView extends Mixen(CollectionView, BaseView)
template: jade.issues
initialize: (options) ->
... | define [
'jquery'
'underscore'
'backbone'
'jade.templates'
'mixen'
'mixens/BaseViewMixen'
'mixens/CollectionViewMixen'
], ($, _, Backbone, jade, Mixen, BaseView, CollectionView) ->
class IssuesListView extends Mixen(CollectionView, BaseView)
template: jade.issues
initialize: (options) ->
... |
Stop trying to make Map a polyfill. | exports.Util =
last: (arr) -> arr[arr.length - 1]
isString: (s) -> typeof s == 'string' || s instanceof String
defineNonEnumerable: (obj, k, v) ->
Object.defineProperty obj, k,
value: v
writable: true
enumerable: false
configurable: true
# polyfill
if Map?
if not Map.prototype.it... | exports.Util =
last: (arr) -> arr[arr.length - 1]
isString: (s) -> typeof s == 'string' || s instanceof String
defineNonEnumerable: (obj, k, v) ->
Object.defineProperty obj, k,
value: v
writable: true
enumerable: false
configurable: true
class exports.Map
constructor: ->
@cach... |
Add Promise.all/race/resolve/reject & improve then/catch | ".source.js":
"Promise":
prefix: "promise",
body: """
new Promise((resolve, reject) => {
\t${0}
});
"""
"Promise.then":
prefix: "then"
body: """
then((${2:value}) => {
\t${0}
});
"""
"Promise.catch":
prefix: "catch"
body: """
catch(${2:(err)} => {
\t... | ".source.js":
"Promise":
prefix: "promise",
body: """
new Promise((resolve, reject) => {
\t${0}
});
"""
"Promise.ptorotype.then":
prefix: "then"
body: """
then(${1:(${2:value}) => {
\t${0}
\\}})
"""
"Promise.ptorotype.catch":
prefix: "catch"
body: """
ca... |
Switch cson keys to be single quoted | menu: [
{
label: 'View'
submenu: [
{
label: 'Toggle Treeview'
command: 'tree-view:toggle'
}
]
}
]
'context-menu':
'.tree-view':
'Add File': 'tree-view:add'
'Rename': 'tree-view:move'
'Delete': 'tree-view:remove'
| 'menu': [
{
'label': 'View'
'submenu': [
{
'label': 'Toggle Treeview'
'command': 'tree-view:toggle'
}
]
}
]
'context-menu':
'.tree-view':
'Add File': 'tree-view:add'
'Rename': 'tree-view:move'
'Delete': 'tree-view:remove'
|
Remove some parens per @markijbema's suggestion. | $( ->
$modal = $('.js-feedback-modal')
$iframe = $('.js-feedback-modal iframe')
iframeIsLoaded = false
openFeedbackFrame = ->
iframeIsLoaded = true
$modal.fadeIn('fast')
$iframe[0].contentWindow.updateHeight()
$(".js-feedback-modal-link").on('click', ->
if !$iframe.attr('src')
$iframe.... | $ ->
$modal = $('.js-feedback-modal')
$iframe = $('.js-feedback-modal iframe')
iframeIsLoaded = false
openFeedbackFrame = ->
iframeIsLoaded = true
$modal.fadeIn('fast')
$iframe[0].contentWindow.updateHeight()
$(".js-feedback-modal-link").on 'click', ->
if !$iframe.attr('src')
$iframe.a... |
Fix multiple tooltips in stream; don't clean up positionedRegion if it wasn't created. | Backbone.Factlink ||= {}
class TooltipCreator
constructor: (@_$offsetParent, @_positioning, @_tooltipViewFactory)->
createTooltip: ($target) ->
@_positionedRegion().bindToElement $target, @_$offsetParent
@_positionedRegion().show @_tooltipView()
@_positionedRegion().updatePosition()
@_positionedR... | Backbone.Factlink ||= {}
class TooltipCreator
constructor: (@_$offsetParent, @_positioning, @_tooltipViewFactory)->
createTooltip: ($target) ->
@_ensureRegion()
@_positionedRegion.bindToElement $target, @_$offsetParent
@_positionedRegion.show @_tooltipView()
@_positionedRegion.updatePosition()
... |
Comment out my local tasks | module.exports = (grunt) ->
grunt.initConfig
pkgFile: 'package.json'
files:
adapter: ['src/adapter.js']
build:
adapter: '<%= files.adapter %>'
# JSHint options
# http://www.jshint.com/options/
jshint:
adapter:
files:
src: '<%= files.adapter %>'
op... | module.exports = (grunt) ->
grunt.initConfig
pkgFile: 'package.json'
files:
adapter: ['src/adapter.js']
build:
adapter: '<%= files.adapter %>'
# JSHint options
# http://www.jshint.com/options/
jshint:
adapter:
files:
src: '<%= files.adapter %>'
op... |
Save collapsibles state so that changing countries for a new location keeps the collapsible expanded | # These includes mimic the includes in the phonegap app. Everything
# else is loaded in application_extra.js.coffee
#= require jquery
#= require myplaceonline
#= require jquery.mobile
#= require handlebars-v2.0.0
#= require ember-1.9.0
#= require forge.min
$ ->
$('body').on('change', 'select.region', ->
select_... | # These includes mimic the includes in the phonegap app. Everything
# else is loaded in application_extra.js.coffee
#= require jquery
#= require myplaceonline
#= require jquery.mobile
#= require handlebars-v2.0.0
#= require ember-1.9.0
#= require forge.min
$ ->
$('body').on('change', 'select.region', ->
select_... |
Fix question wont remove bug | jQuery ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('div.question').hide()
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new ... | jQuery ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('div.question').remove()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$... |
Add add method to Size |
#
module.exports =
class Size
@create: (width, height) ->
return width if width instanceof Size
if Array.isArray(width)
new Size(width[0], width[1])
else
new Size(width, height)
constructor: (width, height) ->
@set(width, height)
set: (@width, @height) ->
[@width, @height] = @wi... | Point = require './point'
#
module.exports =
class Size
@create: (width, height) ->
return width if width instanceof Size
if Array.isArray(width)
new Size(width[0], width[1])
else
new Size(width, height)
constructor: (width, height) ->
@set(width, height)
set: (@width, @height) ->
... |
Add key bindings for block travel | 'atom-workspace':
'ctrl-cmd-r': 'tree-view:reveal-active-file'
'ctrl-cmd-t': 'window:run-package-specs'
'ctrl-shift-alt-t': 'custom:open-todo-list'
'atom-text-editor':
'ctrl-shift-a': 'asciidoc-preview:toggle'
'.platform-darwin atom-workspace':
'ctrl-"': 'toggle-quotes:toggle'
'alt-cmd-n': 'advanced-open-fi... | 'atom-workspace':
'ctrl-cmd-r': 'tree-view:reveal-active-file'
'ctrl-cmd-t': 'window:run-package-specs'
'ctrl-shift-alt-t': 'custom:open-todo-list'
'atom-text-editor':
'ctrl-shift-a': 'asciidoc-preview:toggle'
'alt-up': 'block-travel:move-up'
'alt-down': 'block-travel:move-down'
'.platform-darwin atom-works... |
Move persistency area to the bottom | React = require 'react'
R = require 'ramda'
serialize = require '../../builder/serializer'
SimulationHeader = require './simulation_header'
Observable = require './observable'
PersistencyArea = require './persistency'
ResultControl = require './result_control'
module.exports = React.createClass
getInitialState: ->... | React = require 'react'
R = require 'ramda'
serialize = require '../../builder/serializer'
SimulationHeader = require './simulation_header'
Observable = require './observable'
PersistencyArea = require './persistency'
ResultControl = require './result_control'
module.exports = React.createClass
getInitialState: ->... |
Add option to pass data into render fn | ns2path = (ns)->
ns.replace(".","/").toLowerCase()
Lanes.Templates.find = (name, namespace) ->
return Lanes.Templates[name] if Lanes.Templates[name]
if namespace?
Lanes.Templates[ ns2path(namespace) + "/" + name]
else
null
Lanes.Templates.render = (view, name)->
template_fn = Lanes... | ns2path = (ns)->
ns.replace(".","/").toLowerCase()
Lanes.Templates.find = (name, namespace) ->
return Lanes.Templates[name] if Lanes.Templates[name]
if namespace?
Lanes.Templates[ ns2path(namespace) + "/" + name]
else
null
Lanes.Templates.render = (view, name, data)->
template_fn =... |
Remove console log from privacy policy page | angular.module("doubtfire.config.privacy-policy", [])
.factory('PrivacyPolicy', ($http, api) ->
privacyPolicy = {
privacy: '',
plagiarism: '',
loaded: false,
}
$http.get("#{api}/settings/privacy").then ((response) ->
console.log(response.data)
privacyPolicy.privacy = response.data.privacy
... | angular.module("doubtfire.config.privacy-policy", [])
.factory('PrivacyPolicy', ($http, api) ->
privacyPolicy = {
privacy: '',
plagiarism: '',
loaded: false,
}
$http.get("#{api}/settings/privacy").then ((response) ->
privacyPolicy.privacy = response.data.privacy
privacyPolicy.plagiarism = re... |
Make sure isSuperTypeOf works as expected. | ProxyType = require '../../../../src/finitio/type/proxy_type'
should = require 'should'
{intType,
byteType} = require '../../../spec_helpers'
describe "ProxyType#isSuperTypeOf", ->
it "works against a real type", ->
type = new ProxyType('int', intType)
should(type.isSuperTypeOf(byteType)).be.true
i... | ProxyType = require '../../../../src/finitio/type/proxy_type'
AliasType = require '../../../../src/finitio/type/alias_type'
should = require 'should'
{intType,
byteType} = require '../../../spec_helpers'
describe "ProxyType#isSuperTypeOf", ->
it "works against a real type", ->
type = new ProxyType('int',... |
Fix int parsing for port | mongoAdapter = require 'sails-mongo'
module.exports =
db:
adapters:
mongo: mongoAdapter
connections:
default:
adapter: 'mongo'
url: process.env.MONGOLAB_URI
defaults:
migrate: 'alter'
autoPK: true
autoCreatedAt: false
autoUpdatedAt: false
mailgun:
... | mongoAdapter = require 'sails-mongo'
module.exports =
db:
adapters:
mongo: mongoAdapter
connections:
default:
adapter: 'mongo'
url: process.env.MONGOLAB_URI
defaults:
migrate: 'alter'
autoPK: true
autoCreatedAt: false
autoUpdatedAt: false
mailgun:
... |
Remove use of workspaceView in tests | {WorkspaceView} = require 'atom'
TableEdit = require '../lib/table-edit'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe "TableEdit", ->
act... | TableEdit = require '../lib/table-edit'
# Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
#
# To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
# or `fdescribe`). Remove the `f` to unfocus the block.
describe "TableEdit", ->
activationPromise = null
beforeEa... |
Add GA call upon click on Sign Up button | SublimeVideo.UI.Utils =
makeSticky: (element, cssSelector) ->
$("#{cssSelector} .active").each -> jQuery(this).removeClass 'active'
element.addClass 'active'
if li = element.parent 'li' then li.addClass 'active'
# Opens a new popup and store its reference in `SublimeVideo.UI.popup`
#
# @param [Obj... | SublimeVideo.UI.Utils =
makeSticky: (element, cssSelector) ->
$("#{cssSelector} .active").each -> jQuery(this).removeClass 'active'
element.addClass 'active'
if li = element.parent 'li' then li.addClass 'active'
# Opens a new popup and store its reference in `SublimeVideo.UI.popup`
#
# @param [Obj... |
Switch to the log in page on log out. | 'use strict'
angular.module('xoWebApp')
.controller 'NavBarCtrl', ($scope, $location, xoApi) ->
# TODO: It would make sense to inject xoApi in the scope.
$scope.$watch(
-> xoApi.status
(status) ->
$scope.status = status
)
$scope.$watch(
-> xoApi.user
(user) ->
... | 'use strict'
angular.module('xoWebApp')
.controller 'NavBarCtrl', ($scope, $state, xoApi) ->
# TODO: It would make sense to inject xoApi in the scope.
$scope.$watch(
-> xoApi.status
(status) ->
$scope.status = status
)
$scope.$watch(
-> xoApi.user
(user) ->
$sc... |
Remove leading whitespace from prefix | {View, Range} = require 'atom'
module.exports =
class SearchResultView extends View
@content: ({filePath, match}) ->
range = Range.fromObject(match.range)
matchStart = range.start.column - match.lineTextOffset
matchEnd = range.end.column - match.lineTextOffset
prefix = match.lineText[match.lineTextOf... | {View, Range} = require 'atom'
LeadingWhitespace = /^\s+/
removeLeadingWhitespace = (string) -> string.replace(LeadingWhitespace, '')
module.exports =
class SearchResultView extends View
@content: ({filePath, match}) ->
range = Range.fromObject(match.range)
matchStart = range.start.column - match.lineTextOf... |
Add 6to5 step to default task | module.exports = (grunt) ->
require('time-grunt')(grunt)
require('load-grunt-config') grunt,
jitGrunt: true
grunt.registerTask 'default', ['clean', 'amd_tamer', 'uglify']
grunt.registerTask 'test', ['jshint']
grunt.registerTask 'doc', ['groc']
grunt.registerTask 'pages', ['metalsmith', 'doc'... | module.exports = (grunt) ->
require('time-grunt')(grunt)
require('load-grunt-config') grunt,
jitGrunt: true
grunt.registerTask 'default', ['clean', '6to5', 'amd_tamer', 'uglify']
grunt.registerTask 'test', ['jshint']
grunt.registerTask 'doc', ['groc']
grunt.registerTask 'pages', ['metalsmith... |
Fix binding on share event | _ = require '../../utils/lodash'
EventBus = require '../../utils/eventbus'
assign = require '../../polyfills/assign'
class Tracker
constructor : (api, remoteConfig, config)->
@api = api
@setupTracking()
getCurrentUserId: -> @api.currentUser.getId()
setupTracking : () ->
return if @setup
... | _ = require '../../utils/lodash'
EventBus = require '../../utils/eventbus'
assign = require '../../polyfills/assign'
class Tracker
constructor : (api, remoteConfig, config)->
@api = api
@setupTracking()
getCurrentUserId: -> @api.currentUser.getId()
setupTracking : () ->
return if @setup
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.