text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Transform emitted code with babel
import fs from "fs"; import path from "path"; import babel from "babel"; import nodeEval from "eval"; import {parse, SyntaxError} from "../../src/compiler/parser"; import emit from "../../src/compiler/emit"; export default function loadComponent(name) { const file = fs.readFileSync(path.join(__dirname, `../fixtures/${name}.piece`), {encoding: "utf8"}); try { const parsed = parse(file); console.log(JSON.stringify(parsed, null, 2)); const emitted = emit(parsed); console.log(emitted); return nodeEval(babel.transform(emitted)); } catch (e) { if (e instanceof SyntaxError) { const {line, column} = e.location.start; throw new Error(`Syntax error at ${line}:${column}: ${e.message}`); } else { throw e; } } }
import fs from "fs"; import path from "path"; import babel from "babel"; import nodeEval from "eval"; import {parse, SyntaxError} from "../../src/compiler/parser"; import emit from "../../src/compiler/emit"; export default function loadComponent(name) { const file = fs.readFileSync(path.join(__dirname, `../fixtures/${name}.piece`), {encoding: "utf8"}); try { const parsed = parse(file); console.log(JSON.stringify(parsed, null, 2)); const emitted = emit(parsed); console.log(emitted); return nodeEval(emitted); } catch (e) { if (e instanceof SyntaxError) { const {line, column} = e.location.start; throw new Error(`Syntax error at ${line}:${column}: ${e.message}`); } else { throw e; } } }
Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
# Test the 'trait_set', 'trait_get' interface to # the HasTraits class. # # Copyright (c) 2014, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # License included in /LICENSE.txt and may be redistributed only under the # conditions described in the aforementioned license. The license is also # available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! """ A decorator for marking methods/functions as deprecated. """ # Standard library imports. import functools import warnings def deprecated(message): """ A factory for decorators for marking methods/functions as deprecated. """ def decorator(fn): """ A decorator for marking methods/functions as deprecated. """ @functools.wraps(fn) def wrapper(*args, **kw): """ The method/function wrapper. """ warnings.warn(message, DeprecationWarning, stacklevel=2) return fn(*args, **kw) return wrapper return decorator
""" A decorator for marking methods/functions as deprecated. """ # Standard library imports. import logging # We only warn about each function or method once! _cache = {} def deprecated(message): """ A factory for decorators for marking methods/functions as deprecated. """ def decorator(fn): """ A decorator for marking methods/functions as deprecated. """ def wrapper(*args, **kw): """ The method/function wrapper. """ global _cache module_name = fn.__module__ function_name = fn.__name__ if (module_name, function_name) not in _cache: logging.getLogger(module_name).warning( 'DEPRECATED: %s.%s, %s' % ( module_name, function_name, message ) ) _cache[(module_name, function_name)] = True return fn(*args, **kw) wrapper.__doc__ = fn.__doc__ wrapper.__name__ = fn.__name__ return wrapper return decorator #### EOF ######################################################################
Add values to vote enum
package wissolsoft.porada.webapp.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.appfuse.model.User; @Entity @Table(name="vote") public class Vote { public enum Value { /** Утримався */ ABSTAIN, /** За */ FOR, /** Проти */ AGAINST } @Id @GeneratedValue private long id; @ManyToOne private Law law; @ManyToOne private User user; private Value value; public long getId() { return id; } public Law getLaw() { return law; } public User getUser() { return user; } public Value getValue() { return value; } public void setLaw(Law law) { this.law = law; } public void setUser(User user) { this.user = user; } public void setValue(Value value) { this.value = value; } }
package wissolsoft.porada.webapp.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.appfuse.model.User; @Entity @Table(name="vote") public class Vote { public enum Value { } @Id @GeneratedValue private long id; @ManyToOne private Law law; @ManyToOne private User user; private Value value; public long getId() { return id; } public Law getLaw() { return law; } public User getUser() { return user; } public Value getValue() { return value; } public void setLaw(Law law) { this.law = law; } public void setUser(User user) { this.user = user; } public void setValue(Value value) { this.value = value; } }
Allow more symbols in links.
function Resolve(stage, text){ if(text == null) { return ''; } text = text.replace(Resolve.rxExternalLink, '<a href="$1" class="external-link" target="_blank" rel="nofollow">$2</a>'); text = text.replace(Resolve.rxInternalLink, function(match, link){ var ref = Convert.LinkToReference(link, stage); return '<a href="' + ref.url + '" data-link="' + ref.link + '" >' + ref.title + "</a>"; }); return text; } Resolve.rxExternalLink = /\[\[\s*(https?\:[^ \]]+)\s+([^\]]+)\]\]/g; Resolve.rxInternalLink = /\[\[\s*([^\]]+)\s*\]\]/g; //TODO: add HTML sanitation function ResolveHTML(stage, text){ return Resolve(stage, text); }
function Resolve(stage, text){ if(text == null) { return ''; } text = text.replace(Resolve.rxExternalLink, '<a href="$1" class="external-link" target="_blank" rel="nofollow">$2</a>'); text = text.replace(Resolve.rxInternalLink, function(match, link){ var ref = Convert.LinkToReference(link, stage); return '<a href="' + ref.url + '" data-link="' + ref.link + '" >' + ref.title + "</a>"; }); return text; } Resolve.rxExternalLink = /\[\[\s*(http[a-zA-Z0-9:\.\/\-]+)\s+([^\]]+)\]\]/g; Resolve.rxInternalLink = /\[\[\s*([^\]]+)\s*\]\]/g; //TODO: add HTML sanitation function ResolveHTML(stage, text){ return Resolve(stage, text); }
Refactor landing page to use mapDispatchToProps which is another method of doing what we were already doing
import React from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import { setSearchTerm } from './actionCreators' const { string, func, object } = React.PropTypes const Landing = React.createClass({ contextTypes: { router: object }, propTypes: { searchTerm: string, dispatchSetSearchTerm: func }, handleSearchTermChange (event) { this.props.dispatchSetSearchTerm(event.target.value) }, handleSearchSubmit (event) { event.preventDefault() this.context.router.transitionTo('/search') }, render () { return ( <div className='landing'> <h1>svideo</h1> <form onSubmit={this.handleSearchSubmit}> <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' /> </form> <Link to='/search'>or Browse All</Link> </div> ) } }) const mapStateToProps = (state) => { return { searchTerm: state.searchTerm } } const mapDispatchToProps = (dispatch) => { return { dispatchSetSearchTerm (searchTerm) { dispatch(setSearchTerm(searchTerm)) } } } export default connect(mapStateToProps, mapDispatchToProps)(Landing)
import React from 'react' import { Link } from 'react-router' import { setSearchTerm } from './actionCreators' import { connect } from 'react-redux' const { string, func, object } = React.PropTypes const Landing = React.createClass({ contextTypes: { router: object }, propTypes: { searchTerm: string, dispatch: func }, handleSearchTermChange (event) { this.props.dispatch(setSearchTerm(event.target.value)) }, handleSearchSubmit (event) { event.preventDefault() this.context.router.transitionTo('/search') }, render () { return ( <div className='landing'> <h1>svideo</h1> <form onSubmit={this.handleSearchSubmit}> <input onChange={this.handleSearchTermChange} type='text' placeholder='Search' /> </form> <Link to='/search'>or Browse All</Link> </div> ) } }) const mapStateToProps = (state) => { return { searchTerm: state.searchTerm } } export default connect(mapStateToProps)(Landing)
Revert "Fix 502 on admin page, is_authenticated() is now a boolean" This reverts commit 0d9a7f86c1d988b4e0f4617c5e4f0409c0754e19.
from database import User, Paste, ApiKey from flask import abort, current_app from flask_login import current_user from flask_admin import BaseView, Admin from flask_admin.contrib.mongoengine import ModelView def is_admin(): if current_user.is_anonymous(): abort(403) else: return current_user.admin class ProtectedView(BaseView): def is_accessible(self): return is_admin() class SecureModelView(ModelView): def is_accessible(self): return is_admin() class UserModel(SecureModelView): column_exclude_list = "hash" column_searchable_list = ("username", "email") can_create = False can_edit = True can_delete = True class PasteModel(SecureModelView): list_display = ("name", "paste", "time", "expire", "user", "views", "language") column_searchable_list = ("name", "paste") class ApiKeyModel(SecureModelView): pass admin = Admin(current_app) admin.add_view(UserModel(User)) admin.add_view(PasteModel(Paste)) admin.add_view(ApiKeyModel(ApiKey))
from database import User, Paste, ApiKey from flask import abort, current_app from flask_login import current_user from flask_admin import BaseView, Admin from flask_admin.contrib.mongoengine import ModelView def is_admin(): if current_user.is_anonymous: abort(403) else: return current_user.admin class ProtectedView(BaseView): def is_accessible(self): return is_admin() class SecureModelView(ModelView): def is_accessible(self): return is_admin() class UserModel(SecureModelView): column_exclude_list = "hash" column_searchable_list = ("username", "email") can_create = False can_edit = True can_delete = True class PasteModel(SecureModelView): list_display = ("name", "paste", "time", "expire", "user", "views", "language") column_searchable_list = ("name", "paste") class ApiKeyModel(SecureModelView): pass admin = Admin(current_app) admin.add_view(UserModel(User)) admin.add_view(PasteModel(Paste)) admin.add_view(ApiKeyModel(ApiKey))
Allow events to be configurable through config
<?php namespace NotificationChannels\ExpoPushNotifications\Models; use Illuminate\Database\Eloquent\Model; class Interest extends Model { /** * The associated table. * * @var string */ protected $table; /** * The event map for the model. * * @var array */ protected $dispatchesEvents; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'key', 'value', ]; /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = false; /** * Interest constructor. * * @param array $attributes */ public function __construct(array $attributes = []) { $this->dispatchesEvents = config('exponent-push-notifications.interests.database.events'); $this->table = config('exponent-push-notifications.interests.database.table_name'); parent::__construct($attributes); } }
<?php namespace NotificationChannels\ExpoPushNotifications\Models; use Illuminate\Database\Eloquent\Model; class Interest extends Model { /** * The associated table. * * @var string */ protected $table; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'key', 'value', ]; /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = false; /** * Interest constructor. * * @param array $attributes */ public function __construct(array $attributes = []) { $this->table = config('exponent-push-notifications.interests.database.table_name'); parent::__construct($attributes); } }
Add css support for assertExpected
var fs = require('fs'), glob = require('glob'), path = require('path'), wrench = require('wrench'); var counter = 0; try { fs.mkdirSync('/tmp/lumbar-test', 0755); } catch (err) {} exports.testDir = function(testName, configFile) { var outdir = '/tmp/lumbar-test/' + testName + '-' + path.basename(configFile) + '-' + Date.now() + '-' + (counter++); console.log('Creating test directory ' + outdir + ' for ' + configFile); fs.mkdirSync(outdir, 0755); return outdir; }; exports.assertExpected = function(outdir, expectedDir, configFile, assert) { var expectedFiles = glob.globSync(expectedDir + '/**/*.{js,css}').map(function(fileName) { return fileName.substring(expectedDir.length); }), generatedFiles = glob.globSync(outdir + '/**/*.{js,css}').map(function(fileName) { return fileName.substring(outdir.length); }); assert.deepEqual(generatedFiles, expectedFiles, configFile + ': file list matches'); generatedFiles.forEach(function(fileName) { var generatedContent = fs.readFileSync(outdir + fileName, 'utf8'), expectedContent = fs.readFileSync(expectedDir + fileName, 'utf8'); assert.equal(generatedContent, expectedContent, configFile + ':' + fileName + ': content matches'); }); };
var fs = require('fs'), glob = require('glob'), path = require('path'), wrench = require('wrench'); var counter = 0; try { fs.mkdirSync('/tmp/lumbar-test', 0755); } catch (err) {} exports.testDir = function(testName, configFile) { var outdir = '/tmp/lumbar-test/' + testName + '-' + path.basename(configFile) + '-' + Date.now() + '-' + (counter++); console.log('Creating test directory ' + outdir + ' for ' + configFile); fs.mkdirSync(outdir, 0755); return outdir; }; exports.assertExpected = function(outdir, expectedDir, configFile, assert) { var expectedFiles = glob.globSync(expectedDir + '/**/*.js').map(function(fileName) { return fileName.substring(expectedDir.length); }), generatedFiles = glob.globSync(outdir + '/**/*.js').map(function(fileName) { return fileName.substring(outdir.length); }); assert.deepEqual(generatedFiles, expectedFiles, configFile + ': file list matches'); generatedFiles.forEach(function(fileName) { var generatedContent = fs.readFileSync(outdir + fileName, 'utf8'), expectedContent = fs.readFileSync(expectedDir + fileName, 'utf8'); assert.equal(generatedContent, expectedContent, configFile + ':' + fileName + ': content matches'); }); };
Add getter for template variable
package cz.quanti.mailq.entities.v2; import cz.quanti.mailq.entities.v2.enums.NotificationStatus; public class SmsNotificationEntity extends BaseEntity { private Long id; private String name; private String code; private String template; private NotificationStatus status; private LinkEntity company; public Long getId() { return id; } public String getName() { return name; } public String getCode() { return code; } public NotificationStatus getStatus() { return status; } public LinkEntity getCompany() { return company; } public String getTemplate() { return template; } public SmsNotificationEntity setName(String name) { this.name = name; return this; } public SmsNotificationEntity setCode(String code) { this.code = code; return this; } public SmsNotificationEntity setTemplate(String template) { this.template = template; return this; } }
package cz.quanti.mailq.entities.v2; import cz.quanti.mailq.entities.v2.enums.NotificationStatus; public class SmsNotificationEntity extends BaseEntity { private Long id; private String name; private String code; private String template; private NotificationStatus status; private LinkEntity company; public Long getId() { return id; } public String getName() { return name; } public String getCode() { return code; } public NotificationStatus getStatus() { return status; } public LinkEntity getCompany() { return company; } public SmsNotificationEntity setName(String name) { this.name = name; return this; } public SmsNotificationEntity setCode(String code) { this.code = code; return this; } public SmsNotificationEntity setTemplate(String template) { this.template = template; return this; } }
Make error event of GeoNames data
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var Events = app.Events || require('../base/events.js'); var GeoNamesData = function(url) { this._url = url; this._loadPromise = null; this._data = []; this._events = new Events(); }; GeoNamesData.prototype.on = function() { return Events.prototype.on.apply(this._events, arguments); }; GeoNamesData.prototype.load = function() { if (!this._loadPromise) { this._events.emit('loading'); this._loadPromise = dom.loadJSON(this._url).then(function(data) { this._data = data; this._events.emit('loaded'); }.bind(this)).catch(function() { this._loadPromise = null; this._events.emit('error'); }.bind(this)); } return this._loadPromise; }; if (typeof module !== 'undefined' && module.exports) { module.exports = GeoNamesData; } else { app.GeoNamesData = GeoNamesData; } })(this.app || (this.app = {}));
(function(app) { 'use strict'; var dom = app.dom || require('../dom.js'); var Events = app.Events || require('../base/events.js'); var GeoNamesData = function(url) { this._url = url; this._loadPromise = null; this._data = []; this._events = new Events(); }; GeoNamesData.prototype.on = function() { return Events.prototype.on.apply(this._events, arguments); }; GeoNamesData.prototype.load = function() { if (!this._loadPromise) { this._events.emit('loading'); this._loadPromise = dom.loadJSON(this._url).then(function(data) { this._data = data; this._events.emit('loaded'); }.bind(this)); } return this._loadPromise; }; if (typeof module !== 'undefined' && module.exports) { module.exports = GeoNamesData; } else { app.GeoNamesData = GeoNamesData; } })(this.app || (this.app = {}));
Revert @Transactional annotation on findById(). The hint @Type(type = "org.hibernate.type.TextType") eliminates need for transactions on postgres when dealing with TEXT columns.
/* * * 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 writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ohdsi.webapi.cohortdefinition; import java.io.Serializable; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.Repository; /** * * @author cknoll1 */ public interface CohortDefinitionRepository extends CrudRepository<CohortDefinition, Integer> { Page<CohortDefinition> findAll(Pageable pageable); // Bug in hibernate, findById should use @EntityGraph, but details are not being feched. Workaround: mark details Fetch.EAGER, // but means findAll() will eager load definitions (what the @EntityGraph was supposed to solve) @EntityGraph(value = "CohortDefinition.withDetail", type = EntityGraph.EntityGraphType.LOAD) CohortDefinition findById(Integer id); }
/* * * 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 writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ohdsi.webapi.cohortdefinition; import java.io.Serializable; import javax.transaction.Transactional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.Repository; /** * * @author cknoll1 */ public interface CohortDefinitionRepository extends CrudRepository<CohortDefinition, Integer> { Page<CohortDefinition> findAll(Pageable pageable); // Bug in hibernate, findById should use @EntityGraph, but details are not being feched. Workaround: mark details Fetch.EAGER, // but means findAll() will eager load definitions (what the @EntityGraph was supposed to solve) @EntityGraph(value = "CohortDefinition.withDetail", type = EntityGraph.EntityGraphType.LOAD) @Transactional CohortDefinition findById(Integer id); }
Fix events drop down list
import PropTypes from 'prop-types'; import React from 'react'; import Select from '../select'; import { getY } from '../../index'; const choices = currentValue => () => new Promise(resolve => { const gmId = getY().Wegas.Facade.GameModel.cache.get('currentGameModelId'); getY().Wegas.Facade.GameModel.cache.sendRequest({ request: `/${gmId}/FindAllFiredEvents`, on: { success: e => { const events = e.response.entities; if (currentValue && events.indexOf(currentValue) < 0) { resolve(events.concat(currentValue).sort()); } else { resolve(events.sort()); } } } }); }); function EventSelect(props) { return <Select {...props} view={{ ...props.view, choices: choices(props.value) }} />; } EventSelect.propTypes = { value: PropTypes.string, view: PropTypes.object }; export default EventSelect;
import PropTypes from 'prop-types'; import React from 'react'; import Select from '../select'; import { getY } from '../../index'; const choices = currentValue => () => new Promise(resolve => { const gmId = getY().Wegas.Facade.GameModel.cache.get('currentGameModelId'); getY().Wegas.Facade.GameModel.cache.sendRequest({ request: `/${gmId}/FindAllFiredEvents`, on: { success: e => { const events = e.response.entities; if (events.indexOf(currentValue) < 0) { resolve(events.concat(currentValue).sort()); } else { resolve(events.sort()); } } } }); }); function EventSelect(props) { return <Select {...props} view={{ ...props.view, choices: choices(props.value) }} />; } EventSelect.propTypes = { value: PropTypes.string, view: PropTypes.object }; export default EventSelect;
Remove "-y" flag from apt-get upgrade
from fabric.api import * import subprocess __all__ = ['ssh', 'all', 'uptime', 'upgrade', 'restart'] @task def all(): """ Select all hosts """ env.hosts = [] for hosts in env.roledefs.values(): env.hosts.extend(hosts) # remove dupes env.hosts = list(set(env.hosts)) @task def uptime(): run('uptime') @task def upgrade(): """ Upgrade apt packages """ with settings(hide('stdout'), show('running')): sudo('apt-get update') sudo("apt-get upgrade") @task def ssh(*cmd): """ Open an interactive ssh session """ run = ['ssh', '-A', '-t'] if env.key_filename: run.extend(["-i", env.key_filename]) run.append('%s@%s' % (env.user, env.host_string)) run += cmd subprocess.call(run) @task def restart(service): """ Restart or start an upstart service """ with settings(warn_only=True): result = sudo('restart %s' % service) if result.failed: sudo('start %s' % service) @task def reboot(): """ Reboot a server """ run('reboot')
from fabric.api import * import subprocess __all__ = ['ssh', 'all', 'uptime', 'upgrade', 'restart'] @task def all(): """ Select all hosts """ env.hosts = [] for hosts in env.roledefs.values(): env.hosts.extend(hosts) # remove dupes env.hosts = list(set(env.hosts)) @task def uptime(): run('uptime') @task def upgrade(): """ Upgrade apt packages """ with settings(hide('stdout'), show('running')): sudo('apt-get update') sudo("apt-get upgrade -y") @task def ssh(*cmd): """ Open an interactive ssh session """ run = ['ssh', '-A', '-t'] if env.key_filename: run.extend(["-i", env.key_filename]) run.append('%s@%s' % (env.user, env.host_string)) run += cmd subprocess.call(run) @task def restart(service): """ Restart or start an upstart service """ with settings(warn_only=True): result = sudo('restart %s' % service) if result.failed: sudo('start %s' % service) @task def reboot(): """ Reboot a server """ run('reboot')
Enable more linting for shared imports
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Lint = require("tslint"); class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { return this.applyWithWalker(new NoNonSharedCode(sourceFile, this.getOptions())); } } Rule.DEBUG_FAILURE_STRING = "Do not import debugger code because it is expected to run in another process."; Rule.EXTENSION_FAILURE_STRING = "Do not import extension code because the extension packing will mean duplicate definitions and state."; class NoNonSharedCode extends Lint.RuleWalker { visitImportDeclaration(node) { // TODO: Remove first part of this condition when DAs are not running in process. // https://github.com/Dart-Code/Dart-Code/issues/1876 if (this.sourceFile.fileName.indexOf("debug_config_provider") === -1 && node.moduleSpecifier.text.indexOf("../debug/") !== -1) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.DEBUG_FAILURE_STRING)); } if (node.moduleSpecifier.text.indexOf("../extension/") !== -1) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.EXTENSION_FAILURE_STRING)); } } } exports.Rule = Rule;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Lint = require("tslint"); class Rule extends Lint.Rules.AbstractRule { apply(sourceFile) { if (sourceFile.fileName.indexOf("src/debug/") === -1) { return this.applyWithWalker(new NoNonSharedCode(sourceFile, this.getOptions())); } } } Rule.DEBUG_FAILURE_STRING = "Do not import debugger code because it is expected to run in another process."; Rule.EXTENSION_FAILURE_STRING = "Do not import extension code because the extension packing will mean duplicate definitions and state."; class NoNonSharedCode extends Lint.RuleWalker { visitImportDeclaration(node) { // TODO: Remove first part of this condition when DAs are not running in process. // https://github.com/Dart-Code/Dart-Code/issues/1876 if (this.sourceFile.fileName.indexOf("debug_config_provider") === -1 && node.moduleSpecifier.text.indexOf("../debug/") !== -1) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.DEBUG_FAILURE_STRING)); } if (node.moduleSpecifier.text.indexOf("../extension/") !== -1) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.EXTENSION_FAILURE_STRING)); } } } exports.Rule = Rule;
Remove unnecessary warning about mobile performance. Seems like the problem with my other presentations had more to do with CodeMirror than with reveal.js.
Reveal.addEventListener("ready", function() { var codes = document.querySelectorAll("code.javascript"); Array.prototype.forEach.call(codes, function (block) { hljs.highlightBlock(block); }); }); // Full list of configuration options available at: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, center: true, transition: 'none', // none/fade/slide/convex/concave/zoom // Optional reveal.js plugins dependencies: [{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/zoom-js/zoom.js', async: true }, { src: 'plugin/notes/notes.js', async: true }] });
var mobilePattern = /Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i; Reveal.addEventListener("ready", function() { var codes = document.querySelectorAll("code.javascript"); Array.prototype.forEach.call(codes, function (block) { hljs.highlightBlock(block); }); // hljs.initHighlightingOnLoad(); if (navigator.userAgent.match(mobilePattern)) { alert("Warning: this presentation is large and contains multitudes, so " + "mobile performance may be disappointing."); } }); // Full list of configuration options available at: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, center: true, transition: 'none', // none/fade/slide/convex/concave/zoom // Optional reveal.js plugins dependencies: [{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/zoom-js/zoom.js', async: true }, { src: 'plugin/notes/notes.js', async: true }] });
Simplify logic since time.Date is benevolent
package next import ( "time" ) // Minute returns a time.Time referencing the beginning of the next minute func Minute(t time.Time) time.Time { return t.Add(time.Minute).Truncate(time.Minute) } // Hour returns a time.Time referencing the beginning of the next hour func Hour(t time.Time) time.Time { return t.Add(time.Hour).Truncate(time.Hour) } // Day returns a time.Time referencing the beginning of the next day func Day(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, t.Location()) } // Week returns a time.Time referencing the beginning of the next week Sun->Sat func Week(t time.Time) time.Time { weekRemainder := 7 - int(t.Weekday()) return time.Date(t.Year(), t.Month(), t.Day()+weekRemainder, 0, 0, 0, 0, t.Location()) } // Month returns a time.Time referencing the beginning of the next month func Month(t time.Time) time.Time { // truncate starting time back to beginning of the month return time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, t.Location()) }
package next import ( "time" ) // Minute returns a time.Time referencing the beginning of the next minute func Minute(t time.Time) time.Time { return t.Add(time.Minute).Truncate(time.Minute) } // Hour returns a time.Time referencing the beginning of the next hour func Hour(t time.Time) time.Time { return t.Add(time.Hour).Truncate(time.Hour) } // Day returns a time.Time referencing the beginning of the next day func Day(t time.Time) time.Time { t = t.AddDate(0, 0, 1) return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) } // Week returns a time.Time referencing the beginning of the next week Sun->Sat func Week(t time.Time) time.Time { weekRemainder := 7 - int(t.Weekday()) nextWeek := t.AddDate(0, 0, weekRemainder) return time.Date(nextWeek.Year(), nextWeek.Month(), nextWeek.Day(), 0, 0, 0, 0, t.Location()) } // Month returns a time.Time referencing the beginning of the next month func Month(t time.Time) time.Time { // truncate starting time back to beginning of the month t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) return t.AddDate(0, 1, 0) }
Fix section end tag in Blade view.
@extends('fluxbb::layout.main') @section('main') {{-- TODO: Escape all the variables!!! --}} <ul> @foreach ($categories as $cat_info) <?php $category = $cat_info['category']; ?> <li> {{ $category->cat_name }} <ul> @foreach ($cat_info['forums'] as $forum) <li> <a href="{{ URL::action('fluxbb::home@forum', array($forum->id)) }}">{{ $forum->forum_name }}</a> <em class="forumdesc">{{ $forum->forum_desc }}</em> <ul> <li>{{ $forum->numTopics() }} topics</li> <li>{{ $forum->numPosts() }} posts</li> </ul> </li> @endforeach </ul> </li> @endforeach </ul> @stop
@extends('fluxbb::layout.main') @section('main') {{-- TODO: Escape all the variables!!! --}} <ul> @foreach ($categories as $cat_info) <?php $category = $cat_info['category']; ?> <li> {{ $category->cat_name }} <ul> @foreach ($cat_info['forums'] as $forum) <li> <a href="{{ URL::action('fluxbb::home@forum', array($forum->id)) }}">{{ $forum->forum_name }}</a> <span class="forumdesc">{{ $forum->forum_desc }}</span> <ul> <li>{{ $forum->numTopics() }} topics</li> <li>{{ $forum->numPosts() }} posts</li> </ul> </li> @endforeach </ul> </li> @endforeach </ul> @endsection
Add warning to widget namespace import.
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from IPython.utils.warn import warn warn("""The widget API is still considered experimental and may change by the next major release of IPython.""")
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget
Set file open to enforce utf8
import sys from tinydb import TinyDB, where import markdown2 articles_db = TinyDB("data/articles.json") def get_all_articles(): return articles_db.all() def get_article_data_by_url(url: str): results = articles_db.search(where("url") == url) if len(results) == 0: raise FileNotFoundError("Error: no article with url " + url) elif len(results) == 1: return results[0] else: # TODO handle multiple results case return results[0] def get_article_html(url: str): info = get_article_data_by_url(url) html = None if "html" in info: html = get_contents(info["html"]) elif "markdown" in info: markdown = get_contents(info["markdown"]) html = markdown2.markdown(markdown) return html def get_contents(filename: str): contents = None with open("data/articles/" + filename, "r", encoding="utf8") as file: contents = file.read() return contents
import sys from tinydb import TinyDB, where import markdown2 articles_db = TinyDB("data/articles.json") def get_all_articles(): return articles_db.all() def get_article_data_by_url(url: str): results = articles_db.search(where("url") == url) if len(results) == 0: raise FileNotFoundError("Error: no article with url " + url) elif len(results) == 1: return results[0] else: # TODO handle multiple results case return results[0] def get_article_html(url: str): info = get_article_data_by_url(url) html = None if "html" in info: html = get_contents(info["html"]) elif "markdown" in info: markdown = get_contents(info["markdown"]) html = markdown2.markdown(markdown) return html def get_contents(filename: str): contents = None with open("data/articles/" + filename) as file: contents = file.read() return contents
Update default stargazers in demo
import fetch from 'isomorphic-fetch'; const LOAD_STARGAZERS_SUCCESS = 'LOAD_STARGAZERS_SUCCESS'; const initialState = { stargazers: '975' }; export function loadStargazers() { return dispatch => { fetch('https://api.github.com/repos/moroshko/react-autosuggest') .then(response => response.json()) .then(response => { dispatch({ type: LOAD_STARGAZERS_SUCCESS, stargazers: String(response.stargazers_count) }); }); }; } export default function reducer(state = initialState, action = {}) { switch (action.type) { case LOAD_STARGAZERS_SUCCESS: return { ...state, stargazers: action.stargazers }; default: return state; } }
import fetch from 'isomorphic-fetch'; const LOAD_STARGAZERS_SUCCESS = 'LOAD_STARGAZERS_SUCCESS'; const initialState = { stargazers: '815' }; export function loadStargazers() { return dispatch => { fetch('https://api.github.com/repos/moroshko/react-autosuggest') .then(response => response.json()) .then(response => { dispatch({ type: LOAD_STARGAZERS_SUCCESS, stargazers: String(response.stargazers_count) }); }); }; } export default function reducer(state = initialState, action = {}) { switch (action.type) { case LOAD_STARGAZERS_SUCCESS: return { ...state, stargazers: action.stargazers }; default: return state; } }
Add ‘age’ to post content
"use strict"; var user = module.parent.require('./user'), db = module.parent.require('./database'), plugin = {}; plugin.init = function(params, callback) { var app = params.router, middleware = params.middleware, controllers = params.controllers; app.get('/admin/custom-topics', middleware.admin.buildHeader, renderAdmin); app.get('/api/admin/custom-topics', renderAdmin); callback(); }; plugin.addAdminNavigation = function(header, callback) { header.plugins.push({ route: '/custom-topics', icon: 'fa-tint', name: 'Custom Topics' }); callback(null, header); }; plugin.onTopicCreate = function(data, callback) { console.log("Topic created!"); // data.topic, this is the topic that will be saved to the database // data.data, this is the data that is submitted from the client side // Now all you have to do is validate `data.myCustomField` and set it in data.topic. if (data.data.age) { data.data.content += '<b>Age: </b>' + data.data.age + '</br>'; } console.dir(data); callback(null, data); }; function renderAdmin(req, res, next) { res.render('admin/custom-topics', {}); } module.exports = plugin;
"use strict"; var user = module.parent.require('./user'), db = module.parent.require('./database'), plugin = {}; plugin.init = function(params, callback) { var app = params.router, middleware = params.middleware, controllers = params.controllers; app.get('/admin/custom-topics', middleware.admin.buildHeader, renderAdmin); app.get('/api/admin/custom-topics', renderAdmin); callback(); }; plugin.addAdminNavigation = function(header, callback) { header.plugins.push({ route: '/custom-topics', icon: 'fa-tint', name: 'Custom Topics' }); callback(null, header); }; plugin.onTopicCreate = function(data, callback) { console.log("Topic created!"); // data.topic, this is the topic that will be saved to the database // data.data, this is the data that is submitted from the client side // Now all you have to do is validate `data.myCustomField` and set it in data.topic. if (data.data.age) { data.topic.age = data.data.age; } console.dir(data); callback(null, data); }; function renderAdmin(req, res, next) { res.render('admin/custom-topics', {}); } module.exports = plugin;
Remove leftovers after logic cleanup
'use strict'; module.exports = function () { var map, iterator, result; if (typeof Map !== 'function') return false; if (String(Map.prototype) !== '[object Map]') return false; try { // WebKit doesn't support arguments and crashes map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); } catch (e) { return false; } if (map.size !== 3) return false; if (typeof map.clear !== 'function') return false; if (typeof map.delete !== 'function') return false; if (typeof map.entries !== 'function') return false; if (typeof map.forEach !== 'function') return false; if (typeof map.get !== 'function') return false; if (typeof map.has !== 'function') return false; if (typeof map.keys !== 'function') return false; if (typeof map.set !== 'function') return false; if (typeof map.values !== 'function') return false; iterator = map.entries(); result = iterator.next(); if (result.done !== false) return false; if (!result.value) return false; if (result.value[0] !== 'raz') return false; if (result.value[1] !== 'one') return false; return true; };
'use strict'; module.exports = function () { var map, iterator, result; if (typeof Map !== 'function') return false; if (String(Map.prototype) !== '[object Map]') return false; try { // WebKit doesn't support arguments and crashes map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); } catch (e) { return false; } if (map.size !== 3) return false; if (typeof map.clear !== 'function') return false; if (typeof map.delete !== 'function') return false; if (typeof map.entries !== 'function') return false; if (typeof map.forEach !== 'function') return false; if (typeof map.get !== 'function') return false; if (typeof map.has !== 'function') return false; if (typeof map.keys !== 'function') return false; if (typeof map.set !== 'function') return false; if (typeof map.values !== 'function') return false; iterator = map.entries(); result = iterator.next(); if (result.done !== false) return false; if (!result.value) return false; if (result.value[0] !== 'raz') return false; if (result.value[1] !== 'one') return false; if (!map) return false; if (map.size !== 3) return false; return true; };
Fix help and make version an alias of bump
#!/usr/bin/env node process.title = 'fusepm' var program = require('commander'); var install = require('../lib/install'); var bump = require('../lib/bump'); var fixunoproj = require('../lib/fixunoproj'); var fusepm = require('../lib/fusepm'); var fpm_npm = require('../lib/npm'); program .version(require('../package.json').version) .option('-p, --unoproj [filename]', 'Specify .unoproj file') program .command('install <module>') .description('install fuse module') .action(install); program .command('bump <release>') .description('bump version') .action(bump); program .command('version <release>', null, { noHelp: true }) .description('bump version') .action(bump); program .command('fixunoproj') .description('fix the unoproj') .action(fixunoproj); program .command('npm <module...>') .description('make npm module(s) ready for fuse (experimental)') .option('--ignore-missing', 'ignore missing depdencies for require') .action(fpm_npm); program .command('*', null, { noHelp: 1 }) .action(function () { program.help() }) fusepm.set_commander(program); program .parse(process.argv); if (!process.argv.slice(2).length) { program.help(); }
#!/usr/bin/env node process.title = 'fusepm' var program = require('commander'); var install = require('../lib/install'); var bump = require('../lib/bump'); var fixunoproj = require('../lib/fixunoproj'); var fusepm = require('../lib/fusepm'); var fpm_npm = require('../lib/npm'); program .version(require('../package.json').version) .option('-p, --unoproj [filename]', 'Specify .unoproj file') program .command('install <module>') .description('install fuse module') .action(install); program .command('bump <release>') .description('bump version') .action(bump); program .command('fixunoproj') .description('fix the unoproj') .action(fixunoproj); program .command('npm <module...>') .description('make npm module(s) ready for fuse (experimental)') .option('--ignore-missing', 'Ignore missing depdencies for require') .action(fpm_npm); program .command('*', null, { noHelp: 1 }) .action(function () { program.help() }) fusepm.set_commander(program); program .parse(process.argv); if (!process.argv.slice(2).length) { program.help(); }
Set log level to 'WARN'
# Configuration file for jupyterhub. #------------------------------------------------------------------------------ # Configurable configuration #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # JupyterHub configuration #------------------------------------------------------------------------------ # An Application for starting a Multi-User Jupyter Notebook server. # The public facing ip of the proxy c.JupyterHub.ip = '127.0.0.1' # The ip for the proxy API handlers c.JupyterHub.proxy_api_ip = '127.0.0.1' # The public facing port of the proxy c.JupyterHub.port = 9510 # The base URL of the entire application c.JupyterHub.base_url = '/jupyterhub' # The ip for this process c.JupyterHub.hub_ip = '127.0.0.1' # put the log file in /var/log c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log' c.JupyterHub.log_level = 'WARN' #------------------------------------------------------------------------------ # Spawner configuration #------------------------------------------------------------------------------ # The IP address (or hostname) the single-user server should listen on c.Spawner.ip = '127.0.0.1' #------------------------------------------------------------------------------ # Authenticator configuration #------------------------------------------------------------------------------ # A class for authentication. # # The API is one method, `authenticate`, a tornado gen.coroutine. # set of usernames of admin users # # If unspecified, only the user that launches the server will be admin. c.Authenticator.admin_users = {'root', 'ubuntu'}
# Configuration file for jupyterhub. #------------------------------------------------------------------------------ # Configurable configuration #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # JupyterHub configuration #------------------------------------------------------------------------------ # An Application for starting a Multi-User Jupyter Notebook server. # The public facing ip of the proxy c.JupyterHub.ip = '127.0.0.1' # The ip for the proxy API handlers c.JupyterHub.proxy_api_ip = '127.0.0.1' # The public facing port of the proxy c.JupyterHub.port = 9510 # The base URL of the entire application c.JupyterHub.base_url = '/jupyterhub' # The ip for this process c.JupyterHub.hub_ip = '127.0.0.1' # put the log file in /var/log c.JupyterHub.extra_log_file = '/var/log/jupyterhub.log' #------------------------------------------------------------------------------ # Spawner configuration #------------------------------------------------------------------------------ # The IP address (or hostname) the single-user server should listen on c.Spawner.ip = '127.0.0.1' #------------------------------------------------------------------------------ # Authenticator configuration #------------------------------------------------------------------------------ # A class for authentication. # # The API is one method, `authenticate`, a tornado gen.coroutine. # set of usernames of admin users # # If unspecified, only the user that launches the server will be admin. c.Authenticator.admin_users = {'root', 'ubuntu'}
interstellar: Fix reversed grid width/height segment counts.
/*exported Grid*/ var Grid = (function() { 'use strict'; function create( options, callback ) { options = options || {}; var size = options.size || 512; var width = options.width || size; var height = options.height || size; var segments = options.segments || 2; var widthSegments = options.widthSegments || segments; var heightSegments = options.heightSegments || segments; var segmentWidth = width / widthSegments; var segmentHeight = height / heightSegments; var canvas = options.canvas || document.createElement( 'canvas' ); var ctx = canvas.getContext( '2d' ); canvas.width = width; canvas.height = height; var x, y; for ( y = 0; y < heightSegments; y++ ) { for ( x = 0; x < widthSegments; x++ ) { ctx.fillStyle = callback( x, y ); ctx.fillRect( x * segmentWidth, y * segmentHeight, segmentWidth, segmentHeight ); } } return canvas; } function checkerboard( options ) { var colors = options.colors || []; return create( options, function( x, y ) { var index = ( x + y ) % colors.length; return colors[ index ]; }); } return { create: create, checkerboard: checkerboard }; }) ();
/*exported Grid*/ var Grid = (function() { 'use strict'; function create( options, callback ) { options = options || {}; var size = options.size || 512; var width = options.width || size; var height = options.height || size; var segments = options.segments || 2; var widthSegments = options.widthSegments || segments; var heightSegments = options.heightSegments || segments; var segmentWidth = width / widthSegments; var segmentHeight = height / heightSegments; var canvas = options.canvas || document.createElement( 'canvas' ); var ctx = canvas.getContext( '2d' ); canvas.width = width; canvas.height = height; var x, y; for ( y = 0; y < widthSegments; y++ ) { for ( x = 0; x < heightSegments; x++ ) { ctx.fillStyle = callback( x, y ); ctx.fillRect( x * segmentWidth, y * segmentHeight, segmentWidth, segmentHeight ); } } return canvas; } function checkerboard( options ) { var colors = options.colors || []; return create( options, function( x, y ) { var index = ( x + y ) % colors.length; return colors[ index ]; }); } return { create: create, checkerboard: checkerboard }; }) ();
Fix calling without query throws TypeError
/* * @license MIT http://www.opensource.org/licenses/mit-license.php * @author Hovhannes Babayan <bhovhannes at gmail dot com> */ var loaderUtils = require('loader-utils'); module.exports = function(content) { this.cacheable && this.cacheable(); var query = loaderUtils.getOptions(this) || {}; var limit = query.limit ? parseInt(query.limit, 10) : 0; if (limit <= 0 || content.length < limit) { content = content.toString('utf8'); if (query.stripdeclarations) { content = content.replace(/^\s*<\?xml [^>]*>\s*/i, ""); } content = content.replace(/"/g, "'"); content = content.replace(/\s+/g, " "); content = content.replace(/[{}\|\\\^~\[\]`"<>#%]/g, function(match) { return '%'+match[0].charCodeAt(0).toString(16).toUpperCase(); }); var data = 'data:image/svg+xml,' + content.trim(); if (!query.noquotes) { data = '"'+data+'"'; } return 'module.exports = ' + JSON.stringify(data); } else { var fileLoader = require('file-loader'); return fileLoader.call(this, content); } }; module.exports.raw = true;
/* * @license MIT http://www.opensource.org/licenses/mit-license.php * @author Hovhannes Babayan <bhovhannes at gmail dot com> */ var loaderUtils = require('loader-utils'); module.exports = function(content) { this.cacheable && this.cacheable(); var query = loaderUtils.getOptions(this); var limit = query.limit ? parseInt(query.limit, 10) : 0; if (limit <= 0 || content.length < limit) { content = content.toString('utf8'); if (query.stripdeclarations) { content = content.replace(/^\s*<\?xml [^>]*>\s*/i, ""); } content = content.replace(/"/g, "'"); content = content.replace(/\s+/g, " "); content = content.replace(/[{}\|\\\^~\[\]`"<>#%]/g, function(match) { return '%'+match[0].charCodeAt(0).toString(16).toUpperCase(); }); var data = 'data:image/svg+xml,' + content.trim(); if (!query.noquotes) { data = '"'+data+'"'; } return 'module.exports = ' + JSON.stringify(data); } else { var fileLoader = require('file-loader'); return fileLoader.call(this, content); } }; module.exports.raw = true;
Add support for server side authentication. Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e Reviewed-on: http://review.pozytywnie.pl:8080/5087 Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com> Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
from uuid import uuid1 from django.conf import settings from django.contrib.auth import models as auth_models from django.db import models import facepy import simplejson from facebook_auth import utils class FacebookUser(auth_models.User): user_id = models.BigIntegerField(unique=True) access_token = models.TextField(blank=True, null=True) app_friends = models.ManyToManyField('self') @property def graph(self): return facepy.GraphAPI(self.access_token) @property def js_session(self): return simplejson.dumps({ 'access_token': self.access_token, 'uid': self.user_id }) @property def friends(self): return utils.get_from_graph_api(self.graph, "me/friends")['data'] def update_app_friends(self): friends = self.friends friends_ids = [f['id'] for f in friends] self.app_friends.clear() self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids)) def get_auth_address(request, redirect_to, scope=''): state = unicode(uuid1()) request.session['state'] = state return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % ( settings.FACEBOOK_APP_ID, redirect_to, scope, state )
from django.contrib.auth import models as auth_models from django.db import models import facepy import simplejson from facebook_auth import utils class FacebookUser(auth_models.User): user_id = models.BigIntegerField(unique=True) access_token = models.TextField(blank=True, null=True) app_friends = models.ManyToManyField('self') @property def graph(self): return facepy.GraphAPI(self.access_token) @property def js_session(self): return simplejson.dumps({ 'access_token': self.access_token, 'uid': self.user_id }) @property def friends(self): return utils.get_from_graph_api(self.graph, "me/friends")['data'] def update_app_friends(self): friends = self.friends friends_ids = [f['id'] for f in friends] self.app_friends.clear() self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
Make sure we test the right binary
#!/usr/bin/env python # -*- encoding: utf-8 import collections import os import subprocess import unittest Result = collections.namedtuple('Result', 'rc stdout stderr') ROOT = subprocess.check_output([ 'git', 'rev-parse', '--show-toplevel']).decode('ascii').strip() BINARY = os.path.join(ROOT, 'target', 'release', 'safari') subprocess.check_call(['cargo', 'build', '--release'], cwd=ROOT) class BaseTest(unittest.TestCase): def run_safari_rs(self, *args): proc = subprocess.Popen([BINARY] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = proc.communicate() return Result( rc=proc.returncode, stdout=stdout.decode('ascii'), stderr=stderr.decode('ascii') )
#!/usr/bin/env python # -*- encoding: utf-8 import collections import os import subprocess import unittest Result = collections.namedtuple('Result', 'rc stdout stderr') ROOT = subprocess.check_output([ 'git', 'rev-parse', '--show-toplevel']).decode('ascii').strip() BINARY = os.path.join(ROOT, 'target', 'debug', 'safari') subprocess.check_call(['cargo', 'build', '--release'], cwd=ROOT) class BaseTest(unittest.TestCase): def run_safari_rs(self, *args): proc = subprocess.Popen([BINARY] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = proc.communicate() return Result( rc=proc.returncode, stdout=stdout.decode('ascii'), stderr=stderr.decode('ascii') )
Add a few asserts to the test
package org.xbean.jmx; import junit.framework.TestCase; import org.xbean.spring.context.ClassPathXmlApplicationContext; import java.util.List; /** * $Rev$ */ public class JMXTest extends TestCase { public void testSimple() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/xbean/jmx/jmx-simple.xml"); try { Object jmxService = context.getBean("jmxService"); assertNotNull(jmxService); Object jmxExporter = context.getBean("jmxExporter"); assertNotNull(jmxExporter); assertTrue(jmxExporter instanceof MBeanExporter); List mbeans = ((MBeanExporter) jmxExporter).getMBeans(); assertNotNull(mbeans); assertEquals(2, mbeans.size()); assertSame(jmxService, mbeans.get(0)); assertSame(jmxService, mbeans.get(1)); } finally { context.destroy(); } } }
package org.xbean.jmx; import junit.framework.TestCase; import org.xbean.spring.context.ClassPathXmlApplicationContext; /** * $Rev$ */ public class JMXTest extends TestCase { public void testSimple() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("org/xbean/jmx/jmx-simple.xml"); try { Object jmxService = context.getBean("jmxService"); assertNotNull(jmxService); Object jmxExporter = context.getBean("jmxExporter"); assertNotNull(jmxExporter); } finally { context.destroy(); } } }
Remove not needed double semicolon
package org.synyx.urlaubsverwaltung.security; import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; public class LoginControllerTest { private LoginController sut; private static final String APPLICATION_VERSION = "1.1.1"; @Before public void setUp() { sut = new LoginController(APPLICATION_VERSION); } @Test public void ensureLoginHasCorrectVersionAndView() throws Exception { perform(get("/login")) .andExpect(model().attribute("version", equalTo(APPLICATION_VERSION))) .andExpect(view().name("login/login")); } private ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception { return standaloneSetup(sut).build().perform(builder); } }
package org.synyx.urlaubsverwaltung.security; import org.junit.Before; import org.junit.Test; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; public class LoginControllerTest { private LoginController sut; private static final String APPLICATION_VERSION = "1.1.1"; @Before public void setUp() { sut = new LoginController(APPLICATION_VERSION); } @Test public void ensureLoginHasCorrectVersionAndView() throws Exception { perform(get("/login")) .andExpect(model().attribute("version", equalTo(APPLICATION_VERSION))) .andExpect(view().name("login/login")); ; } private ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception { return standaloneSetup(sut).build().perform(builder); } }
Disable SQL logging from DAO tests Was polluting the Travis CI logs
package org.coner.core.hibernate.dao; import io.dropwizard.testing.junit.DAOTestRule; abstract class AbstractDaoTest { DAOTestRule.Builder daoTestRuleBuilder; AbstractDaoTest() { daoTestRuleBuilder = DAOTestRule.newBuilder() .setDriver(org.hsqldb.jdbc.JDBCDriver.class) .setUrl("jdbc:hsqldb:mem:coner-" + getClass().getSimpleName()) .setShowSql(false) .useSqlComments(true); } DAOTestRule.Builder getDaoTestRuleBuilder() { return daoTestRuleBuilder; } }
package org.coner.core.hibernate.dao; import io.dropwizard.testing.junit.DAOTestRule; abstract class AbstractDaoTest { DAOTestRule.Builder daoTestRuleBuilder; AbstractDaoTest() { daoTestRuleBuilder = DAOTestRule.newBuilder() .setDriver(org.hsqldb.jdbc.JDBCDriver.class) .setUrl("jdbc:hsqldb:mem:coner-" + getClass().getSimpleName()) .setShowSql(true) .useSqlComments(true); } DAOTestRule.Builder getDaoTestRuleBuilder() { return daoTestRuleBuilder; } }
Add statement to check if fennec_ids are set in the request
<?php namespace AppBundle\API\Details; use AppBundle\Entity\FennecUser; use AppBundle\Service\DBVersion; use Symfony\Component\HttpFoundation\ParameterBag; use AppBundle\Entity\Organism; /** * Web Service. * Returns trait information to a list of organism ids */ class TraitsOfOrganisms { private $manager; /** * TraitsOfOrganisms constructor. * @param $dbversion */ public function __construct(DBVersion $dbversion) { $this->manager = $dbversion->getEntityManager(); } /** * @param 'fennec_ids' => [13,7,12,5] * @returns array $result * <code> * array(type_cvterm_id => array( * 'trait_type' => 'habitat', * 'trait_entry_ids' => array(1, 20, 36, 7), * 'fennec_ids' => array(13, 20, 5) * ); * </code> */ public function execute($fennec_ids) { if(isset($_REQUEST['fennec_ids'])){ $fennec_ids = $_REQUEST['fennec_ids']; } return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids); } }
<?php namespace AppBundle\API\Details; use AppBundle\Entity\FennecUser; use AppBundle\Service\DBVersion; use Symfony\Component\HttpFoundation\ParameterBag; use AppBundle\Entity\Organism; /** * Web Service. * Returns trait information to a list of organism ids */ class TraitsOfOrganisms { private $manager; /** * TraitsOfOrganisms constructor. * @param $dbversion */ public function __construct(DBVersion $dbversion) { $this->manager = $dbversion->getEntityManager(); } /** * @param 'fennec_ids' => [13,7,12,5] * @returns array $result * <code> * array(type_cvterm_id => array( * 'trait_type' => 'habitat', * 'trait_entry_ids' => array(1, 20, 36, 7), * 'fennec_ids' => array(13, 20, 5) * ); * </code> */ public function execute($fennec_ids) { return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids); } }
Fix regex for win32 platform
'use strict'; /* global require */ /* global process */ var fs = require ('fs'); var path = require ('path'); var mkdirSync = function (path) { try { fs.mkdirSync (path); } catch (e) { if (e.code !== 'EEXIST') { throw e; } } }; var cwd = process.cwd ().replace (/\\/g, '/'); var suffix = '/node_modules/mai-chai'; if (cwd.endsWith (suffix)) { var root = cwd.substr (0, cwd.length - suffix.length); var test = path.join (root, 'test'); var files = fs.readdirSync (path.join (cwd, 'templates')); mkdirSync (test); mkdirSync (path.join (root, 'src')); mkdirSync (path.join (root, 'src.test')); var regex = /\r\n/g; var newline = '\n'; if (process.platform === 'win32') { regex = /([^\r])\n/g; newline = '$1\r\n'; } files.forEach (function (file) { var data = fs.readFileSync (path.join (cwd, 'templates', file)); if (file.substr (0, 2) === '--') { var name = file.substr (2, file.length - 2); fs.writeFileSync (path.join (root, name), data.toString ().replace (regex, newline)); } else { fs.writeFileSync (path.join (test, file), data.toString ().replace (regex, newline)); } }); }
'use strict'; /* global require */ /* global process */ var fs = require ('fs'); var path = require ('path'); var mkdirSync = function (path) { try { fs.mkdirSync (path); } catch (e) { if (e.code !== 'EEXIST') { throw e; } } }; var cwd = process.cwd ().replace (/\\/g, '/'); var suffix = '/node_modules/mai-chai'; if (cwd.endsWith (suffix)) { var root = cwd.substr (0, cwd.length - suffix.length); var test = path.join (root, 'test'); var files = fs.readdirSync (path.join (cwd, 'templates')); mkdirSync (test); mkdirSync (path.join (root, 'src')); mkdirSync (path.join (root, 'src.test')); var regex = /\r\n/g; var newline = '\n'; if (process.platform === 'win32') { regex = /[^\r]\n/g; newline = '\r\n'; } files.forEach (function (file) { var data = fs.readFileSync (path.join (cwd, 'templates', file)); if (file.substr (0, 2) === '--') { var name = file.substr (2, file.length - 2); fs.writeFileSync (path.join (root, name), data.toString ().replace (regex, newline)); } else { fs.writeFileSync (path.join (test, file), data.toString ().replace (regex, newline)); } }); }
Add a warning message for Edge
import _ from 'underscore'; import UAParser from 'ua-parser-js'; import View from '../view'; import BrowserAlertTemplate from './browserAlert.pug'; import './browserAlert.styl'; const BrowserAlertView = View.extend({ className: 'isic-browser-alert', initialize: function (settings) { this.currentBrowserName = (new UAParser()).getBrowser().name; this.unsupportedBrowsers = [ 'Edge', 'IE', 'Safari' ]; }, render: function () { if (_.contains(this.unsupportedBrowsers, this.currentBrowserName)) { this.$el.html(BrowserAlertTemplate()); } return this; } }); export default BrowserAlertView;
import _ from 'underscore'; import UAParser from 'ua-parser-js'; import View from '../view'; import BrowserAlertTemplate from './browserAlert.pug'; import './browserAlert.styl'; const BrowserAlertView = View.extend({ className: 'isic-browser-alert', initialize: function (settings) { this.currentBrowserName = (new UAParser()).getBrowser().name; this.unsupportedBrowsers = [ 'IE', 'Safari' ]; }, render: function () { if (_.contains(this.unsupportedBrowsers, this.currentBrowserName)) { this.$el.html(BrowserAlertTemplate()); } return this; } }); export default BrowserAlertView;
Rename 'engine' fixture to 'test_engine'
import pytest from sqlalchemy import text from sqlalchemy.exc import ProgrammingError from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from virtool.models import Base @pytest.fixture(scope="function") async def test_engine(): engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT") async with engine.connect() as conn: try: await conn.execute(text("CREATE DATABASE test")) except ProgrammingError: pass return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test") @pytest.fixture(scope="function") async def test_session(test_engine, loop): async with test_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) session = AsyncSession(bind=test_engine) yield session async with test_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await session.close()
import pytest from sqlalchemy import text from sqlalchemy.exc import ProgrammingError from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from sqlalchemy.ext.asyncio import AsyncSession from virtool.models import Base @pytest.fixture(scope="function") async def engine(): engine = create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/virtool", isolation_level="AUTOCOMMIT") async with engine.connect() as conn: try: await conn.execute(text("CREATE DATABASE test")) except ProgrammingError: pass return create_async_engine("postgresql+asyncpg://virtool:virtool@postgres/test") @pytest.fixture(scope="function") async def dbsession(engine, loop): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) session = AsyncSession(bind=engine) yield session async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await session.close()
Fix auth views : use class-based views
# -*- coding: utf-8 -*- """urls""" from __future__ import unicode_literals from django.conf.urls import include, url from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordResetView, PasswordResetConfirmView from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm urlpatterns = [ url( r'^login/$', LoginView.as_view(authentication_form=EmailAuthForm), name='login' ), url(r'^password_change/$', PasswordChangeView.as_view(form_class=BsPasswordChangeForm), name='password_change' ), url( r'^password_reset/$', PasswordResetView.as_view(form_class=BsPasswordResetForm), name='password_reset' ), url( r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(form_class=BsSetPasswordForm), name='password_reset_confirm' ), url(r'^', include('django.contrib.auth.urls')), ]
# -*- coding: utf-8 -*- """urls""" from __future__ import unicode_literals from django.conf.urls import include, url from django.contrib.auth.views import login, password_change, password_reset, password_reset_confirm from coop_cms.apps.email_auth.forms import BsPasswordChangeForm, BsPasswordResetForm, EmailAuthForm, BsSetPasswordForm urlpatterns = [ url( r'^login/$', login, {'authentication_form': EmailAuthForm}, name='login' ), url(r'^password_change/$', password_change, {'password_change_form': BsPasswordChangeForm}, name='password_change' ), url( r'^password_reset/$', password_reset, {'password_reset_form': BsPasswordResetForm}, name='password_reset' ), url( r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'set_password_form': BsSetPasswordForm}, name='password_reset_confirm' ), url(r'^', include('django.contrib.auth.urls')), ]
Revert "opens README.md in utf-8 encoding" This reverts commit f73fd446dc9b953c57c773f21744616265adc754.
from setuptools import setup setup( name='unicode-slugify', version='0.1.3', description='A slug generator that turns strings into unicode slugs.', long_description=open('README.md').read(), author='Jeff Balogh, Dave Dash', author_email='jbalogh@mozilla.com, dd@mozilla.com', url='http://github.com/mozilla/unicode-slugify', license='BSD', packages=['slugify'], include_package_data=True, package_data={'': ['README.md']}, zip_safe=False, install_requires=['six', 'unidecode'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Environment :: Web Environment :: Mozilla', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
from setuptools import setup setup( name='unicode-slugify', version='0.1.3', description='A slug generator that turns strings into unicode slugs.', long_description=open('README.md', encoding='utf-8').read(), author='Jeff Balogh, Dave Dash', author_email='jbalogh@mozilla.com, dd@mozilla.com', url='http://github.com/mozilla/unicode-slugify', license='BSD', packages=['slugify'], include_package_data=True, package_data={'': ['README.md']}, zip_safe=False, install_requires=['six', 'unidecode'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Environment :: Web Environment :: Mozilla', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Change url to point to tagged release
"""Setup for pymd5 module and command-line script.""" from setuptools import setup def readme(): """Use text contained in README.rst as long description.""" with open('README.rst') as desc: return desc.read() setup(name='pymd5', version='0.1', description=('Recursively calculate and display MD5 file hashes ' 'for all files rooted in a directory.'), long_description=readme(), url='https://github.com/richmilne/pymd5/releases/tag/v0.1', author='Richard Milne', author_email='richmilne@hotmail.com', license='MIT', packages=['pymd5'], include_package_data=True, entry_points={ 'console_scripts': ['pymd5=pymd5:_read_args'] }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
"""Setup for pymd5 module and command-line script.""" from setuptools import setup def readme(): """Use text contained in README.rst as long description.""" with open('README.rst') as desc: return desc.read() setup(name='pymd5', version='0.1', description=('Recursively calculate and display MD5 file hashes ' 'for all files rooted in a directory.'), long_description=readme(), url='https://github.com/richmilne/pymd5', author='Richard Milne', author_email='richmilne@hotmail.com', license='MIT', packages=['pymd5'], include_package_data=True, entry_points={ 'console_scripts': ['pymd5=pymd5:_read_args'] }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Use Lanczos2Lut for the native resize test This should make the native method a bit faster
package magick import ( "github.com/nfnt/resize" "image" _ "image/png" "os" "testing" ) func BenchmarkResizePng(b *testing.B) { im := decodeFile(b, "wizard.png") b.ResetTimer() for ii := 0; ii < b.N; ii++ { _, _ = im.Resize(240, 180, FLanczos) } } func BenchmarkResizePngNative(b *testing.B) { f, err := os.Open("test_data/wizard.png") if err != nil { b.Fatal(err) } defer f.Close() im, _, err := image.Decode(f) if err != nil { b.Fatal(err) } b.ResetTimer() for ii := 0; ii < b.N; ii++ { _ = resize.Resize(240, 180, im, resize.Lanczos2Lut) } }
package magick import ( "github.com/nfnt/resize" "image" _ "image/png" "os" "testing" ) func BenchmarkResizePng(b *testing.B) { im := decodeFile(b, "wizard.png") b.ResetTimer() for ii := 0; ii < b.N; ii++ { _, _ = im.Resize(240, 180, FLanczos) } } func BenchmarkResizePngNative(b *testing.B) { f, err := os.Open("test_data/wizard.png") if err != nil { b.Fatal(err) } defer f.Close() im, _, err := image.Decode(f) if err != nil { b.Fatal(err) } b.ResetTimer() for ii := 0; ii < b.N; ii++ { _ = resize.Resize(240, 180, im, resize.Lanczos2) } }
Add managing of _id field
'use strict'; var async = require("async"); function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } module.exports = function seeder(seedObject, mongoose, logger, cb) { if(!cb) { cb = logger; logger = console.log; } var ObjectId = mongoose.Types.ObjectId; async.each(Object.keys(seedObject), function(mongoModel, cb) { var documents = seedObject[mongoModel]; var mongoModelName = capitalize(mongoModel); var Model = mongoose.model(mongoModelName); async.each(Object.keys(documents), function(_id, cb) { var document = documents[_id]; if(document._id) { _id = document._id; } // Fake an upsert call, to keep the hooks Model.findById(_id, function(err, mongoDocument) { if(err) { return cb(err); } if(!mongoDocument) { mongoDocument = new Model({_id: new ObjectId(_id)}); } for(var key in document) { mongoDocument[key] = document[key]; mongoDocument.markModified(key); } logger(mongoModelName, _id); mongoDocument.save(cb); }); }, cb); }, cb); };
'use strict'; var async = require("async"); function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } module.exports = function seeder(seedObject, mongoose, logger, cb) { if(!cb) { cb = logger; logger = console.log; } var ObjectId = mongoose.Types.ObjectId; async.each(Object.keys(seedObject), function(mongoModel, cb) { var documents = seedObject[mongoModel]; var mongoModelName = capitalize(mongoModel); var Model = mongoose.model(mongoModelName); async.each(Object.keys(documents), function(_id, cb) { // Fake an upsert call, to keep the hooks Model.findById(_id, function(err, mongoDocument) { if(err) { return cb(err); } if(!mongoDocument) { mongoDocument = new Model({_id: new ObjectId(_id)}); } var document = documents[_id]; for(var key in document) { mongoDocument[key] = document[key]; mongoDocument.markModified(key); } logger(mongoModelName, _id); mongoDocument.save(cb); }); }, cb); }, cb); };
Add multithreading with threading module, run until the end The template has over 3M usages, so 5M should be a safe number.
import pywikibot import sys import requests from app import get_proposed_edits, app import threading from time import sleep def worker(title=None): try: get_proposed_edits(title, False, True) except: pass def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: threading.Thread(target=worker, args=[p.title()]).start() except: sleep(60) count += 1 sleep(0.1) if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(5000000, sys.argv[1]) else: prefill_cache(5000000)
import pywikibot import sys import requests from app import get_proposed_edits, app def prefill_cache(max_pages=5000, starting_page=None): site = pywikibot.Site() cs1 = pywikibot.Page(site, 'Module:Citation/CS1') count = 0 starting_page_seen = starting_page is None for p in cs1.embeddedin(namespaces=[0]): print(p.title().encode('utf-8')) if p.title() == starting_page: starting_page_seen = True continue if count >= max_pages: break if not starting_page_seen: continue try: get_proposed_edits(p.title(), False, True) count += 1 except: print("ERROR: Something went wrong with this page!") if __name__ == '__main__': if len(sys.argv) >= 2: prefill_cache(1000000, sys.argv[1]) else: prefill_cache(1000000)
Fix bug where heading was not always updated
import Ember from 'ember'; import request from 'ic-ajax'; import ENV from './../config/environment'; var run = Ember.run; const POLL_INTERVAL = 15 * 1000; export default Ember.Route.extend({ pendingRefresh: null, model: function(params) { request(`${ENV.APP.SERVER}/api/arrivals/${params.stop_id}`).then(run.bind(this, 'requestDidFinish')); return { arrivals: [], stopId: params['stop_id'], isLoading: true }; }, setupController: function(controller, model) { controller.setProperties(model); }, requestDidFinish: function(response) { this.controller.setProperties({ arrivals: response.arrivals, isLoading: false }); // Enqueue a refresh this.set('pendingRefresh', run.later(this, this.refresh, POLL_INTERVAL)); }, actions: { willTransition: function() { run.cancel(this.get('pendingRefresh')); } } });
import Ember from 'ember'; import request from 'ic-ajax'; import ENV from './../config/environment'; var run = Ember.run; const POLL_INTERVAL = 15 * 1000; export default Ember.Route.extend({ pendingRefresh: null, model: function(params) { // Eagerly load template request(`${ENV.APP.SERVER}/api/arrivals/${params.stop_id}`).then(run.bind(this, 'requestDidFinish')); }, setupController: function(controller) { controller.setProperties({ arrivals: [], stopId: this.paramsFor('arrivals')['stop_id'], isLoading: true }); }, requestDidFinish: function(response) { this.controller.setProperties({ arrivals: response.arrivals, isLoading: false }); // Enqueue a refresh this.set('pendingRefresh', run.later(this, this.refresh, POLL_INTERVAL)); }, actions: { willTransition: function() { run.cancel(this.get('pendingRefresh')); } } });
Edit GUI robot sleep time
package guitests.guihandles; import guitests.GuiRobot; import javafx.stage.Stage; /** * A handle to the Command Box in the GUI. */ public class CommandBoxHandle extends GuiHandle{ public static final String COMMAND_INPUT_FIELD_ID = "#commandTextField"; public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) { super(guiRobot, primaryStage, stageTitle); } public void enterCommand(String command) { setTextField(COMMAND_INPUT_FIELD_ID, command); } public String getCommandInput() { return getTextFieldText(COMMAND_INPUT_FIELD_ID); } /** * Enters the given command in the Command Box and presses enter. */ public void runCommand(String command) { enterCommand(command); pressEnter(); guiRobot.sleep(500); //Give time for the command to take effect } public HelpWindowHandle runHelpCommand() { enterCommand("help"); pressEnter(); return new HelpWindowHandle(guiRobot, primaryStage); } }
package guitests.guihandles; import guitests.GuiRobot; import javafx.stage.Stage; /** * A handle to the Command Box in the GUI. */ public class CommandBoxHandle extends GuiHandle{ public static final String COMMAND_INPUT_FIELD_ID = "#commandTextField"; public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) { super(guiRobot, primaryStage, stageTitle); } public void enterCommand(String command) { setTextField(COMMAND_INPUT_FIELD_ID, command); } public String getCommandInput() { return getTextFieldText(COMMAND_INPUT_FIELD_ID); } /** * Enters the given command in the Command Box and presses enter. */ public void runCommand(String command) { enterCommand(command); pressEnter(); guiRobot.sleep(2000); //Give time for the command to take effect } public HelpWindowHandle runHelpCommand() { enterCommand("help"); pressEnter(); return new HelpWindowHandle(guiRobot, primaryStage); } }
Use real base64 decoding for SVGs.
define(["github/base64", "github/github"], function(B64) { return ['github', function(github) { return function(repoOwner, repoName, currentGitDir, relativePath) { // Return a promise that resolves to a dataUrl of the requested file. return new Promise(function(resolve, reject) { var absPath = currentGitDir + "/" + relativePath; github.getFile(repoOwner, repoName, absPath).then(function(f) { if(f.name.toLowerCase().endsWith(".png")) var type = "image/png"; else if (f.name.toLowerCase().endsWith(".svg")) var type = "image/svg+xml"; var dataUrl = "data:" + type + ";base64," + B64.btoa(f.decodedContent); // This is horrible. We should be able to use the raw base64 from github. console.log("Retrieved", f.path, "from git:", dataUrl, f); return resolve(dataUrl); }).catch(function(e) { console.error("Failed to retrieve", absPath, e); return reject(e); }); }); }; }]; });
define(["github/github"], function() { return ['github', function(github) { return function(repoOwner, repoName, currentGitDir, relativePath) { // Return a promise that resolves to a dataUrl of the requested file. return new Promise(function(resolve, reject) { var absPath = currentGitDir + "/" + relativePath; github.getFile(repoOwner, repoName, absPath).then(function(f) { if(f.name.toLowerCase().endsWith(".png")) var type = "image/png"; else if (f.name.toLowerCase().endsWith(".svg")) var type = "image/svg+xml"; var dataUrl = "data:" + type + ";base64," + btoa(f.decodedContent); // This is horrible. We should be able to use the raw base64 from github. console.log("Retrieved", f.path, "from git:", dataUrl, f); return resolve(dataUrl); }).catch(function(e) { console.error("Failed to retrieve", absPath, e); return reject(e); }); }); }; }]; });
Clarify unsupported left button exception message
package com.reactnativenavigation.params.parsers; import android.os.Bundle; import com.balysv.materialmenu.MaterialMenuDrawable; import com.reactnativenavigation.params.TitleBarLeftButtonParams; public class TitleBarLeftButtonParamsParser extends TitleBarButtonParamsParser { public TitleBarLeftButtonParams parseSingleButton(Bundle params) { TitleBarLeftButtonParams leftButtonParams = new TitleBarLeftButtonParams(super.parseSingleButton(params)); leftButtonParams.iconState = getIconStateFromId(leftButtonParams.eventId); return leftButtonParams; } private MaterialMenuDrawable.IconState getIconStateFromId(String id) { switch (id) { case "back": return MaterialMenuDrawable.IconState.ARROW; case "cancel": return MaterialMenuDrawable.IconState.X; case "accept": return MaterialMenuDrawable.IconState.CHECK; case "sideMenu": return MaterialMenuDrawable.IconState.BURGER; default: throw new RuntimeException("Unsupported button id: " + id + ". Supported ids are: back, cancel, accept and sideMenu"); } } }
package com.reactnativenavigation.params.parsers; import android.os.Bundle; import com.balysv.materialmenu.MaterialMenuDrawable; import com.reactnativenavigation.params.TitleBarLeftButtonParams; public class TitleBarLeftButtonParamsParser extends TitleBarButtonParamsParser { public TitleBarLeftButtonParams parseSingleButton(Bundle params) { TitleBarLeftButtonParams leftButtonParams = new TitleBarLeftButtonParams(super.parseSingleButton(params)); leftButtonParams.iconState = getIconStateFromId(leftButtonParams.eventId); return leftButtonParams; } private MaterialMenuDrawable.IconState getIconStateFromId(String id) { switch (id) { case "back": return MaterialMenuDrawable.IconState.ARROW; case "cancel": return MaterialMenuDrawable.IconState.X; case "accept": return MaterialMenuDrawable.IconState.CHECK; case "sideMenu": return MaterialMenuDrawable.IconState.BURGER; default: throw new RuntimeException("Unsupported button type " + id); } } }
event: Add a comment at Modifier Updates #926
// Copyright 2019 The Ebiten Authors // // 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package event import ( "github.com/hajimehoshi/ebiten/internal/driver" ) // Modifier is a bit set of modifier keys on a keyboard. type Modifier int const ( ModifierShift Modifier = Modifier(driver.ModifierShift) ModifierControl Modifier = Modifier(driver.ModifierControl) ModifierAlt Modifier = Modifier(driver.ModifierAlt) ModifierCapsLock Modifier = Modifier(driver.ModifierCapsLock) ModifierNumLock Modifier = Modifier(driver.ModifierNumLock) )
// Copyright 2019 The Ebiten Authors // // 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package event import ( "github.com/hajimehoshi/ebiten/internal/driver" ) type Modifier int const ( ModifierShift Modifier = Modifier(driver.ModifierShift) ModifierControl Modifier = Modifier(driver.ModifierControl) ModifierAlt Modifier = Modifier(driver.ModifierAlt) ModifierCapsLock Modifier = Modifier(driver.ModifierCapsLock) ModifierNumLock Modifier = Modifier(driver.ModifierNumLock) )
Disable builtin tests for input() as it hangs
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class InputTests(TranspileTestCase): pass # class BuiltinInputFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): # functions = ["input"] # not_implemented = [ # 'test_bool', # 'test_bytearray', # 'test_bytes', # 'test_class', # 'test_complex', # 'test_dict', # 'test_float', # 'test_frozenset', # 'test_int', # 'test_list', # 'test_set', # 'test_str', # 'test_tuple', # ]
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class InputTests(TranspileTestCase): pass class BuiltinInputFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["input"] not_implemented = [ 'test_bool', 'test_bytearray', 'test_bytes', 'test_class', 'test_complex', 'test_dict', 'test_float', 'test_frozenset', 'test_int', 'test_list', 'test_set', 'test_str', 'test_tuple', ]
Use better test for UnsupportedClassVersionError. The previous test worked correctly with the Oracle JVM but failed with other JVMs. This new test should work correctly on all JVMs.
var java = require("../testHelpers").java; var nodeunit = require("nodeunit"); var util = require("util"); exports['Java8'] = nodeunit.testCase({ "call methods of a class that uses lambda expressions": function(test) { try { var TestLambda = java.import('TestLambda'); var lambda = new TestLambda(); var sum = lambda.testLambdaAdditionSync(23, 42); test.equal(sum, 65); var diff = lambda.testLambdaSubtractionSync(23, 42); test.equal(diff, -19); } catch (err) { var unsupportedVersion = java.instanceOf(err.cause, 'java.lang.UnsupportedClassVersionError'); test.ok(unsupportedVersion); if (unsupportedVersion) console.log('JRE 1.8 not available'); else console.error('Java8 test failed with unknown error:', err); } test.done(); } });
var java = require("../testHelpers").java; var nodeunit = require("nodeunit"); var util = require("util"); exports['Java8'] = nodeunit.testCase({ "call methods of a class that uses lambda expressions": function(test) { try { var TestLambda = java.import('TestLambda'); var lambda = new TestLambda(); var sum = lambda.testLambdaAdditionSync(23, 42); test.equal(sum, 65); var diff = lambda.testLambdaSubtractionSync(23, 42); test.equal(diff, -19); } catch (err) { var unsupportedVersion = err.toString().match(/Unsupported major.minor version 52.0/) test.ok(unsupportedVersion); if (unsupportedVersion) console.log('JRE 1.8 not available'); else console.error('Java8 test failed with unknown error:', err); } test.done(); } });
Fix crash at loading shard details when still spawning
const Discord = require('discord.js'); const logger = require('./util/logger') const config = require('./config.js'); const fs = require('fs'); // write PID-file fs.writeFile( './trump.pid', parseInt(process.pid).toString(), function (error) { if (error) return logger.log(null, error); } ); var options = new Object(); options.token = config.token; options.totalShards = 'auto'; const manager = new Discord.ShardingManager('./bot.js', options); manager.on('shardCreate', shard => { logger.log(null, "=== Launched shard " + shard.id); }); logger.log(null, "Spawning shard(s)"); manager.spawn(); // write stats all 30 seconds setInterval(function () { getStats(0, 0); }, 30000); function getStats(index, guildCount) { manager.fetchClientValues('guilds.cache.size').then(results => { // write current stats var fileName = './stats.json'; var file = require(fileName); file.guildCount = results.reduce((prev, val) => prev + val, 0); file.shards = manager.shardList.length; fs.writeFile( fileName, JSON.stringify(file, null, 2), function (error) { if (error) return logger.log(null, error); } ); }) .catch(console.error); }
const Discord = require('discord.js'); const logger = require('./util/logger') const config = require('./config.js'); const fs = require('fs'); // write PID-file fs.writeFile( './trump.pid', parseInt(process.pid).toString(), function (error) { if (error) return logger.log(null, error); } ); var options = new Object(); options.token = config.token; options.totalShards = 'auto'; const manager = new Discord.ShardingManager('./bot.js', options); manager.on('shardCreate', shard => { logger.log(null, "=== Launched shard " + shard.id); }); logger.log(null, "Spawning shard(s)"); manager.spawn(); // write stats all 30 seconds setInterval(function () { getStats(0, 0); }, 30000); function getStats(index, guildCount) { manager.fetchClientValues('guilds.cache.size').then(results => { // write current stats var fileName = './stats.json'; var file = require(fileName); file.guildCount = results.reduce((prev, val) => prev + val, 0); file.shards = manager.shardList.length; fs.writeFile( fileName, JSON.stringify(file, null, 2), function (error) { if (error) return logger.log(null, error); } ); }); }
Raise exception if faulty definition of classes inserted
# -*- coding: utf-8 -*- """common.py Contains basic functions that are shared throughout the module """ def compute_totals(distribution, classes): "Compute the number of individuals per class, per unit and in total" N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution} N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes} N_tot = sum(N_class.values()) return N_unit, N_class, N_tot def regroup_per_class(distribution, classes): "Return classes as they are presented in the data" try: new_distribution = {au: {cl: sum([dist_au[c] for c in composition]) for cl,composition in classes.iteritems()} for au, dist_au in distribution.iteritems()} except KeyError: raise KeyError("Verify that the categories specified in the class" " definitions exist in the original data.") return new_distribution def return_categories(distribution): "Return the categories in the original data" keys = next(distribution.itervalues()).keys() return {k:[k] for k in keys}
# -*- coding: utf-8 -*- """common.py Contains basic functions that are shared thoughout the module """ def compute_totals(distribution, classes): "Compute the number of individuals per class, per unit and in total" N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution} N_class = {cl:sum([dist_a[cl] for dist_a in distribution.values()]) for cl in classes} N_tot = sum(N_class.values()) return N_unit, N_class, N_tot def regroup_per_class(distribution, classes): "Return classes as they are presented in the data" new_distribution = {au: {cl: sum([dist_au[c] for c in composition]) for cl,composition in classes.iteritems()} for au, dist_au in distribution.iteritems()} return new_distribution def return_categories(distribution): "Return the categories in the original data" keys = next(distribution.itervalues()).keys() return {k:[k] for k in keys}
Fix field set on post admin, opps core
# -*- coding: utf-8 -*- from django.contrib.sites.models import Site from django.contrib import admin from django import forms from opps.core.models import Post, PostImage from opps.core.models import Image from redactor.widgets import RedactorEditor class PostImageInline(admin.TabularInline): model = PostImage fk_name = 'post' raw_id_fields = ['image'] actions = None extra = 1 fieldsets = [(None, {'fields': ('image', 'order')})] class PostAdminForm(forms.ModelForm): class Meta: model = Post widgets = {'content': RedactorEditor(),} class PostAdmin(admin.ModelAdmin): form = PostAdminForm prepopulated_fields = {"slug": ("title",)} inlines = [PostImageInline] fieldsets = ( (None, {'fields': ('title', 'short_title', 'headline', 'channel', 'content',) }), (None, {'fields': ('main_image', 'credit', 'slug',)}) ) exclude = ('user',) def save_model(self, request, obj, form, change): if not obj.user: obj.user = request.user obj.save() admin.site.register(Post, PostAdmin)
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from opps.core.models import Post, PostImage from opps.core.models import Image from redactor.widgets import RedactorEditor class PostImageInline(admin.TabularInline): model = PostImage fk_name = 'post' raw_id_fields = ['image'] actions = None extra = 1 fieldsets = [(None, {'fields': ('image', 'order')})] class PostAdminForm(forms.ModelForm): class Meta: model = Post widgets = {'content': RedactorEditor(),} class PostAdmin(admin.ModelAdmin): form = PostAdminForm prepopulated_fields = {"slug": ("title",)} inlines = [PostImageInline] def save_model(self, request, obj, form, change): if not obj.user: obj.user = request.user obj.save() admin.site.register(Post, PostAdmin)
Fix MP3 track not closed when header parsing fails.
package com.sedmelluq.discord.lavaplayer.container.mp3; import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.BaseAudioTrack; import com.sedmelluq.discord.lavaplayer.track.playback.AudioTrackExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Audio track that handles an MP3 stream */ public class Mp3AudioTrack extends BaseAudioTrack { private static final Logger log = LoggerFactory.getLogger(Mp3AudioTrack.class); private final SeekableInputStream inputStream; /** * @param executor Track executor * @param trackInfo Track info * @param inputStream Input stream for the MP3 file */ public Mp3AudioTrack(AudioTrackExecutor executor, AudioTrackInfo trackInfo, SeekableInputStream inputStream) { super(executor, trackInfo); this.inputStream = inputStream; } @Override public void process(AtomicInteger volumeLevel) throws Exception { Mp3StreamingFile file = new Mp3StreamingFile(inputStream, executor.getFrameConsumer(), volumeLevel); try { file.parseHeaders(); log.debug("Starting to play MP3 track {}", getIdentifier()); executor.executeProcessingLoop(file::provideFrames, file::seekToTimecode); } finally { file.close(); } } }
package com.sedmelluq.discord.lavaplayer.container.mp3; import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import com.sedmelluq.discord.lavaplayer.track.BaseAudioTrack; import com.sedmelluq.discord.lavaplayer.track.playback.AudioTrackExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Audio track that handles an MP3 stream */ public class Mp3AudioTrack extends BaseAudioTrack { private static final Logger log = LoggerFactory.getLogger(Mp3AudioTrack.class); private final SeekableInputStream inputStream; /** * @param executor Track executor * @param trackInfo Track info * @param inputStream Input stream for the MP3 file */ public Mp3AudioTrack(AudioTrackExecutor executor, AudioTrackInfo trackInfo, SeekableInputStream inputStream) { super(executor, trackInfo); this.inputStream = inputStream; } @Override public void process(AtomicInteger volumeLevel) throws Exception { Mp3StreamingFile file = new Mp3StreamingFile(inputStream, executor.getFrameConsumer(), volumeLevel); file.parseHeaders(); log.debug("Starting to play MP3 track {}", getIdentifier()); try { executor.executeProcessingLoop(file::provideFrames, file::seekToTimecode); } finally { file.close(); } } }
[Admin] Add latest customers and orders
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Order\Repository; use Sylius\Component\Order\Model\OrderInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface { /** * @return int */ public function count(); /** * @return int */ public function getTotalSales(); /** * @param int $count * * @return OrderInterface[] */ public function findLatest($count); /** * @param int|string $number * * @return bool */ public function isNumberUsed($number); /** * @param string $orderNumber * * @return OrderInterface|null */ public function findOneByNumber($orderNumber); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Order\Repository; use Sylius\Component\Order\Model\OrderInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface { /** * @return int */ public function count(); /** * @return int */ public function getTotalSales(); /** * @param int $amount * * @return OrderInterface[] */ public function findRecentOrders($amount = 10); /** * @param int|string $number * * @return bool */ public function isNumberUsed($number); /** * @param string $orderNumber * * @return OrderInterface|null */ public function findOneByNumber($orderNumber); }
Fix for IE 11 (Focus) IE presents itself as mozilla, so it trips on the bug.
def ensureFocusHandler(): JS(""" return (focusHandler !== null) ? focusHandler : (focusHandler = @{{createFocusHandler}}()); """) def createFocusHandler(): JS(""" return function(evt) { // This function is called directly as an event handler, so 'this' is // set up by the browser to be the input on which the event is fired. We // call focus() in a timeout or the element may be blurred when this event // ends. var div = this['parentNode']; if (div['onfocus']) { $wnd['setTimeout'](function() { div['focus'](); }, 0); } }; """) def createFocusable0(focusHandler): JS(""" var div = $doc['createElement']('div'); div['tabIndex'] = 0; var input = $doc['createElement']('input'); input['type'] = 'text'; input['style']['opacity'] = 0; input['tabIndex'] = -1; input['style']['zIndex'] = -1; input['style']['width'] = '1px'; input['style']['height'] = '1px'; input['style']['overflow'] = 'hidden'; input['style']['position'] = 'absolute'; input['addEventListener']( 'focus', focusHandler, false); div['appendChild'](input); return div; """) def createFocusable(): return createFocusable0(ensureFocusHandler())
def ensureFocusHandler(): JS(""" return (focusHandler !== null) ? focusHandler : (focusHandler = @{{createFocusHandler}}()); """) def createFocusHandler(): JS(""" return function(evt) { // This function is called directly as an event handler, so 'this' is // set up by the browser to be the input on which the event is fired. We // call focus() in a timeout or the element may be blurred when this event // ends. var div = this['parentNode']; if (div['onfocus']) { $wnd['setTimeout'](function() { div['focus'](); }, 0); } }; """) def createFocusable0(focusHandler): JS(""" var div = $doc['createElement']('div'); div['tabIndex'] = 0; var input = $doc['createElement']('input'); input['type'] = 'text'; input['style']['opacity'] = 0; input['tabIndex'] = -1; input['style']['zIndex'] = -1; input['style']['width'] = '1px'; input['style']['height'] = '1px'; input['style']['overflow'] = 'hidden'; input['style']['position'] = 'absolute'; input['addEventListener']( 'focus', focusHandler, false); div['appendChild'](input); return div; """) def createFocusable(): ensureFocusHandler() return createFocusable0()
Set curly brackets to same line than condition
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2014-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Webcam / Config */ namespace PH7; defined('PH7') or exit('Restricted access'); class Permission extends PermissionCore { public function __construct() { parent::__construct(); if (!AdminCore::auth() || UserCore::isAdminLoggedAs()) {// If the admin is not logged (but can be if the admin use "login as user" feature) if (!$this->checkMembership() || !$this->group->webcam_access) { $this->paymentRedirect(); } } } }
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2014-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Webcam / Config */ namespace PH7; defined('PH7') or exit('Restricted access'); class Permission extends PermissionCore { public function __construct() { parent::__construct(); if (!AdminCore::auth() || UserCore::isAdminLoggedAs()) // If the admin is not logged (but can be if the admin use "login as user" feature) { if (!$this->checkMembership() || !$this->group->webcam_access) { $this->paymentRedirect(); } } } }
Rework undefined test & fix v2 typo
'use strict'; let cli = require('heroku-cli-util'); let shellescape = require('shell-escape'); let co = require('co'); function* run (context, heroku) { let configVars = yield heroku.request({path: `/apps/${context.app}/config-vars`}); let v = configVars[context.args.key]; if (v === undefined) { cli.log(''); // match v3 output for missing } else { if (context.flags.shell) { v = process.stdout.isTTY ? shellescape([v]) : v; cli.log(`${context.args.key}=${v}`); } else { cli.log(v); } } } module.exports = { topic: 'config', command: 'get', description: 'display a config value for an app', help: `Example: $ heroku config:get RAILS_ENV production `, args: [{name: 'key'}], flags: [{name: 'shell', char: 's', description: 'output config var in shell format'}], needsApp: true, needsAuth: true, run: cli.command(co.wrap(run)) };
'use strict'; let cli = require('heroku-cli-util'); let shellescape = require('shell-escape'); let co = require('co'); function* run (context, heroku) { let configVars = yield heroku.request({path: `/apps/${context.app}/config-vars`}); let v = configVars[context.args.key]; if (typeof(v) === 'undefined') { cli.log(''); // match v2 output for missing } else { if (context.flags.shell) { v = process.stdout.isTTY ? shellescape([v]) : v; cli.log(`${context.args.key}=${v}`); } else { cli.log(v); } } } module.exports = { topic: 'config', command: 'get', description: 'display a config value for an app', help: `Example: $ heroku config:get RAILS_ENV production `, args: [{name: 'key'}], flags: [{name: 'shell', char: 's', description: 'output config var in shell format'}], needsApp: true, needsAuth: true, run: cli.command(co.wrap(run)) };
Move callback to return a 201 status code
var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); // create reusable transporter object using the default SMTP transport var smtp = process.env.SMTPCREDENTIALS || ''; var transporter = nodemailer.createTransport(smtp); var SECRET = process.env.SPASECRET || ''; router.post('/deliverforme', function(req, res, next) { var data = req.body; if (data.key !== SECRET) { res.status(400).send(); } var sended_at = new Date(data.timestamp); var received_at = new Date(Date.now()); var message = [data['form[content]'], "\n\nEnviado em ", sended_at.toString(), ". Processado em ", received_at.toString() ].join(' '); var mailOptions = { to: 'kenner.hp@gmail.com', from: [data['form[name]'],"<",data['form[email]'],">"].join(' '), subject: data['form[subject]'], text: message }; transporter.sendMail(mailOptions, function(error, info){ if(error) { res.status(403).send(); } }); res.status(201).send(); }); module.exports = router;
var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); // create reusable transporter object using the default SMTP transport var smtp = process.env.SMTPCREDENTIALS || ''; var transporter = nodemailer.createTransport(smtp); var SECRET = process.env.SPASECRET || ''; router.post('/deliverforme', function(req, res, next) { var data = req.body; if (data.key !== SECRET) { res.status(400).send(); } var sended_at = new Date(data.timestamp); var received_at = new Date(Date.now()); var message = [data['form[content]'], "\n\nEnviado em ", sended_at.toString(), ". Processado em ", received_at.toString() ].join(' '); var mailOptions = { to: 'kenner.hp@gmail.com', from: [data['form[name]'],"<",data['form[email]'],">"].join(' '), subject: data['form[subject]'], text: message }; transporter.sendMail(mailOptions, function(error, info){ if(error){ res.status(403).send(error); } res.send(info.response); }); }); module.exports = router;
Simplify the CardDB test check for tags
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): for tag in card.tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
from hearthstone.enums import CardType, GameTag, Rarity import utils CARDS = utils.fireplace.cards.db def test_all_tags_known(): """ Iterate through the card database and check that all specified GameTags are known in hearthstone.enums.GameTag """ unknown_tags = set() known_tags = list(GameTag) known_rarities = list(Rarity) # Check the db loaded correctly assert utils.fireplace.cards.db for card in CARDS.values(): card_tags = [int(e.attrib["enumID"]) for e in card.xml.findall("./Tag")] for tag in card_tags: # We have fake tags in fireplace.enums which are always negative if tag not in known_tags and tag > 0: unknown_tags.add(tag) # Test rarities as well (cf. TB_BlingBrawl_Blade1e in 10956...) assert card.rarity in known_rarities assert not unknown_tags def test_play_scripts(): for card in CARDS.values(): if card.scripts.activate: assert card.type == CardType.HERO_POWER elif card.scripts.play: assert card.type not in (CardType.HERO, CardType.HERO_POWER, CardType.ENCHANTMENT)
Fix alembic migration for rpms->artifacts rename The migration does not work on MySQL-based engines, because it requires setting the existing_type parameter [1]. It worked fine on SQLite, though. [1] - https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.alter_column Change-Id: If0cc05af843e3db5f4b2e501caa8f4f773b24509
# 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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Rename rpms to artifacts Revision ID: 2d503b5034b7 Revises: 2a0313a8a7d6 Create Date: 2019-04-26 01:06:50.462042 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2d503b5034b7' down_revision = '2a0313a8a7d6' branch_labels = None depends_on = None def upgrade(): with op.batch_alter_table("commits") as batch_op: batch_op.alter_column('rpms', existing_type=sa.Text(), new_column_name='artifacts') def downgrade(): with op.batch_alter_table("commits") as batch_op: batch_op.alter_column('artifacts', existing_type=sa.Text(), new_column_name='rpms')
# 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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Rename rpms to artifacts Revision ID: 2d503b5034b7 Revises: 2a0313a8a7d6 Create Date: 2019-04-26 01:06:50.462042 """ from alembic import op # revision identifiers, used by Alembic. revision = '2d503b5034b7' down_revision = '2a0313a8a7d6' branch_labels = None depends_on = None def upgrade(): with op.batch_alter_table("commits") as batch_op: batch_op.alter_column('rpms', new_column_name='artifacts') def downgrade(): with op.batch_alter_table("commits") as batch_op: batch_op.alter_column('artifacts', new_column_name='rpms')
Include the python module in the package The top level files, parse_this and parse_this_test, were not included. By using the 'py_modules' option these files are now actually included in the parse_this pacakge.
#!/usr/bin/env python import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), "r") as readme_file: readme = readme_file.read() setup( name = "parse_this", version = "0.2.1", description = "Makes it easy to create a command line interface for any function, method or classmethod..", long_description = readme, py_modules = ["parse_this", "parse_this_test"], author = "Bertrand Vidal", author_email = "vidal.bertrand@gmail.com", download_url = "https://pypi.python.org/pypi/parse_this", url = "https://github.com/bertrandvidal/parse_this", classifiers = [ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Operating System :: OS Independent", "Programming Language :: Python", ], setup_requires = [ "nose", ], )
#!/usr/bin/env python import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), "r") as readme_file: readme = readme_file.read() setup( name = "parse_this", version = "0.2.1", description = "Makes it easy to create a command line interface for any function, method or classmethod..", long_description = readme, author = "Bertrand Vidal", author_email = "vidal.bertrand@gmail.com", download_url = "https://pypi.python.org/pypi/parse_this", url = "https://github.com/bertrandvidal/parse_this", classifiers = [ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Operating System :: OS Independent", "Programming Language :: Python", ], setup_requires = [ "nose", ], )
Change title limit to 30 chars.
App.populator('feed', function (page, data) { $(page).find('.app-title').text(data.title); $.getJSON('/data/feed/' + data.id + '/articles', function (articles) { articles.forEach(function (article) { var li = $('<li class="app-button">' + article.title + '</li>'); li.on('click', function () { App.load('article', article); }); $(page).find('.app-list').append(li); }); }); }); App.populator('article', function (page, data) { $(page).find('.app-title').text(data.title.substring(0, 30)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' + '<a href="' + article.url + '">' + article.url + '</a></p>' + article.content; $(page).find('.app-content').html(content); }); });
App.populator('feed', function (page, data) { $(page).find('.app-title').text(data.title); $.getJSON('/data/feed/' + data.id + '/articles', function (articles) { articles.forEach(function (article) { var li = $('<li class="app-button">' + article.title + '</li>'); li.on('click', function () { App.load('article', article); }); $(page).find('.app-list').append(li); }); }); }); App.populator('article', function (page, data) { $(page).find('.app-title').text(data.title.substring(0, 20)); $.getJSON('/data/article/' + data.url, function (article) { var content = '<p><strong>' + article.title + '</strong><br/>' + '<a href="' + article.url + '">' + article.url + '</a></p>' + article.content; $(page).find('.app-content').html(content); }); });
FEATURE: Add metadata title in portrayal view
# -*- encoding: utf-8 -*- __author__ = 'ray' __date__ = '4/4/15' from stonemason.mason import Portrayal from stonemason.mason.theme import Theme def jsonify_portrayal(portrayal): assert isinstance(portrayal, Portrayal) template = { 'name': portrayal.name, 'metadata': { 'title': portrayal.metadata.title, 'version': portrayal.metadata.version, 'abstract': portrayal.metadata.abstract, 'attribution': portrayal.metadata.attribution, 'center': portrayal.metadata.center, 'center_zoom': portrayal.metadata.center_zoom }, 'maptype': portrayal.bundle.map_type, 'tileformat': portrayal.bundle.tile_format, 'pyramid': portrayal.pyramid, 'schemas': [] } for tag in portrayal.iter_schema(): template['schemas'].append(tag) return template def jsonify_map_theme(map_theme): assert isinstance(map_theme, Theme) return repr(map_theme)
# -*- encoding: utf-8 -*- __author__ = 'ray' __date__ = '4/4/15' from stonemason.mason import Portrayal from stonemason.mason.theme import Theme def jsonify_portrayal(portrayal): assert isinstance(portrayal, Portrayal) template = { 'name': portrayal.name, 'metadata': { 'version': portrayal.metadata.version, 'abstract': portrayal.metadata.abstract, 'attribution': portrayal.metadata.attribution, 'center': portrayal.metadata.center, 'center_zoom': portrayal.metadata.center_zoom }, 'maptype': portrayal.bundle.map_type, 'tileformat': portrayal.bundle.tile_format, 'pyramid': portrayal.pyramid, 'schemas': [] } for tag in portrayal.iter_schema(): template['schemas'].append(tag) return template def jsonify_map_theme(map_theme): assert isinstance(map_theme, Theme) return repr(map_theme)
Swap deprecated findDOMNode to the version from the react-dom module.
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import styles from './GlobalSearch.scss'; export default class GlobalSearch extends Component { render () { return ( <input ref='searchBox' placeholder={this.props.placeholder} className={styles['gs-input']} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} onFocus={this.props.onFocus} onClick={() => { findDOMNode(this).select(); }} /> ); }; }; GlobalSearch.propTypes = { placeholder: React.PropTypes.string, onFocus: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onKeyUp: React.PropTypes.func.isRequired, styles: React.PropTypes.object };
import React, { Component, findDOMNode } from 'react'; import styles from './GlobalSearch.scss'; export default class GlobalSearch extends Component { render () { return ( <input ref='searchBox' placeholder={this.props.placeholder} className={styles['gs-input']} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} onFocus={this.props.onFocus} onClick={() => { findDOMNode(this).select(); }} /> ); }; }; GlobalSearch.propTypes = { placeholder: React.PropTypes.string, onFocus: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onKeyUp: React.PropTypes.func.isRequired, styles: React.PropTypes.object };
Make it yet even easier to read key logger output
"""Run a server that takes all GET requests and dumps them.""" from json import loads from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # Print, log, and return. print(request.url) with open("cap.log", "a") as f: f.write(replace_entities(str(request.url)) + "\n") with open("key.log", "a") as f: if "c" in request.args: keys = loads(replace_entities(request.args.get('c'))) try: keys = "".join(keys) except Exception: pass f.write(keys + '\n') return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages." # @app.route('/<path:path>') # def staticserve(path): # """Serve a file from your static directory.""" # return app.send_static_file(path) if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
"""Run a server that takes all GET requests and dumps them.""" from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # Print, log, and return. print(request.url) with open("cap.log", "a") as f: f.write(replace_entities(str(request.url)) + "\n") with open("key.log", "a") as f: if "c" in request.args: keys = replace_entities(request.args.get('c')) f.write(keys + '\n') return "WARNING: This site exists to demonstrate a 'capture server' for a penetration tester. Every GET request you send to it will be logged and recorded. Old logs will be deleted after some time, but information you send here is not safe. Use this site for educational purposes only! I am not responsible for any damages caused, as this site will be taken down as frequently as possible to reduce damages." # @app.route('/<path:path>') # def staticserve(path): # """Serve a file from your static directory.""" # return app.send_static_file(path) if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
Rename all spade variable names to shovel variable names
package info.u_team.u_team_core.item.tool; import info.u_team.u_team_core.api.registry.IUArrayRegistryType; import net.minecraft.item.Item; public class ToolSet implements IUArrayRegistryType<Item> { private final UAxeItem axe; private final UHoeItem hoe; private final UPickaxeItem pickaxe; private final UShovelItem shovel; private final USwordItem sword; public ToolSet(UAxeItem axe, UHoeItem hoe, UPickaxeItem pickaxe, UShovelItem shovel, USwordItem sword) { this.axe = axe; this.hoe = hoe; this.pickaxe = pickaxe; this.shovel = shovel; this.sword = sword; } @Override public Item[] getArray() { return new Item[] { axe, hoe, pickaxe, shovel, sword }; } public UAxeItem getAxe() { return axe; } public UHoeItem getHoe() { return hoe; } public UPickaxeItem getPickaxe() { return pickaxe; } public UShovelItem getShovel() { return shovel; } public USwordItem getSword() { return sword; } }
package info.u_team.u_team_core.item.tool; import info.u_team.u_team_core.api.registry.IUArrayRegistryType; import net.minecraft.item.Item; public class ToolSet implements IUArrayRegistryType<Item> { private final UAxeItem axe; private final UHoeItem hoe; private final UPickaxeItem pickaxe; private final UShovelItem spade; private final USwordItem sword; public ToolSet(UAxeItem axe, UHoeItem hoe, UPickaxeItem pickaxe, UShovelItem spade, USwordItem sword) { this.axe = axe; this.hoe = hoe; this.pickaxe = pickaxe; this.spade = spade; this.sword = sword; } @Override public Item[] getArray() { return new Item[] { axe, hoe, pickaxe, spade, sword }; } public UAxeItem getAxe() { return axe; } public UHoeItem getHoe() { return hoe; } public UPickaxeItem getPickaxe() { return pickaxe; } public UShovelItem getSpade() { return spade; } public USwordItem getSword() { return sword; } }
Add GUI for 3D Rotation script
from Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from System.Collections.Generic import * uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document getselection = uidoc.Selection.GetElementIds app = __revit__.Application from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import UIApplication def alert(msg): TaskDialog.Show('RevitPythonShell', msg) def quit(): __window__.Close() exit = quit t = Transaction(doc, "Copie tous les gabarits de vue") t.Start() try: ids = List[ElementId]() for e in FilteredElementCollector(doc).OfClass(ViewFamilyType): #Cherche l'Id des éléments sélectionnés ids.Add(e.Id) ld = {} for n, d in enumerate(app.Documents): ld[n] = d.Title, d for i in ld: print i, ld[i][0] autreDoc = ld[2][1] cp_opts = CopyPasteOptions() ElementTransformUtils.CopyElements(doc, ids, autreDoc, Transform.Identity, cp_opts) except: # print a stack trace and error messages for debugging import traceback traceback.print_exc() t.RollBack() else: # no errors, so just close the window t.Commit()
from Autodesk.Revit.DB import * from Autodesk.Revit.DB.Architecture import * from Autodesk.Revit.DB.Analysis import * from System.Collections.Generic import * uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document getselection = uidoc.Selection.GetElementIds app = __revit__.Application from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI import UIApplication def alert(msg): TaskDialog.Show('RevitPythonShell', msg) def quit(): __window__.Close() exit = quit t = Transaction(doc, "Copie tous les gabarits de vue") t.Start() try: ids = List[ElementId]() for e in FilteredElementCollector(doc).OfClass(ViewFamilyType): #Cherche l'Id des éléments sélectionnés ids.Add(e.Id) ld = {} for n, d in enumerate(app.Documents): ld[n] = d.Title, d for i in ld: print i, ld[i][0] autreDoc = ld[2][1] cp_opts = CopyPasteOptions() ElementTransformUtils.CopyElements(doc, ids, autreDoc, Transform.Identity, cp_opts) t.Commit() except: # print a stack trace and error messages for debugging import traceback traceback.print_exc() t.RollBack() else: # no errors, so just close the window __window__.Close()
BAP-12479: Create new widget controller buttonsAction - Removed unnecessary options.
<?php namespace Oro\Bundle\ActionBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class ButtonsWidgetController extends Controller { /** * @Route("/buttons", name="oro_action_buttons_widget_buttons") * @Template() * * @return array */ public function buttonsAction() { $buttonProvider = $this->get('oro_action.provider.button'); $buttonSearchContextProvider = $this->get('oro_action.provider.button_search_context'); $buttonSearchContext = $buttonSearchContextProvider->getButtonSearchContext(); return [ 'buttons' => $buttonProvider->findAll($buttonSearchContext), ]; } }
<?php namespace Oro\Bundle\ActionBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class ButtonsWidgetController extends Controller { /** * @Route("/buttons", name="oro_action_buttons_widget_buttons") * @Template() * * @return array */ public function buttonsAction() { $buttonProvider = $this->get('oro_action.provider.button'); $buttonSearchContextProvider = $this->get('oro_action.provider.button_search_context'); $buttonSearchContext = $buttonSearchContextProvider->getButtonSearchContext(); return [ 'buttons' => $buttonProvider->findAll($buttonSearchContext), 'searchContext' => $buttonSearchContext, ]; } }
Add cacheType to allow cache with keys.
<?php namespace ProcessWire\GraphQL\Type; use ProcessWire\Template; trait CacheTrait { private static $type; public static function type($options = null) { if ($options instanceof Template) { return self::templateType($options); } if (self::$type) { return self::$type; } self::$type = self::buildType(); return self::$type; } private static $types = []; public static function templateType(Template $template) { if (isset(self::$types[$template->name])) { return self::$types[$template->name]; } self::$types[$template->name] = self::buildTemplateType($template); return self::$types[$template->name]; } private static $field = []; public static function field($options) { $name = $options['name']; if (isset(self::$field[$name])) { return self::$field[$name]; } self::$field[$name] = self::buildField($options); return self::$field[$name]; } public static function cacheType($key = 'default', $buildType) { if (isset(self::$types[$key])) { return self::$types[$key]; } self::$types[$key] = $buildType(); return self::$types[$key]; } }
<?php namespace ProcessWire\GraphQL\Type; use ProcessWire\Template; trait CacheTrait { private static $type; public static function type($options = null) { if ($options instanceof Template) { return self::templateType($options); } if (self::$type) { return self::$type; } self::$type = self::buildType(); return self::$type; } private static $types = []; public static function templateType(Template $template) { if (isset(self::$types[$template->name])) { return self::$types[$template->name]; } self::$types[$template->name] = self::buildTemplateType($template); return self::$types[$template->name]; } private static $field = []; public static function field($options) { $name = $options['name']; if (isset(self::$field[$name])) { return self::$field[$name]; } self::$field[$name] = self::buildField($options); return self::$field[$name]; } }
Add platform detection for centos 6/7
from setuptools import setup, find_packages import platform distro, version, _ = platform.dist() # Default to cent7 data_files = [('/usr/lib/systemd/system', ['pkg/hubble.service']),] if distro == 'redhat' or distro == 'centos': if version.startswith('6'): data_files = [('/etc/init.d', ['pkg/hubble']),] elif version.startswith('7'): data_files = [('/usr/lib/systemd/system', ['pkg/hubble.service']),] setup( name="hubblestack", version="2.0", packages=find_packages(), entry_points={ 'console_scripts': [ 'hubble = hubble.daemon:run', ], }, install_requires=[ 'salt >= 2016.3.4', ], data_files=data_files, options={ # 'build_scripts': { # 'executable': '/usr/bin/env python', # }, 'bdist_rpm': { 'requires': 'salt', }, }, )
from setuptools import setup, find_packages setup( name="hubblestack", version="2.0", packages=find_packages(), entry_points={ 'console_scripts': [ 'hubble = hubble.daemon:run', ], }, install_requires=[ 'salt >= 2016.3.4', ], data_files=[('/etc/init.d', ['pkg/hubble']),], options={ # 'build_scripts': { # 'executable': '/usr/bin/env python', # }, 'bdist_rpm': { 'requires': 'salt', }, }, )
Update to work with makara
var moment = require('moment'); module.exports = function (dust) { // format dust.helpers.moment = function(chunk, context, bodies, params) { var type = dust.helpers.tap(params.type, chunk, context) || 'format'; var date = dust.helpers.tap(params.date, chunk, context) || new Date(); var format = dust.helpers.tap(params.format, chunk, context) || 'MMM Do YYYY'; var input = dust.helpers.tap(params.input, chunk, context) || 1; var value = dust.helpers.tap(params.value, chunk, context) || 'days'; var locale = dust.helpers.tap(params.locale, chunk, context) || 'en'; moment.lang(locale); switch (type) { case 'format': return chunk.write(moment(date).format(format)); break; case 'fromNow': return chunk.write(moment(date).fromNow()); break; case 'subtract': return chunk.write(moment(date).subtract(input, value).calendar()); break; case 'add': return chunk.write(moment(date).add(input, value).calendar()); break; } }; }; module.exports.registerWith = module.exports;
var moment = require('moment'); (function(dust) { // format dust.helpers.moment = function(chunk, context, bodies, params) { var type = dust.helpers.tap(params.type, chunk, context) || 'format'; var date = dust.helpers.tap(params.date, chunk, context) || new Date(); var format = dust.helpers.tap(params.format, chunk, context) || 'MMM Do YYYY'; var input = dust.helpers.tap(params.input, chunk, context) || 1; var value = dust.helpers.tap(params.value, chunk, context) || 'days'; var locale = dust.helpers.tap(params.locale, chunk, context) || 'en'; moment.lang(locale); switch (type) { case 'format': return chunk.write(moment(date).format(format)); break; case 'fromNow': return chunk.write(moment(date).fromNow()); break; case 'subtract': return chunk.write(moment(date).subtract(input, value).calendar()); break; case 'add': return chunk.write(moment(date).add(input, value).calendar()); break; } }; }(typeof exports !== 'undefined' ? module.exports = require('dustjs-linkedin') : dust));
Check posix calls work on this platform
/** * Copyright (c) 2016, University of Glasgow. All Rights Reserved. * * Cloudera, Inc. licenses this file to you 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 * * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the * License. */ package probos; /** To use this test suite, you must have the following vars set: * HADOOP_HOME, JAVA_HOME */ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestSelectors.class, TestKittenUtils2.class, TestPBSJob.class, TestPBSLightJobStatus.class, TestPConfiguration.class, TestStaticMethods.class, TestPBSClientProtocol.class, TestPosix.class, TestQstat.class, TestToken.class, TestEndToEnd.class, TestQsub.class, }) public class ProbosSuite { }
/** * Copyright (c) 2016, University of Glasgow. All Rights Reserved. * * Cloudera, Inc. licenses this file to you 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 * * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the * License. */ package probos; /** To use this test suite, you must have the following vars set: * HADOOP_HOME, JAVA_HOME */ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ TestSelectors.class, TestKittenUtils2.class, TestPBSJob.class, TestPBSLightJobStatus.class, TestPConfiguration.class, TestStaticMethods.class, TestPBSClientProtocol.class, TestQstat.class, TestToken.class, TestEndToEnd.class, TestQsub.class, }) public class ProbosSuite { }
Add missing dependency to LayoutCtrl
angular.module("protonet.platform").controller("LayoutCtrl", function($scope, $state, API, App) { App.startFetcher(); $scope.apps = App.records; $scope.$on("$destroy", function() { App.stopFetcher(); }); $scope.$on("$stateChangeSuccess", function() { $scope.state = $state.current.name; }); $scope.isDashboard = function() { return $scope.state === "dashboard.index" || $scope.state.match(/create_app/); }; function setPTW(data) { $scope.nodename = data.nodename; $scope.ptwEnabled = data.enabled; } function updatePTW() { API.get("/admin/api/ptw").then(setPTW); } updatePTW(); $scope.logout = function() { API.post("/admin/api/logout").then(function() { $state.go("login"); }); }; $scope.$on("ptw.change", updatePTW); });
angular.module("protonet.platform").controller("LayoutCtrl", function($scope, $state, API) { App.startFetcher(); $scope.apps = App.records; $scope.$on("$destroy", function() { App.stopFetcher(); }); $scope.$on("$stateChangeSuccess", function() { $scope.state = $state.current.name; }); $scope.isDashboard = function() { return $scope.state === "dashboard.index" || $scope.state.match(/create_app/); }; function setPTW(data) { $scope.nodename = data.nodename; $scope.ptwEnabled = data.enabled; } function updatePTW() { API.get("/admin/api/ptw").then(setPTW); } updatePTW(); $scope.logout = function() { API.post("/admin/api/logout").then(function() { $state.go("login"); }); }; $scope.$on("ptw.change", updatePTW); });
Fix typo in log message
# -*- coding: utf-8 -*- from pelican import signals from subprocess import call import logging import os logger = logging.getLogger(__name__) # Display command output on DEBUG and TRACE SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG """ Minify CSS and JS files in output path with Yuicompressor from Yahoo Required : pip install yuicompressor """ def minify(pelican): """ Minify CSS and JS with YUI Compressor :param pelican: The Pelican instance """ for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']): for name in filenames: if os.path.splitext(name)[1] in ('.css','.js'): filepath = os.path.join(dirpath, name) logger.info('minify %s', filepath) verbose = '-v' if SHOW_OUTPUT else '' call("yuicompressor {} --charset utf-8 {} -o {}".format( verbose, filepath, filepath), shell=True) def register(): signals.finalized.connect(minify)
# -*- coding: utf-8 -*- from pelican import signals from subprocess import call import logging import os logger = logging.getLogger(__name__) # Display command output on DEBUG and TRACE SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG """ Minify CSS and JS files in output path with Yuicompressor from Yahoo Required : pip install yuicompressor """ def minify(pelican): """ Minify CSS and JS with YUI Compressor :param pelican: The Pelican instance """ for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']): for name in filenames: if os.path.splitext(name)[1] in ('.css','.js'): filepath = os.path.join(dirpath, name) logger.info('minifiy %s', filepath) verbose = '-v' if SHOW_OUTPUT else '' call("yuicompressor {} --charset utf-8 {} -o {}".format( verbose, filepath, filepath), shell=True) def register(): signals.finalized.connect(minify)
FIX dependency on aeroo rpoert
# -*- coding: utf-8 -*- { 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'l10n_ar_aeroo_invoice', #esta dependencia es porque actualizamos algo que crea portal_sale con un valor de las invoice 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'Argentinian Like Sale Order Aeroo Report', 'version': '1.0', 'category': 'Localization/Argentina', 'sequence': 14, 'summary': '', 'description': """ Argentinian Like Sale Order / Quotation Aeroo Report ==================================================== """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'report_extended_sale', 'l10n_ar_aeroo_base', 'portal_sale', ], 'data': [ 'report_configuration_defaults_data.xml', 'sale_order_report.xml', 'sale_order_template.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Remove obsolete code from migration package
package migrations import ( "github.com/diyan/assimilator/migrations/source" "github.com/GeertJohan/go.rice" "github.com/mattes/migrate" "github.com/pkg/errors" // Enable PostgreSQL driver for migration tool _ "github.com/mattes/migrate/database/postgres" ) func UpgradeDB(databaseURL string) error { // TODO Who should run `create database sentry_ci` statement? box, err := rice.FindBox("postgres") if err != nil { return errors.Wrap(err, "can not find db migrations") } sourceDriver, err := source.WithInstance(box) if err != nil { return errors.Wrap(err, "can not init source driver for db migrations") } m, err := migrate.NewWithSourceInstance("go.rice", sourceDriver, databaseURL) if err != nil { return errors.Wrap(err, "failed to upgrade database schema") } if err := m.Up(); err != nil { return errors.Wrap(err, "failed to upgrade database schema") } return nil }
package migrations import ( "github.com/GeertJohan/go.rice" "github.com/mattes/migrate" "github.com/pkg/errors" // Enable PostgreSQL driver for migration tool _ "github.com/mattes/migrate/database/postgres" // Enable File source for migration tool _ "github.com/mattes/migrate/source/file" // Enable go.rice source for migration tool "github.com/diyan/assimilator/migrations/source" ) func UpgradeDB(databaseURL string) error { // TODO Who is responsible to run `create database sentry_ci` statement? box, err := rice.FindBox("postgres") if err != nil { return errors.Wrap(err, "can not find db migrations") } sourceDriver, err := source.WithInstance(box) if err != nil { return errors.Wrap(err, "can not init source driver for db migrations") } m, err := migrate.NewWithSourceInstance("go.rice", sourceDriver, databaseURL) if err != nil { return errors.Wrap(err, "failed to upgrade database schema") } if err := m.Up(); err != nil { return errors.Wrap(err, "failed to upgrade database schema") } return nil }
Set py2app.__version__ using pkg_resources, that ensures that the version stays in sync with the value in setup.py
""" builds Mac OS X application bundles from Python scripts New keywords for distutils' setup function specify what to build: app list of scripts to convert into gui app bundles py2app options, to be specified in the options keyword to the setup function: optimize - string or int (0, 1, or 2) includes - list of module names to include packages - list of packages to include with subpackages ignores - list of modules to ignore if they are not found excludes - list of module names to exclude dylib_excludes - list of dylibs and/or frameworks to exclude resources - list of additional files and folders to include plist - Info.plist template file, dict, or plistlib.Plist dist_dir - directory where to build the final files Items in the macosx list can also be dictionaries to further customize the build process. The following keys in the dictionary are recognized, most are optional: script (MACOSX) - list of python scripts (required) dest_base - directory and basename for the executable if a directory is contained, must be the same for all targets """ import pkg_resources __version__ = pkg_resources.require('py2app')[0].version # This makes the py2app command work in the distutils.core.setup() case import setuptools
""" builds Mac OS X application bundles from Python scripts New keywords for distutils' setup function specify what to build: app list of scripts to convert into gui app bundles py2app options, to be specified in the options keyword to the setup function: optimize - string or int (0, 1, or 2) includes - list of module names to include packages - list of packages to include with subpackages ignores - list of modules to ignore if they are not found excludes - list of module names to exclude dylib_excludes - list of dylibs and/or frameworks to exclude resources - list of additional files and folders to include plist - Info.plist template file, dict, or plistlib.Plist dist_dir - directory where to build the final files Items in the macosx list can also be dictionaries to further customize the build process. The following keys in the dictionary are recognized, most are optional: script (MACOSX) - list of python scripts (required) dest_base - directory and basename for the executable if a directory is contained, must be the same for all targets """ __version__ = "0.4.4" # This makes the py2app command work in the distutils.core.setup() case import setuptools
Add default values for google strategy
'use strict'; module.exports = { app: { name: "OpenIt - Control your Raspberry Pi" }, facebook: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/facebook/callback" }, twitter: { clientID: "CONSUMER_KEY", clientSecret: "CONSUMER_SECRET", callbackURL: "http://localhost:3000/auth/twitter/callback" }, github: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/github/callback" }, google: { clientID: process.env.GOOGLE_APP_ID || "APP_ID" , clientSecret: process.env.GOOGLE_APP_SECRET || "APP_SECRET", callbackURL: process.env.GOOGLE_CALLBACK || "http://localhost:3000/auth/google/callback" } }
'use strict'; module.exports = { app: { name: "OpenIt - Control your Raspberry Pi" }, facebook: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/facebook/callback" }, twitter: { clientID: "CONSUMER_KEY", clientSecret: "CONSUMER_SECRET", callbackURL: "http://localhost:3000/auth/twitter/callback" }, github: { clientID: "APP_ID", clientSecret: "APP_SECRET", callbackURL: "http://localhost:3000/auth/github/callback" }, google: { clientID: process.env.GOOGLE_APP_ID, clientSecret: process.env.GOOGLE_APP_SECRET, callbackURL: process.env.GOOGLE_CALLBACK } }
Fix a bug that caused side effects between list() and run().
if (!('requireModule' in global)) { const join = require('path').join; const appRoot = join('..', __dirname); global.requireModule = (module) => require(join(appRoot, module)); } const profiles = requireModule('lib/profiles'); const DEFAULTS = requireModule('lib/support/defaults'); const ProfileRunner = requireModule('lib/profile-runner'); const Reporter = requireModule('lib/reporter/reporter'); const ConsoleReporter = requireModule('lib/reporter/console'); const JSONReporter = requireModule('lib/reporter/json'); module.exports = { list: (verbosity = DEFAULTS.verbosity) => profiles.map((profile) => ({ name: profile.name, description: profile.description(verbosity) })), run: (options = DEFAULTS) => { let p = profiles.slice(); if (Array.isArray(options.profiles)) { p = profiles.filter((profile) => options.profiles.includes(profile.name)); } let reporter; if (options.json) { reporter = new JSONReporter(options); } else if (options.console) { reporter = new ConsoleReporter(options); } else { reporter = new Reporter(options); } const profileRunner = new ProfileRunner({ iterations: options.iterations, magnitude: options.magnitude, profiles: p }); const promise = reporter.reportOn(profileRunner); profileRunner.run(); return promise; } };
if (!('requireModule' in global)) { const join = require('path').join; const appRoot = join('..', __dirname); global.requireModule = (module) => require(join(appRoot, module)); } let profiles = requireModule('lib/profiles'); const DEFAULTS = requireModule('lib/support/defaults'); const ProfileRunner = requireModule('lib/profile-runner'); const Reporter = requireModule('lib/reporter/reporter'); const ConsoleReporter = requireModule('lib/reporter/console'); const JSONReporter = requireModule('lib/reporter/json'); module.exports = { list: (verbosity = DEFAULTS.verbosity) => profiles.map((profile) => ({ name: profile.name, description: profile.description(verbosity) })), run: (options = DEFAULTS) => { if (Array.isArray(options.profiles)) { profiles = profiles.filter((profile) => options.profiles.includes(profile.name)); } let reporter; if (options.json) { reporter = new JSONReporter(options); } else if (options.console) { reporter = new ConsoleReporter(options); } else { reporter = new Reporter(options); } const profileRunner = new ProfileRunner({ iterations: options.iterations, magnitude: options.magnitude, profiles }); const promise = reporter.reportOn(profileRunner); profileRunner.run(); return promise; } };
Fix carrying kramed links around
var _ = require('lodash'); // Split a page up into sections (lesson, exercises, ...) function split(nodes) { var section = []; var sections = _.chain(nodes) .reduce(function(sections, el) { if(el.type === 'hr') { sections.push(section); section = []; } else { section.push(el); } return sections; }, []) // Add remaining nodes .concat([section]) // Exclude empty sections .filter(_.negate(_.isEmpty)) // Spit out JS array .value(); // Copy over links (kramed needs them) sections.links = nodes.links || {}; return sections; } function join(sections) { var nodes = _.reduce(sections, function(nodes, section) { return nodes.concat(section); }, []); // Restore links (needed by kramed) nodes.links = sections.links || {}; return nodes; } module.exports = { split: split, join: split, };
var _ = require('lodash'); // Split a page up into sections (lesson, exercises, ...) function split(nodes) { var section = []; return _.chain(nodes) .reduce(function(sections, el) { if(el.type === 'hr') { sections.push(section); section = []; section.links = nodes.links || {}; } else { section.push(el); } return sections; }, []) // Add remaining nodes .concat([section]) // Exclude empty sections .filter(_.negate(_.isEmpty)) // Spit out JS array .value(); } function join(sections) { var nodes = _.reduce(sections, function(nodes, section) { return nodes.concat(section); }, []); nodes.links = (sections[0] && (sections[0].links) || {}); return nodes; } module.exports = { split: split, join: split, };
Update typescript plugin patch version to match npm version.
Package.describe({ name: "typescript", version: "3.6.3-rc182.3", summary: "Compiler plugin that compiles TypeScript and ECMAScript in .ts and .tsx files", documentation: "README.md" }); Package.registerBuildPlugin({ name: "compile-typescript", use: ["babel-compiler"], sources: ["plugin.js"] }); Package.onUse(function (api) { api.use("isobuild:compiler-plugin@1.0.0"); // The following api.imply calls should match those in // ../ecmascript/package.js. api.imply("modules"); api.imply("ecmascript-runtime"); api.imply("babel-runtime"); api.imply("promise"); // Runtime support for Meteor 1.5 dynamic import(...) syntax. api.imply("dynamic-import"); }); Package.onTest(function (api) { api.use("tinytest"); api.use("es5-shim"); api.use("typescript"); api.mainModule("tests.ts"); });
Package.describe({ name: "typescript", version: "3.6.2-rc182.3", summary: "Compiler plugin that compiles TypeScript and ECMAScript in .ts and .tsx files", documentation: "README.md" }); Package.registerBuildPlugin({ name: "compile-typescript", use: ["babel-compiler"], sources: ["plugin.js"] }); Package.onUse(function (api) { api.use("isobuild:compiler-plugin@1.0.0"); // The following api.imply calls should match those in // ../ecmascript/package.js. api.imply("modules"); api.imply("ecmascript-runtime"); api.imply("babel-runtime"); api.imply("promise"); // Runtime support for Meteor 1.5 dynamic import(...) syntax. api.imply("dynamic-import"); }); Package.onTest(function (api) { api.use("tinytest"); api.use("es5-shim"); api.use("typescript"); api.mainModule("tests.ts"); });
Make sure navigate is passed to controllers res
'use strict'; import Router from './base' import utils from '../utils' class DragonDispatcher { constructor(options = {}) { this.uid = utils.uniqueId(this) this.options = options this.app = options.app this.currentController = null } dispatch(route, params, options = {}) { if(this.currentController && this.currentController.dispose) { this.currentController.dispose() } var req = { params: params } var res = { navigate: Router.navigate } var controller = null if(options.Controller) { controller = new options.Controller() controller[options.action](req, res, this.next) } else { var segs = route.pattern.split('/') var controllerName = segs[1], actionName = options.action || segs[2] var Controller = this.options.getController(controllerName) controller = new Controller() controller[actionName](req, res, this.next) } this.currentController = controller } next() { } dispose() { if(!this.disposed) { utils.dispose(this, { ignoreProperties: ['app'] }) } } } DragonDispatcher.prototype.disposed = false export default DragonDispatcher
'use strict'; import utils from '../utils' class DragonDispatcher { constructor(options = {}) { this.uid = utils.uniqueId(this) this.options = options this.app = options.app this.currentController = null } dispatch(route, params, options = {}) { if(this.currentController && this.currentController.dispose) { this.currentController.dispose() } var req = { params: params } var controller = null if(options.Controller) { controller = new options.Controller() controller[options.action](req) } else { var segs = route.pattern.split('/') var controllerName = segs[1], actionName = options.action || segs[2] var Controller = this.options.getController(controllerName) controller = new Controller() controller[actionName](req) } this.currentController = controller } dispose() { if(!this.disposed) { utils.dispose(this, { ignoreProperties: ['app'] }) } } } DragonDispatcher.prototype.disposed = false export default DragonDispatcher
Disable matomo since it's misconfigured anyway
// function init() { // window._paq = window._paq || []; // } // function paq() { // return window._paq; // } // function installed() { // return !!paq(); // } // function push(...args) { // return paq().push(...args); // } export function install() { if (process.env.NODE_ENV === 'production') { // init(); // /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ // push(['trackPageView']); // push(['enableLinkTracking']); // // const u = 'https://matomo.wowanalyzer.com/'; // push(['setTrackerUrl', u + 'js/']); // push(['setSiteId', '1']); // const d = document; // const g = d.createElement('script'); // const s = d.getElementsByTagName('script')[0]; // g.type = 'text/javascript'; // g.async = true; // g.defer = true; // g.src = u + 'js/'; // s.parentNode.insertBefore(g, s); } } export function track(oldLocation, newLocation) { // if (installed()) { // push(['setReferrerUrl', oldLocation]); // push(['setDocumentTitle', document.title]); // push(['setCustomUrl', newLocation]); // push(['trackPageView']); // } }
function init() { window._paq = window._paq || []; } function paq() { return window._paq; } function installed() { return !!paq(); } function push(...args) { return paq().push(...args); } export function install() { if (process.env.NODE_ENV === 'production') { init(); /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ push(['trackPageView']); push(['enableLinkTracking']); const u = 'https://matomo.wowanalyzer.com/'; push(['setTrackerUrl', u + 'js/']); push(['setSiteId', '1']); const d = document; const g = d.createElement('script'); const s = d.getElementsByTagName('script')[0]; g.type = 'text/javascript'; g.async = true; g.defer = true; g.src = u + 'js/'; s.parentNode.insertBefore(g, s); } } export function track(oldLocation, newLocation) { if (installed()) { push(['setReferrerUrl', oldLocation]); push(['setDocumentTitle', document.title]); push(['setCustomUrl', newLocation]); push(['trackPageView']); } }
Swap opcodes for if-else and unless-else. Oops.
..compile = import ..parse.syntax = import compile.r.builtins !! 'else' = (self, cond, otherwise) -> ''' a if b else c a unless b else c Ternary conditional. ''' is_if, (then, cond) = parse.syntax.else_: cond ptr = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 if is_if ptr = self.opcode: 'POP_JUMP_IF_TRUE' cond delta: 0 unless is_if jmp = self.opcode: 'JUMP_FORWARD' then delta: 0 ptr: self.load: otherwise jmp: compile.r.builtins !! 'switch' = (self, cases) -> ''' switch $ condition1 = when_condition1_is_true ... conditionN = when_conditionN_is_true Evaluate the first action assigned to a true condition. `if-elif` is probably a better equivalent than `switch-case`. ''' jumps = list $ map: c -> ( cond, action = c next = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 end = self.opcode: 'JUMP_FORWARD' action delta: 0 next: end ) $ parse.syntax.switch: cases self.load: None # in case nothing matched list $ map: x -> (x:) jumps
..compile = import ..parse.syntax = import compile.r.builtins !! 'else' = (self, cond, otherwise) -> ''' a if b else c a unless b else c Ternary conditional. ''' is_if, (then, cond) = parse.syntax.else_: cond ptr = self.opcode: 'POP_JUMP_IF_TRUE' cond delta: 0 if is_if ptr = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 unless is_if jmp = self.opcode: 'JUMP_FORWARD' then delta: 0 ptr: self.load: otherwise jmp: compile.r.builtins !! 'switch' = (self, cases) -> ''' switch $ condition1 = when_condition1_is_true ... conditionN = when_conditionN_is_true Evaluate the first action assigned to a true condition. `if-elif` is probably a better equivalent than `switch-case`. ''' jumps = list $ map: c -> ( cond, action = c next = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 end = self.opcode: 'JUMP_FORWARD' action delta: 0 next: end ) $ parse.syntax.switch: cases self.load: None # in case nothing matched list $ map: x -> (x:) jumps
Fix test case to not fail due to varying timing (again)
/*global describe, it*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var assert = require('assert'); var run = require('./fixture/run'); describe('stack', function () { this.timeout(3000); it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); var expect = '<testcase classname="test" name="passes" time="0'; assert.equal(lines[1].substring(0, expect.length), expect); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done(); }); }); });
/*global describe, it*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var assert = require('assert'); var run = require('./fixture/run'); describe('stack', function () { this.timeout(3000); it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1].substring(0, lines[1].length - 3), '<testcase classname="test" name="passes" time="0'); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done(); }); }); });
Use the dist file when testing with karma
module.exports = function (config) { 'use strict'; config.set({ basePath: './', files: [ { pattern: 'dist/peeracle-0.0.1.js', included: true }, 'dist/peeracle-0.0.1.js', 'spec/**/*-spec.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome', 'Firefox'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-coverage', 'karma-junit-reporter', 'karma-verbose-reporter' ], reporters: ['verbose', 'junit', 'coverage'], preprocessors: { 'dist/peeracle-0.0.1.js': ['coverage'] }, coverageReporter: { type: 'html', dir: 'coverage/browser' }, junitReporter: { outputFile: 'reports/unit.xml', suite: 'unit' }, singleRun: true }); };
module.exports = function (config) { 'use strict'; config.set({ basePath: './', files: [ { pattern: 'dist/peeracle-0.0.1.js', included: true }, 'spec/**/*-spec.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Chrome', 'Firefox'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-verbose-reporter' ], reporters: ['verbose', 'junit'], junitReporter: { outputFile: 'unit.xml', suite: 'unit' }, singleRun: true }); };
Add temporary mock backend url to Android app for local testing
package com.blocksolid.okrello.api; import com.facebook.stetho.okhttp3.StethoInterceptor; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Dan Buckland on 04/02/2016. */ public class ServiceGenerator { // TODO move these to a Strings file which can be updated from rake task // public static final String BASE_URL = "https://api.trello.com/1/"; // production public static final String BASE_URL = "http://192.168.1.123:9292/"; // mock backend with emulator private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); private static Interceptor logging = interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); private static OkHttpClient httpClient = new OkHttpClient.Builder() .addNetworkInterceptor(new StethoInterceptor()) .addInterceptor(logging) .build(); private static Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()); public static <S> S createService(Class<S> serviceClass) { Retrofit retrofit = builder.client(httpClient).build(); return retrofit.create(serviceClass); } }
package com.blocksolid.okrello.api; import com.facebook.stetho.okhttp3.StethoInterceptor; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Dan Buckland on 04/02/2016. */ public class ServiceGenerator { // public static final String BASE_URL = "https://api.trello.com/1/"; // production public static final String BASE_URL = "http://10.0.2.2:9292/"; // mock backend with emulator private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); private static Interceptor logging = interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); private static OkHttpClient httpClient = new OkHttpClient.Builder() .addNetworkInterceptor(new StethoInterceptor()) .addInterceptor(logging) .build(); private static Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()); public static <S> S createService(Class<S> serviceClass) { Retrofit retrofit = builder.client(httpClient).build(); return retrofit.create(serviceClass); } }
Check for navigator.id.watch when initializing
(function() { // wait for polyfill to be loaded if (document.readyState == "complete") { init(); } else { window.addEventListener('load', init); } var loggedIn = false; function init() { // just quit if no navigator observer API available if (!navigator.id || !navigator.id.watch) return; sendToContent({ type: "init" }); window.addEventListener('browserid-exec', onMessage); navigator.id.watch({ onlogin: onLogin, onlogout: onLogout }); } function onLogin(assertion) { console.log('onLogin'); loggedIn = true; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onLogout() { console.log('onLogout'); loggedIn = false; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onMessage(event) { console.log('message received in agent'); console.log(event.detail); var data = event.detail; if (data.type == 'request-login') { navigator.id.request(); } else if (data.type == 'request-logout') { navigator.id.logout(); } } function sendToContent(message) { window.postMessage(message, "*"); } })();
(function() { // wait for polyfill to be loaded if (document.readyState == "complete") { init(); } else { window.addEventListener('load', init); } var loggedIn = false; function init() { if (!navigator.id) return; sendToContent({ type: "init" }); window.addEventListener('browserid-exec', onMessage); navigator.id.watch({ onlogin: onLogin, onlogout: onLogout }); } function onLogin(assertion) { console.log('onLogin'); loggedIn = true; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onLogout() { console.log('onLogout'); loggedIn = false; sendToContent({ type: 'auth', loggedIn: loggedIn }); } function onMessage(event) { console.log('message received in agent'); console.log(event.detail); var data = event.detail; if (data.type == 'request-login') { navigator.id.request(); } else if (data.type == 'request-logout') { navigator.id.logout(); } } function sendToContent(message) { window.postMessage(message, "*"); } })();
Bugfix: Use valid columns in address filter
(function() { 'use strict'; /** * Generate a human-readable address string from a single museum object * * Can get fancy here and prioritize one of the three address types provided: * source address, geocoded address, physical address * * For now, default to geocoded address since that's what seems to always be populated */ /* ngInject */ function AddressFilter() { return function (input) { var address = input.adstreet; var city = input.adcity; var state = input.adstate; var zip = input.adzip; return address + ', ' + city + ', ' + state + ' ' + zip; }; } angular.module('imls.museum') .filter('imlsAddress', AddressFilter); })();
(function() { 'use strict'; /** * Generate a human-readable address string from a single museum object * * Can get fancy here and prioritize one of the three address types provided: * source address, geocoded address, physical address * * For now, default to geocoded address since that's what seems to always be populated */ /* ngInject */ function AddressFilter() { return function (input) { var address = input.gaddress; var city = input.gcity; var state = input.gstate; var zip = input.gzip; return address + ', ' + city + ', ' + state + ' ' + zip; }; } angular.module('imls.museum') .filter('imlsAddress', AddressFilter); })();
Add ordering to queryset in reindex admin command
from django.core.management.base import NoArgsCommand from bulbs.content.models import Content class Command(NoArgsCommand): help = 'Runs Content.index on all content.' def handle(self, **options): num_processed = 0 content_count = Content.objects.all().count() chunk_size = 10 while num_processed < content_count: for content in Content.objects.all().order_by('id')[num_processed:num_processed + chunk_size]: content.index() num_processed += 1 if not num_processed % 100: print 'Processed %d content items' % num_processed
from django.core.management.base import NoArgsCommand from bulbs.content.models import Content class Command(NoArgsCommand): help = 'Runs Content.index on all content.' def handle(self, **options): num_processed = 0 content_count = Content.objects.all().count() chunk_size = 10 while num_processed < content_count: for content in Content.objects.all()[num_processed:num_processed + chunk_size]: content.index() num_processed += 1 if not num_processed % 100: print 'Processed %d content items' % num_processed
Make DELIMITER a method rather than a constant
/* * Copyright (C) 2008 TranceCode Software * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.trancecode.io; /** * Utility methods related to file paths handling. * * @author Herve Quiroz */ public final class Paths { private Paths() { // No instantiation } public static String delimiter() { return "/"; } public static String asAbsolutePath(final String path) { if (path.startsWith(delimiter())) { return path; } return delimiter() + path; } public static String asDirectory(final String path) { if (path.endsWith(delimiter())) { return path; } return path + delimiter(); } }
/* * Copyright (C) 2008 TranceCode Software * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ package org.trancecode.io; /** * Utility methods related to file paths handling. * * @author Herve Quiroz */ public final class Paths { private static final String PATH_DELIMITER = "/"; private Paths() { // No instantiation } public static String asAbsolutePath(final String path) { if (path.startsWith(PATH_DELIMITER)) { return path; } return PATH_DELIMITER + path; } public static String asDirectory(final String path) { if (path.endsWith(PATH_DELIMITER)) { return path; } return path + PATH_DELIMITER; } }
Remove another constant and shorten require path
const redis = require('./redis'); const config = require('../config'); const getRequest = async (requestId) => { // Set TTL for request redis.expire(`requests:${requestId}`, config('requests_ttl')); return await redis.hgetallAsync(`requests:${requestId}`); }; const createRequest = async (requestDetails) => { // get new unique id for request const requestId = await redis.incrAsync('next_request_id'); // create a new request entry in Redis const {user_id, pickup, dropoff, requested_pickup_time, size, weight} = requestDetails; const [pickup_lat, pickup_long] = pickup.split(','); const [dropoff_lat, dropoff_long] = dropoff.split(','); redis.hmsetAsync(`requests:${requestId}`, 'user_id', user_id, 'pickup_lat', pickup_lat, 'pickup_long', pickup_long, 'dropoff_lat', dropoff_lat, 'dropoff_long', dropoff_long, 'requested_pickup_time', requested_pickup_time, 'size', size, 'weight', weight, ); // Set TTL for request redis.expire(`requests:${requestId}`, config('requests_ttl')); return requestId; }; const deleteRequest = async (requestId) => { return await redis.del(`requests:${requestId}`); }; module.exports = { createRequest, getRequest, deleteRequest };
const redis = require('./redis'); const config = require('../config/index.js'); const getRequest = async (requestId) => { // Set TTL for request redis.expire(`requests:${requestId}`, config('requests_ttl')); return await redis.hgetallAsync(`requests:${requestId}`); }; const createRequest = async (requestDetails) => { // get new unique id for request const requestId = await redis.incrAsync('next_request_id'); // create a new request entry in Redis const {user_id, pickup, dropoff, requested_pickup_time, size, weight} = requestDetails; const [pickup_lat, pickup_long] = pickup.split(','); const [dropoff_lat, dropoff_long] = dropoff.split(','); redis.hmsetAsync(`requests:${requestId}`, 'user_id', user_id, 'pickup_lat', pickup_lat, 'pickup_long', pickup_long, 'dropoff_lat', dropoff_lat, 'dropoff_long', dropoff_long, 'requested_pickup_time', requested_pickup_time, 'size', size, 'weight', weight, ); // Set TTL for request redis.expire(`requests:${requestId}`, 43200); return requestId; }; const deleteRequest = async (requestId) => { return await redis.del(`requests:${requestId}`); }; module.exports = { createRequest, getRequest, deleteRequest };
Fix close button visibility on smaller screens
'use strict'; const React = require('react'); const {string, func} = React.PropTypes; const InventoryDetail = React.createClass({ displayName: 'InventoryDetail', propTypes: { // state name: string.isRequired, type: string.isRequired, image: string.isRequired, //actions close: func.isRequired }, render() { return ( <div style={styles.container}> <img title={this.props.name} src={this.props.image} style={styles.image} /> <div> <button style={styles.button} className='red-button' onClick={this.props.close}> Close </button> </div> </div> ); } }); const styles = { container: { textAlign: 'center', float: 'none' }, image: { height: '80vh', padding: '5vh' }, button: { display: 'inline-block' } }; module.exports = InventoryDetail;
'use strict'; const React = require('react'); const {string, func} = React.PropTypes; const InventoryDetail = React.createClass({ displayName: 'InventoryDetail', propTypes: { // state name: string.isRequired, type: string.isRequired, image: string.isRequired, //actions close: func.isRequired }, render() { return ( <div style={styles.container}> <img title={this.props.name} src={this.props.image} style={styles.image} /> <button className='red-button' onClick={this.props.close}> Close </button> </div> ); } }); const styles = { container: { textAlign: 'center' }, image: { width: '75%', padding: '40px' } }; module.exports = InventoryDetail;
Update Iuchi Daiyu to use AbilityDsl
const DrawCard = require('../../drawcard.js'); const AbilityDsl = require('../../abilitydsl'); class IuchiDaiyu extends DrawCard { setupCardAbilities() { this.action({ title: '+1 military for each faceup province', condition: () => this.game.isDuringConflict(), target: { gameAction: AbilityDsl.actions.cardLastingEffect(context => ({ effect: AbilityDsl.effects.modifyMilitarySkill(context.player.getNumberOfOpponentsFaceupProvinces()) })) }, effect: 'give {0} +1{1} for each faceup non-stronghold province their opponent controls (+{2}{1})', effectArgs: context => ['military', context.player.getNumberOfOpponentsFaceupProvinces()] }); } } IuchiDaiyu.id = 'iuchi-daiyu'; module.exports = IuchiDaiyu;
const DrawCard = require('../../drawcard.js'); class IuchiDaiyu extends DrawCard { setupCardAbilities(ability) { this.action({ title: '+1 military for each faceup province', condition: () => this.game.isDuringConflict(), target: { gameAction: ability.actions.cardLastingEffect(context => ({ effect: ability.effects.modifyMilitarySkill(context.player.getNumberOfOpponentsFaceupProvinces()) })) }, effect: 'give {0} +1{1} for each faceup non-stronghold province their opponent controls (+{2}{1})', effectArgs: context => ['military', context.player.getNumberOfOpponentsFaceupProvinces()] }); } } IuchiDaiyu.id = 'iuchi-daiyu'; module.exports = IuchiDaiyu;
Remove cert requirements from hopefully last spot
"""Heroku web worker.""" listen = ["high", "default", "low"] def main(): import gevent.monkey gevent.monkey.patch_all() from gevent.queue import LifoQueue # These imports are inside the __main__ block # to make sure that we only import from rq_gevent_worker # (which has the side effect of applying gevent monkey patches) # in the worker process. This way other processes can import the # redis connection without that side effect. import os from redis import BlockingConnectionPool, StrictRedis from rq import Queue, Connection from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker from dallinger.config import initialize_experiment_package initialize_experiment_package(os.getcwd()) import logging logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG) redis_url = os.getenv("REDIS_URL", "redis://localhost:6379") # Specify queue class for improved performance with gevent. # see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/ redis_pool = BlockingConnectionPool.from_url( url=redis_url, ssl_cert_reqs="none", queue_class=LifoQueue ) redis_conn = StrictRedis(connection_pool=redis_pool) with Connection(redis_conn): worker = Worker(list(map(Queue, listen))) worker.work() if __name__ == "__main__": # pragma: nocover main()
"""Heroku web worker.""" listen = ["high", "default", "low"] def main(): import gevent.monkey gevent.monkey.patch_all() from gevent.queue import LifoQueue # These imports are inside the __main__ block # to make sure that we only import from rq_gevent_worker # (which has the side effect of applying gevent monkey patches) # in the worker process. This way other processes can import the # redis connection without that side effect. import os from redis import BlockingConnectionPool, StrictRedis from rq import Queue, Connection from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker from dallinger.config import initialize_experiment_package initialize_experiment_package(os.getcwd()) import logging logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG) redis_url = os.getenv("REDIS_URL", "redis://localhost:6379") # Specify queue class for improved performance with gevent. # see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/ redis_pool = BlockingConnectionPool.from_url(redis_url, queue_class=LifoQueue) redis_conn = StrictRedis(connection_pool=redis_pool) with Connection(redis_conn): worker = Worker(list(map(Queue, listen))) worker.work() if __name__ == "__main__": # pragma: nocover main()
Fix init_db and clear_db functions
import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss.exceptions import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, client_encoding='utf8') Session = sessionmaker(bind=engine) @contextmanager def session_scope(SessionFactory=None): """Provide a transactional scope around a series of operations.""" if SessionFactory is None: SessionFactory = Session session = SessionFactory() try: yield session except SQLAlchemyError as e: _logger.error("Database error %s", e) session.rollback() raise OperationInterruptedException(e) else: session.commit() finally: session.close() def init_db(eng=None): _logger.info('Initializing database') if eng is None: eng = engine from rtrss.models import Base Base.metadata.create_all(bind=eng) def clear_db(eng=None): _logger.info('Clearing database') if eng is None: eng = engine from rtrss.models import Base Base.metadata.drop_all(bind=eng)
import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss.exceptions import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, client_encoding='utf8') Session = sessionmaker(bind=engine) @contextmanager def session_scope(SessionFactory=None): """Provide a transactional scope around a series of operations.""" if SessionFactory is None: SessionFactory = Session session = SessionFactory() try: yield session except SQLAlchemyError as e: _logger.error("Database error %s", e) session.rollback() raise OperationInterruptedException(e) else: session.commit() finally: session.close() def init_db(): _logger.info('Initializing database') from rtrss.models import Base Base.metadata.create_all(bind=engine) def clear_db(): _logger.info('Clearing database') from rtrss.models import Base Base.metadata.drop_all(bind=engine)
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-max-widths/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-max-widths/tachyons-max-widths.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_max-widths.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/max-widths/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ module: module, moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/layout/max-widths/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-max-widths/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-max-widths/tachyons-max-widths.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_max-widths.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/max-widths/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ module: module, moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/layout/max-widths/index.html', html)
Change in the acme command
<?php namespace Ketmo\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class AcmeCommand extends Command { protected function configure() { $this ->setName('acme') ->setDescription('Hack me') ->addArgument('name', InputArgument::OPTIONAL) ->addOption('yell', null, InputOption::VALUE_NONE) ; } protected function execute(InputInterface $input, OutputInterface $output) { $text = '<info>Hi</info>'; $name = $input->getArgument('name'); if ($name) { $text .= ' <comment>'.$name.'</comment>'; } if ($input->getOption('yell')) { $text .= ' !!!'; } $output->writeln($text); } }
<?php namespace Ketmo\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class AcmeCommand extends Command { protected function configure() { $this ->setName('acme') ->setDescription('Hack me') ->addArgument('name', InputArgument::OPTIONAL) ->addOption('yell', null, InputOption::VALUE_NONE) ; } protected function execute(InputInterface $input, OutputInterface $output) { $text = '<info>Hello</info>'; $name = $input->getArgument('name'); if ($name) { $text .= ' <comment>'.$name.'</comment>'; } if ($input->getOption('yell')) { $text .= ' !!!'; } $output->writeln($text); } }
Create complete zip of app
/*jshint node:true */ "use strict"; var fs = require("fs"), path = require("path"), shell = require("shelljs"), archiver = require("archiver"); module.exports = function(config, done) { var zip = archiver("zip", { zlib : { level : 0 }}), dest = fs.createWriteStream(path.join("./temp", config.app + ".nw")); dest.on("close", done); zip.on("error", done); zip.pipe(dest); shell.ls("-R", config.temp) .filter(function(item) { return fs.statSync(item).isFile(); }) .forEach(function(file) { zip.append( fs.createReadStream(file), { name : file } ); }); zip.finalize(function(err, bytes) { if (err) { return done(err); } config.log("Wrote " + bytes + " bytes"); }); };
/*jshint node:true */ "use strict"; var fs = require("fs"), shell = require("shelljs"), archiver = require("archiver"); module.exports = function(config, done) { var zip = archiver("zip", { zlib : { level : 0 }}), dest = fs.createWriteStream("./dist/" + config.app + ".nw"); dest.on("close", done); zip.on("error", done); zip.pipe(dest); shell.ls("-R", config.temp) .filter(function(item) { return fs.statSync(item).isFile(); }) .forEach(function(file) { zip.append(fs.createReadStream(file), { name : file }); }); zip.finalize(function(err, bytes) { if (err) { return done(err); } config.log("Wrote " + bytes + " bytes"); }); };
Fix redirection url for GeoJSON
/* ** Module dependencies */ var datasets = require('../controllers/datasets'); module.exports = function(app) { // Params app.param('datasetId', datasets.dataset); // Routes app.route('/datasets/:datasetId') .get(datasets.show); app.route('/datasets/:datasetId/resources/:resourceId/json') .get(function (req, res) { res.redirect('/api/datasets/' + req.params.datasetId + '/resources/' + req.params.resourceId + '/download?format=GeoJSON&projection=WGS84'); }); app.route('/datasets/:datasetId/resources/:resourceId/download') .get(datasets.downloadRelatedResource); app.route('/datasets/by-identifier/:identifier') .get(datasets.findByIdentifier); app.route('/datasets/:datasetId/force-reprocess') .post(datasets.forceReprocess); };
/* ** Module dependencies */ var datasets = require('../controllers/datasets'); module.exports = function(app) { // Params app.param('datasetId', datasets.dataset); // Routes app.route('/datasets/:datasetId') .get(datasets.show); app.route('/datasets/:datasetId/resources/:resourceId/json') .get(function (req, res) { res.redirect('/datasets/' + req.params.datasetId + '/resources/' + req.params.resourceId + '/download?format=GeoJSON&projection=WGS84'); }); app.route('/datasets/:datasetId/resources/:resourceId/download') .get(datasets.downloadRelatedResource); app.route('/datasets/by-identifier/:identifier') .get(datasets.findByIdentifier); app.route('/datasets/:datasetId/force-reprocess') .post(datasets.forceReprocess); };
Add recipients param to send_sms method.
from django.apps import apps from django.template.loader import render_to_string from turbosms.settings import IS_SMS_ENABLED, SMS_RECIPIENTS from turbosms.models import SMS def get_default_sms_recipients(): if apps.is_installed('site_config'): from site_config import config if hasattr(config, 'SMS_RECIPIENTS'): return config.SMS_RECIPIENTS return SMS_RECIPIENTS def send_sms(message, recipients=None): if not IS_SMS_ENABLED: return if recipients is None: recipients = get_default_sms_recipients() for number in recipients: SMS.objects.create(number=number, message=message) def send_sms_from_template(template_name, context=None): message = render_to_string(template_name, context) send_sms(message)
from django.apps import apps from django.template.loader import render_to_string from turbosms.settings import IS_SMS_ENABLED, SMS_RECIPIENTS from turbosms.models import SMS def get_recipients(): if apps.is_installed('site_config'): from site_config import config if hasattr(config, 'SMS_RECIPIENTS'): return config.SMS_RECIPIENTS return SMS_RECIPIENTS def send_sms(message): if IS_SMS_ENABLED: for number in get_recipients(): SMS.objects.create(number=number, message=message) def send_sms_from_template(template_name, context=None): message = render_to_string(template_name, context) send_sms(message)