text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Clear Loki when connection lost
/** * @license * The MIT License (MIT) * Copyright 2015 Government of Canada * * @author * Ian Boyes * * @exports Bar */ import React from "react"; import { forIn } from "lodash"; import ChildBar from "./Child/Bar"; import ParentBar from "./Parent/Bar"; import LostConnection from "./LostConnection"; /** * A container component that renders the primary and secondary navigation bars. */ export default class Bar extends React.Component { constructor (props) { super(props); this.state = { closed: false }; } componentDidMount () { dispatcher.on("closed", this.showLostConnection); } componentWillUnmount () { dispatcher.off("closed", this.showLostConnection); } showLostConnection = () => { forIn(dispatcher.db.collectionNames, collectionName => { dispatcher.db[collectionName].clear(); }); dispatcher.db.loki.saveDatabase(() => this.setState({closed: true})); }; render = () => ( <div> <ParentBar /> <ChildBar /> <LostConnection show={this.state.closed} onHide={this.showLostConnection} /> </div> ); }
/** * @license * The MIT License (MIT) * Copyright 2015 Government of Canada * * @author * Ian Boyes * * @exports Bar */ import React from "react"; import ChildBar from "./Child/Bar"; import ParentBar from "./Parent/Bar"; import LostConnection from "./LostConnection"; /** * A container component that renders the primary and secondary navigation bars. */ export default class Bar extends React.Component { constructor (props) { super(props); this.state = { closed: false }; } componentDidMount () { dispatcher.on("closed", this.showLostConnection); } componentWillUnmount () { dispatcher.off("closed", this.showLostConnection); } showLostConnection = () => { this.setState({ closed: true }); }; render = () => ( <div> <ParentBar /> <ChildBar /> <LostConnection show={this.state.closed} onHide={this.showLostConnection} /> </div> ); }
[Optimization:Speed] Replace is_null with strict identical operator
<?php /** * Many changes have been made in this file. * By Pierre-Henry SORIA. */ namespace PFBC; use PH7\Framework\Security\Validate\Validate; abstract class Validation extends Base { protected $oValidate, $message; public function __construct($message = '') { $this->oValidate = new Validate; if (!empty($message)) { $this->message = t('%element% is invalid.'); } } public function getMessage() { return $this->message; } public function isNotApplicable($value) { return ($value === null || is_array($value) || $value === ''); } public abstract function isValid($value); }
<?php /** * Many changes have been made in this file. * By Pierre-Henry SORIA. */ namespace PFBC; use PH7\Framework\Security\Validate\Validate; abstract class Validation extends Base { protected $oValidate, $message; public function __construct($message = '') { $this->oValidate = new Validate; if (!empty($message)) { $this->message = t('%element% is invalid.'); } } public function getMessage() { return $this->message; } public function isNotApplicable($value) { return (is_null($value) || is_array($value) || $value === ''); } public abstract function isValid($value); }
Fix after latest update from launchpad After the latest update from lauchpad (August/2016) the html pre block for the abap instructtions already contained the class language-abap, which prevented our code from running as this was a condition we checked to prevent running the highlighting unecessarily. We are now using a different class for this, code-highlighted.
$( document ).on('DOMNodeInserted', 'pre', function(eventObject) { var thisElement = $(this); if(!thisElement.hasClass('code-highlighted')) { changingPres = true; thisElement.addClass('code-highlighted'); var newHtmlForElement = thisElement.html(); newHtmlForElement = replaceAll(newHtmlForElement, '<br>', '\n'); newHtmlForElement = '<code>' + newHtmlForElement + '</code>'; // Prevents Highlighting of non ABAP comments newHtmlForElement = replaceAll(newHtmlForElement, '*\n&gt;&gt;&gt;', '*\n</code><code class="language-none">&gt;&gt;&gt;'); newHtmlForElement = replaceAll(newHtmlForElement, '&lt;&lt;&lt;\n\n*&amp;', '&lt;&lt;&lt;</code><code class="language-abap">\n\n*&amp;'); thisElement.html(newHtmlForElement); Prism.highlightAll(); commonCIPostProcessing(thisElement, function(noteNumber) { return '/#/notes/' + noteNumber; }); } });
$( document ).on('DOMNodeInserted', 'pre', function(eventObject) { var thisElement = $(this); if(!thisElement.hasClass('language-abap')) { changingPres = true; thisElement.addClass('language-abap'); var newHtmlForElement = thisElement.html(); newHtmlForElement = replaceAll(newHtmlForElement, '<br>', '\n'); newHtmlForElement = '<code>' + newHtmlForElement + '</code>'; // Prevents Highlighting of non ABAP comments newHtmlForElement = replaceAll(newHtmlForElement, '*\n&gt;&gt;&gt;', '*\n</code><code class="language-none">&gt;&gt;&gt;'); newHtmlForElement = replaceAll(newHtmlForElement, '&lt;&lt;&lt;\n\n*&amp;', '&lt;&lt;&lt;</code><code class="language-abap">\n\n*&amp;'); thisElement.html(newHtmlForElement); Prism.highlightAll(); commonCIPostProcessing(thisElement, function(noteNumber) { return '/#/notes/' + noteNumber; }); } });
Fix to_bytes when text is None
# coding: utf-8 import base64 from flask import request, Response from oauthlib.common import to_unicode, bytes_type def extract_params(): """Extract request params.""" uri = request.url http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del headers['wsgi.input'] if 'wsgi.errors' in headers: del headers['wsgi.errors'] body = request.form.to_dict() return uri, http_method, body, headers def to_bytes(text, encoding='utf-8'): """Make sure text is bytes type.""" if not text: return text if not isinstance(text, bytes_type): text = text.encode(encoding) return text def decode_base64(text, encoding='utf-8'): """Decode base64 string.""" text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding) def create_response(headers, body, status): """Create response class for Flask.""" response = Response(body or '') for k, v in headers.items(): response.headers[k] = v response.status_code = status return response
# coding: utf-8 import base64 from flask import request, Response from oauthlib.common import to_unicode, bytes_type def extract_params(): """Extract request params.""" uri = request.url http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del headers['wsgi.input'] if 'wsgi.errors' in headers: del headers['wsgi.errors'] body = request.form.to_dict() return uri, http_method, body, headers def to_bytes(text, encoding='utf-8'): """Make sure text is bytes type.""" if not isinstance(text, bytes_type): text = text.encode(encoding) return text def decode_base64(text, encoding='utf-8'): """Decode base64 string.""" text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding) def create_response(headers, body, status): """Create response class for Flask.""" response = Response(body or '') for k, v in headers.items(): response.headers[k] = v response.status_code = status return response
Add comment to eslint options
'use strict' module.exports = { extends: [ 'eslint:recommended', 'eslint-config-airbnb-base', 'plugin:prettier/recommended', ], env: { jest: true, }, globals: { RUN_TEST_AGAINST_AWS: true, TEST_BASE_URL: true, }, parserOptions: { sourceType: 'script', }, rules: { // overwrite airbnb-base options // we use underscores to indicate private fields in classes 'no-underscore-dangle': 'off', // import buffer explicitly 'no-restricted-globals': [ 'error', { name: 'Buffer', message: "Import 'Buffer' from 'buffer' module instead", }, ], // until we switch to ES6 modules (which use 'strict mode' implicitly) strict: ['error', 'global'], // TODO FIXME turn off temporary, to make eslint pass 'class-methods-use-this': 'off', 'no-console': 'off', 'no-restricted-syntax': 'off', }, }
'use strict' module.exports = { extends: [ 'eslint:recommended', 'eslint-config-airbnb-base', 'plugin:prettier/recommended', ], env: { jest: true, }, globals: { RUN_TEST_AGAINST_AWS: true, TEST_BASE_URL: true, }, parserOptions: { sourceType: 'script', }, rules: { // overwrite airbnb-base options 'no-underscore-dangle': 'off', // import buffer explicitly 'no-restricted-globals': [ 'error', { name: 'Buffer', message: "Import 'Buffer' from 'buffer' module instead", }, ], // until we switch to ES6 modules (which use 'strict mode' implicitly) strict: ['error', 'global'], // TODO FIXME turn off temporary, to make eslint pass 'class-methods-use-this': 'off', 'no-console': 'off', 'no-restricted-syntax': 'off', }, }
Fix some wrong references to person
package seedu.address.testutil; import seedu.address.model.tag.UniqueTagList; import seedu.address.model.task.Name; import seedu.address.model.task.ReadOnlyTask; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private UniqueTagList tags; public TestTask() { tags = new UniqueTagList(); } /** * Creates a copy of {@code taskToCopy}. */ public TestTask(TestTask taskToCopy) { this.name = taskToCopy.getName(); this.tags = taskToCopy.getTags(); } public void setName(Name name) { this.name = name; } public void setTags(UniqueTagList tags) { this.tags = tags; } @Override public Name getName() { return name; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName + " "); this.getTags().asObservableList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } }
package seedu.address.testutil; import seedu.address.model.tag.UniqueTagList; import seedu.address.model.task.Name; import seedu.address.model.task.ReadOnlyTask; /** * A mutable person object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private UniqueTagList tags; public TestTask() { tags = new UniqueTagList(); } /** * Creates a copy of {@code personToCopy}. */ public TestTask(TestTask personToCopy) { this.name = personToCopy.getName(); this.tags = personToCopy.getTags(); } public void setName(Name name) { this.name = name; } public void setTags(UniqueTagList tags) { this.tags = tags; } @Override public Name getName() { return name; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName + " "); this.getTags().asObservableList().stream().forEach(s -> sb.append("t/" + s.tagName + " ")); return sb.toString(); } }
Bring now uses --myUIDandGIDCheckout if root is not the invoker
from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) myUIDandGID = ["--myUIDandGIDcheckout"] if os.getuid() != 0 else [] run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", "--objectStores=" + config.objectStoresOsmosisParameter()] + myUIDandGID)
from solvent import config from solvent import run from solvent import requirementlabel import logging import os class Bring: def __init__(self, repositoryBasename, product, hash, destination): self._repositoryBasename = repositoryBasename self._product = product self._hash = hash self._destination = destination def go(self): requirementLabel = requirementlabel.RequirementLabel( basename=self._repositoryBasename, product=self._product, hash=self._hash) label = requirementLabel.matching() self.label(label=label, destination=self._destination) @classmethod def label(cls, label, destination): logging.info("Checking out '%(label)s'", dict(label=label)) if not os.path.isdir(destination): os.makedirs(destination) run.run([ "osmosis", "checkout", destination, label, "--MD5", "--removeUnknownFiles", "--putIfMissing", "--objectStores=" + config.objectStoresOsmosisParameter()])
Fix display of HTML-escaped chars in player description
const $ = jQuery = require("jquery") const localforage = require("localforage") const path = require("path") const fs = require("fs") const Jimp = require("jimp") const remote = require("electron").remote const nodeCrypto = require("crypto") const tippy = require("tippy.js") const Request = require("request") const i18n = require("../../lib/i18n.js") const moment = require("moment") const sortable = require( path.join(__dirname, "..", "..", "node_modules", "html5sortable", "dist", "html5sortable.cjs.js") ) const Mousetrap = require("mousetrap") const os = require("os") const package = require(path.join(__dirname, "../..", "package.json")) const sanitizeFilename = require("sanitize-filename") const Autolinker = require("autolinker") let autolinker = new Autolinker({ mention: "twitter", hashtag: false, stripPrefix: false, stripTrailingSlash: false }) var MPRISPlayer; try { MPRISPlayer = require("mpris-service") } catch (e) { MPRISPlayer = null }
const $ = jQuery = require("jquery") const localforage = require("localforage") const path = require("path") const fs = require("fs") const Jimp = require("jimp") const remote = require("electron").remote const nodeCrypto = require("crypto") const tippy = require("tippy.js") const Request = require("request") const i18n = require("../../lib/i18n.js") const moment = require("moment") const sortable = require( path.join(__dirname, "..", "..", "node_modules", "html5sortable", "dist", "html5sortable.cjs.js") ) const Mousetrap = require("mousetrap") const os = require("os") const package = require(path.join(__dirname, "../..", "package.json")) const sanitizeFilename = require("sanitize-filename") const Autolinker = require("autolinker") let autolinker = new Autolinker({ mention: "twitter", hashtag: "twitter", stripPrefix: false, stripTrailingSlash: false }) var MPRISPlayer; try { MPRISPlayer = require("mpris-service") } catch (e) { MPRISPlayer = null }
Remove extra requirements from install.
#!/usr/bin/env python """A custom GeoKey extension for WeGovNow functionality.""" from os.path import join from setuptools import setup, find_packages name = 'geokey-wegovnow' version = __import__(name.replace('-', '_')).__version__ repository = join('https://github.com/ExCiteS', name) setup( name=name, version=version, description='GeoKey extension for WeGovNow functionality', url=repository, download_url=join(repository, 'tarball', version), author='ExCiteS', author_email='excites@ucl.ac.uk', license='MIT', packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']), include_package_data=True, install_requires=['django-material==0.10.0'], )
#!/usr/bin/env python """A custom GeoKey extension for WeGovNow functionality.""" from os.path import join from setuptools import setup, find_packages name = 'geokey-wegovnow' version = __import__(name.replace('-', '_')).__version__ repository = join('https://github.com/ExCiteS', name) setup( name=name, version=version, description='GeoKey extension for WeGovNow functionality', url=repository, download_url=join(repository, 'tarball', version), author='ExCiteS', author_email='excites@ucl.ac.uk', license='MIT', packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']), include_package_data=True, install_requires=['django-material==0.10.0', 'geokey', 'django-allauth', 'django', 'requests'], )
Bump version to 0.0.3 for Nav440 sensor addition
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = '' with open('README.rst') as f: readme = f.read() reqs = [] with open('requirements.txt') as f: reqs = f.read().splitlines() setup( name='ahrs_sensors', version='0.0.3', description='Read data from the sparkfun SEN-10724 sensor stick', long_description=readme, author='Ruairi Fahy', url='https://github.com/ruairif/ahrs', packages=[ 'ahrs_sensors', 'sensor' ], include_package_data=True, install_requires=reqs, license='MIT', zip_safe=False, keywords='sensors', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ] )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = '' with open('README.rst') as f: readme = f.read() reqs = [] with open('requirements.txt') as f: reqs = f.read().splitlines() setup( name='ahrs_sensors', version='0.0.2', description='Read data from the sparkfun SEN-10724 sensor stick', long_description=readme, author='Ruairi Fahy', url='https://github.com/ruairif/ahrs', packages=[ 'ahrs_sensors', 'sensor' ], include_package_data=True, install_requires=reqs, license='MIT', zip_safe=False, keywords='sensors', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ] )
Rename polyline, it was too technical
export default { pan: { id: 'pan', name: 'Pan', title: 'Pan Tool' }, text: { id: 'text', name: 'Text', title: 'Text Label Tool', options: { text: 'Text here' } }, marker: { id: 'marker', dataId: 'Point', name: 'Marker', title: 'Marker Tool' }, polyline: { id: 'polyline', dataId: 'LineString', name: 'Line', title: 'Multi segmented line tool' }, polygon: { id: 'polygon', dataId: 'Polygon', name: 'Polygon', title: 'Polygon Tool' }, circle: { id: 'circle', dmId: google.maps.drawing.OverlayType.CIRCLE, name: 'Circle', title: 'Circle Tool' }, rectangle: { id: 'rectangle', dmId: google.maps.drawing.OverlayType.RECTANGLE, name: 'Rectangle', title: 'Rectangle Tool' } };
export default { pan: { id: 'pan', name: 'Pan', title: 'Pan Tool' }, text: { id: 'text', name: 'Text', title: 'Text Label Tool', options: { text: 'Text here' } }, marker: { id: 'marker', dataId: 'Point', name: 'Marker', title: 'Marker Tool' }, polyline: { id: 'polyline', dataId: 'LineString', name: 'PolyLine', title: 'Multi segmented line tool' }, polygon: { id: 'polygon', dataId: 'Polygon', name: 'Polygon', title: 'Polygon Tool' }, circle: { id: 'circle', dmId: google.maps.drawing.OverlayType.CIRCLE, name: 'Circle', title: 'Circle Tool' }, rectangle: { id: 'rectangle', dmId: google.maps.drawing.OverlayType.RECTANGLE, name: 'Rectangle', title: 'Rectangle Tool' } };
Improve Double Checked Locking Javadoc
package com.iluwatar.doublechecked.locking; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * Double Checked Locking is a concurrency design pattern used to reduce the overhead * of acquiring a lock by first testing the locking criterion (the "lock hint") without * actually acquiring the lock. Only if the locking criterion check indicates that * locking is required does the actual locking logic proceed. * <p> * In {@link Inventory} we store the items with a given size. However, we do not store * more items than the inventory size. To address concurrent access problems we * use double checked locking to add item to inventory. In this method, the * thread which gets the lock first adds the item. * */ public class App { /** * Program entry point * @param args command line args */ public static void main(String[] args) { final Inventory inventory = new Inventory(1000); ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { executorService.execute(new Runnable() { @Override public void run() { while (inventory.addItem(new Item())) ; } }); } } }
package com.iluwatar.doublechecked.locking; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * In {@link Inventory} we store the items with a given size. However, we do not store * more items than the inventory size. To address concurrent access problems we * use double checked locking to add item to inventory. In this method, the * thread which gets the lock first adds the item. * */ public class App { /** * Program entry point * @param args command line args */ public static void main(String[] args) { final Inventory inventory = new Inventory(1000); ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { executorService.execute(new Runnable() { @Override public void run() { while (inventory.addItem(new Item())) ; } }); } } }
Move feed fetch interval time to env
import http from 'http' import throng from 'throng' import app from './app' import { FEED_URL } from './constants' import mongoConfig from './mongoConfig' require('dotenv').config() require('source-map-support').install() http.globalAgent.maxSockets = Infinity function start() { const instance = app({ mongoConfig, url: FEED_URL }) const refreshInterval = process.env.FEED_REFRESH_INTERVAL || 20 console.log({ type: 'info', msg: 'starting worker' }) function shutdown() { console.log({ type: 'info', msg: 'shutting down' }) process.exit() } function beginWork() { if (process.env.NODE_ENV === 'production') process.send('ready') instance.on('lost', shutdown) instance.updateFeed() setInterval(() => instance.updateFeed(), refreshInterval * 60 * 1000) } instance.on('ready', beginWork) process.on('SIGTERM', shutdown) } throng({ workers: 1, start })
import http from 'http' import throng from 'throng' import app from './app' import { FEED_URL } from './constants' import mongoConfig from './mongoConfig' require('dotenv').config() require('source-map-support').install() http.globalAgent.maxSockets = Infinity function start() { const instance = app({ mongoConfig, url: FEED_URL }) console.log({ type: 'info', msg: 'starting worker' }) function shutdown() { console.log({ type: 'info', msg: 'shutting down' }) process.exit() } function beginWork() { if (process.env.NODE_ENV === 'production') process.send('ready') instance.on('lost', shutdown) instance.updateFeed() setInterval(() => instance.updateFeed(), 10 * 60 * 1000) } instance.on('ready', beginWork) process.on('SIGTERM', shutdown) } throng({ workers: 1, start })
Fix error when logging in
<?php namespace App; use Carbon\Carbon; class UserRepository { public function getUser($request) { $user = $request->user; $expiresIn = Carbon::now(); $expiresIn->addSecond($request->expiresIn); return User::updateOrCreate(['id' => $request->id], [ 'id' => $request->id, 'username' => $user['username'], 'email' => $request->email, 'refresh_token' => $request->refreshToken, 'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope']))? 'NAME_SERVERS' : 'NAME_ONLY', 'token' => $request->token, 'expires_in' => $expiresIn->toDateTimeString() ]); } }
<?php namespace App; use Carbon\Carbon; class UserRepository { public function getUser($request) { $user = $request->user; $expiresIn = Carbon::now(); $expiresIn->addSecond($request->expiresIn); return User::updateOrCreate(['id' => $request->id], [ 'id' => $request->id, 'username' => $user['username'], 'email' => $user['email'], 'refresh_token' => $request->refreshToken, 'token_type' => in_array('guilds', explode(' ', $request->accessTokenResponseBody['scope']))? 'NAME_SERVERS' : 'NAME_ONLY', 'token' => $request->token, 'expires_in' => $expiresIn->toDateTimeString() ]); } }
Call on progress update in sync use case
package lib.morkim.mfw.usecase; import lib.morkim.mfw.app.AppContext; public abstract class SyncUseCase extends BaseUseCase implements UseCaseStateListener { public SyncUseCase(AppContext appContext) { super(appContext); } @Override public void execute(UseCaseRequest request) { setRequest(request); onPrepare(); onExecute(); onReportProgress(); onSaveModel(); } @Override public void execute() { execute(null); } @Override public void executeSync() { this.execute(); } @Override public void executeSync(UseCaseRequest request) { execute(request); } @Override protected void reportProgress() { } @Override public void onUseCaseComplete(UseCaseResult response) { } @Override protected void onSaveModel() {} }
package lib.morkim.mfw.usecase; import lib.morkim.mfw.app.AppContext; public abstract class SyncUseCase extends BaseUseCase implements UseCaseStateListener { public SyncUseCase(AppContext appContext) { super(appContext); } @Override public void execute(UseCaseRequest request) { setRequest(request); onPrepare(); onExecute(); onSaveModel(); } @Override public void execute() { execute(null); } @Override public void executeSync() { this.execute(); } @Override public void executeSync(UseCaseRequest request) { execute(request); } @Override protected void reportProgress() { } @Override public void onUseCaseComplete(UseCaseResult response) { } @Override protected void onSaveModel() {} }
Add the recent scope method for the user model to get the recently signed up users.
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; public function topics() { return $this->hasMany('Topic'); } public function replies() { return $this->hasMany('Reply'); } public function notifications() { return $this->hasMany('Notification'); } public function favoriteTopics() { return $this->belongsTo('Topic', 'favorites'); } public function attentTopics() { return $this->belongsTo('Topics', 'attentions'); } public function scopeRecent($query) { return $query->orderBy('created_at', 'desc'); } }
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; public function topics() { return $this->hasMany('Topic'); } public function replies() { return $this->hasMany('Reply'); } public function notifications() { return $this->hasMany('Notification'); } public function favoriteTopics() { return $this->belongsTo('Topic', 'favorites'); } public function attentTopics() { return $this->belongsTo('Topics', 'attentions'); } }
Add terrible stub of a test
'use strict'; const assert = require('assert'); const prepareContext = require('../lib/prepareContext'); const render = require('../lib/render'); const { nunjucksEnv } = require('../constants'); describe('render', function() { it('does a render', function(done) { const tpl = 'templates/base.j2'; const dest = `${__dirname}/dest/base.html`; prepareContext({ data: [], groups: {}, display: {}, }) .then(ctx => render(nunjucksEnv, tpl, dest, ctx)) .then(() => { // Look for side-effects assert.ok(true); done(); }) .catch(err => { assert.fail(err); done(); }); }); it('no-ops with a non-buffer file', function(done) { // What would that even be? How can we trigger that eventuality? }); });
'use strict'; const assert = require('assert'); const prepareContext = require('../lib/prepareContext'); const render = require('../lib/render'); const { nunjucksEnv } = require('../constants'); describe('render', function() { it('does a render', function(done) { const tpl = 'templates/base.j2'; const dest = `${__dirname}/dest/base.html`; prepareContext({ data: [], groups: {}, display: {}, }) .then(ctx => render(nunjucksEnv, tpl, dest, ctx)) .then(() => { // Look for side-effects assert.ok(true); done(); }) .catch(err => { assert.fail(err); done(); }); }); });
Set mangle to false in babel-preset-minify for polymer to fix static build
module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ [ require.resolve('babel-preset-env'), { targets: { browsers: ['last 2 versions', 'safari >= 7'], }, modules: false, }, ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), [ require.resolve('babel-preset-minify'), { mangle: false, }, ], ], plugins: [ require.resolve('babel-plugin-transform-regenerator'), [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
module.exports = { // Don't try to find .babelrc because we want to force this configuration. babelrc: false, presets: [ [ require.resolve('babel-preset-env'), { targets: { browsers: ['last 2 versions', 'safari >= 7'], }, modules: false, }, ], require.resolve('babel-preset-stage-0'), require.resolve('babel-preset-react'), require.resolve('babel-preset-minify'), ], plugins: [ require.resolve('babel-plugin-transform-regenerator'), [ require.resolve('babel-plugin-transform-runtime'), { helpers: true, polyfill: true, regenerator: true, }, ], ], };
Set https as default app url
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => false, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'https://production.yourserver.com', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | | Run a php artisan key:generate --env=staging to create a random one */ 'key' => 'Change_this_key_or_snipe_will_get_ya', );
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => false, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://production.yourserver.com', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | | Run a php artisan key:generate --env=staging to create a random one */ 'key' => 'Change_this_key_or_snipe_will_get_ya', );
Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): print "Context:" for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
Correct the off-by one error from logical to physical pages
#!/usr/bin/env python from lxml import etree import sys comments_file = open("examples/Technical_Document_Comments.xfdf", "r") comments_xml = etree.parse(comments_file) root = comments_xml.getroot() prefix = None try: prefix = root.tag.partition("}")[0].partition("{")[-1] except: pass if prefix: highlights = root[0].findall("{%s}highlight" % prefix) else: highlights = root[0].findall("highlight") with sys.stdout as out: line = u"\tIssue\tSection\tPage\tBy\tObservation Description\n".encode("utf-8") out.write(line) issue = 1 for h in highlights: try: page = int(h.get("page"))+1 except: continue try: author = h.get("title") except: continue try: content = h.find("{%s}contents" % prefix).text except: continue content = content.replace("\n","-").replace("\r","") line = u"NA\t{2}\tSECTION\t{0}\t{3}\t{1}\n".format(page,content,issue,author).encode("utf-8") out.write(line) issue += 1
#!/usr/bin/env python from lxml import etree import sys comments_file = open("examples/Technical_Document_Comments.xfdf", "r") comments_xml = etree.parse(comments_file) root = comments_xml.getroot() prefix = None try: prefix = root.tag.partition("}")[0].partition("{")[-1] except: pass if prefix: highlights = root[0].findall("{%s}highlight" % prefix) else: highlights = root[0].findall("highlight") with sys.stdout as out: line = u"\tIssue\tSection\tPage\tBy\tObservation Description\n".encode("utf-8") out.write(line) issue = 1 for h in highlights: try: page = h.get("page") except: continue try: author = h.get("title") except: continue try: content = h.find("{%s}contents" % prefix).text except: continue content = content.replace("\n","-").replace("\r","") line = u"NA\t{2}\tSECTION\t{0}\t{3}\t{1}\n".format(page,content,issue,author).encode("utf-8") out.write(line) issue += 1
Fix error relating to timeline key
import React, { Component } from "react"; import { connect } from "react-redux"; import { timelineSelectors } from "../../redux/selectors"; import { timelineActions } from "../../redux/actions"; import { Container } from "../_controls"; class Timeline extends Component { componentDidMount() { this.props.load(); } render() { const { entries } = this.props; return ( <Container> Timeline {entries.map(entry => { return ( <div key={entry.id}> {entry.eventTimeDisplay}: {entry.title} </div> ); })} </Container> ); } } function mapStateToProps(state, props) { return { entries: timelineSelectors.all(state) }; } function mapDispatchToProps(dispatch, props) { return { load: () => dispatch(timelineActions.load()) }; } export default connect(mapStateToProps, mapDispatchToProps)(Timeline);
import React, { Component } from "react"; import { connect } from "react-redux"; import { timelineSelectors } from "../../redux/selectors"; import { timelineActions } from "../../redux/actions"; import { Container } from "../_controls"; class Timeline extends Component { componentDidMount() { this.props.load(); } render() { const { entries } = this.props; return ( <Container> Timeline {entries.map(entry => { return ( <div> {entry.eventTimeDisplay}: {entry.title} </div> ); })} </Container> ); } } function mapStateToProps(state, props) { return { entries: timelineSelectors.all(state) }; } function mapDispatchToProps(dispatch, props) { return { load: () => dispatch(timelineActions.load()) }; } export default connect(mapStateToProps, mapDispatchToProps)(Timeline);
Convert to use new port mechanism
package lejos.hardware.sensor; import lejos.hardware.port.Port; import lejos.hardware.port.UARTPort; import lejos.robotics.RangeFinder; /** * Basic sensor driver for the Lego EV3 Ultrasonic sensor.<br> * TODO: Need to implement other modes. Consider implementing other methods * to allow this device to be used in place of the NXT device (getDistance) etc. * @author andy * */ public class EV3UltrasonicSensor extends UARTSensor implements RangeFinder { /** * Create the sensor class. The sensor will be set to return measurements in CM. * @param port */ public EV3UltrasonicSensor(UARTPort port) { super(port); } /** * Create the sensor class. The sensor will be set to return measurements in CM. * @param port */ public EV3UltrasonicSensor(Port port) { super(port); } /** * {@inheritDoc} */ @Override public float getRange() { return (float)port.getShort()/10.0f; } /** * {@inheritDoc} */ @Override public float[] getRanges() { // TODO Work out how to use other modes, maybe change this float [] result = new float[1]; result[0] = getRange(); return result; } }
package lejos.hardware.sensor; import lejos.hardware.port.UARTPort; import lejos.robotics.RangeFinder; /** * Basic sensor driver for the Lego EV3 Ultrasonic sensor.<br> * TODO: Need to implement other modes. Consider implementing other methods * to allow this device to be used in place of the NXT device (getDistance) etc. * @author andy * */ public class EV3UltrasonicSensor extends UARTSensor implements RangeFinder { /** * Create the sensor class. The sensor will be set to return measurements in CM. * @param port */ public EV3UltrasonicSensor(UARTPort port) { super(port); } /** * {@inheritDoc} */ @Override public float getRange() { return (float)port.getShort()/10.0f; } /** * {@inheritDoc} */ @Override public float[] getRanges() { // TODO Work out how to use other modes, maybe change this float [] result = new float[1]; result[0] = getRange(); return result; } }
Add options trailing slashes to the Enrollment API. This allows the edX REST API Client to perform a sucessful GET against this API, since Slumber (which our client is based off of) appends the trailing slash by default.
""" URLs for the Enrollment API """ from django.conf import settings from django.conf.urls import patterns, url from .views import ( EnrollmentView, EnrollmentListView, EnrollmentCourseDetailView ) urlpatterns = patterns( 'enrollment.views', url( r'^enrollment/{username},{course_key}/$'.format( username=settings.USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN ), EnrollmentView.as_view(), name='courseenrollment' ), url( r'^enrollment/{course_key}/$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentView.as_view(), name='courseenrollment' ), url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'), url( r'^course/{course_key}/$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentCourseDetailView.as_view(), name='courseenrollmentdetails' ), )
""" URLs for the Enrollment API """ from django.conf import settings from django.conf.urls import patterns, url from .views import ( EnrollmentView, EnrollmentListView, EnrollmentCourseDetailView ) urlpatterns = patterns( 'enrollment.views', url( r'^enrollment/{username},{course_key}$'.format( username=settings.USERNAME_PATTERN, course_key=settings.COURSE_ID_PATTERN ), EnrollmentView.as_view(), name='courseenrollment' ), url( r'^enrollment/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentView.as_view(), name='courseenrollment' ), url(r'^enrollment$', EnrollmentListView.as_view(), name='courseenrollments'), url( r'^course/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN), EnrollmentCourseDetailView.as_view(), name='courseenrollmentdetails' ), )
Switch password storage to localStorage so that it works across tabs.
module.exports = { unlockCollection: function(id, effectivePassword) { localStorage.setItem("eff_" + id, effectivePassword); }, lockCollection: function(id) { localStorage.removeItem("eff_" + id); }, isLockedCollection: function(id) { return localStorage.getItem("eff_" + id) ? false : true; }, decrypt: function(id, content) { var key = localStorage.getItem("eff_" + id); if (!key) return null; return sjcl.decrypt(key, content); }, encrypt: function(id, content) { var key = localStorage.getItem("eff_" + id); if (!key) return false; return sjcl.encrypt(key, content); } };
module.exports = { unlockCollection: function(id, effectivePassword) { sessionStorage.setItem("eff_" + id, effectivePassword); }, lockCollection: function(id) { sessionStorage.removeItem("eff_" + id); }, isLockedCollection: function(id) { return sessionStorage.getItem("eff_" + id) ? false : true; }, decrypt: function(id, content) { var key = sessionStorage.getItem("eff_" + id); if (!key) return null; return sjcl.decrypt(key, content); }, encrypt: function(id, content) { var key = sessionStorage.getItem("eff_" + id); if (!key) return false; return sjcl.encrypt(key, content); } };
Add explicit Python 3.6 support
from setuptools import setup from os import path with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f: readme = f.read() setup( name='ghstats', version='1.1.1', packages=['ghstats'], description='GitHub Release download count and other statistics.', long_description=readme, author='Alexander Gorishnyak', author_email='kefir500@gmail.com', license='MIT', url='https://github.com/kefir500/ghstats', keywords='github release download count stats statistics', entry_points={ 'console_scripts': [ 'ghstats = ghstats.ghstats:main_cli' ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Utilities' ] )
from setuptools import setup from os import path with open(path.join(path.abspath(path.dirname(__file__)), 'README.rst')) as f: readme = f.read() setup( name='ghstats', version='1.1.1', packages=['ghstats'], description='GitHub Release download count and other statistics.', long_description=readme, author='Alexander Gorishnyak', author_email='kefir500@gmail.com', license='MIT', url='https://github.com/kefir500/ghstats', keywords='github release download count stats statistics', entry_points={ 'console_scripts': [ 'ghstats = ghstats.ghstats:main_cli' ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Utilities' ] )
Remove extraneous whitespace in docblock
<?php namespace Illuminate\Session; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\SessionInterface as BaseSessionInterface; interface SessionInterface extends BaseSessionInterface { /** * Get the session handler instance. * * @return \SessionHandlerInterface */ public function getHandler(); /** * Determine if the session handler needs a request. * * @return bool */ public function handlerNeedsRequest(); /** * Set the request on the handler instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return void */ public function setRequestOnHandler(Request $request); /** * Checks if an attribute exists. * * @param string|array $key * @return bool */ public function exists($key); }
<?php namespace Illuminate\Session; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\SessionInterface as BaseSessionInterface; interface SessionInterface extends BaseSessionInterface { /** * Get the session handler instance. * * @return \SessionHandlerInterface */ public function getHandler(); /** * Determine if the session handler needs a request. * * @return bool */ public function handlerNeedsRequest(); /** * Set the request on the handler instance. * * @param \Symfony\Component\HttpFoundation\Request $request * @return void */ public function setRequestOnHandler(Request $request); /** * Checks if an attribute exists. * * @param string|array $key * * @return bool */ public function exists($key); }
Revert previous change to changePage() call - it's causing problems.
define(['Twitter', 'TwitterConfirmer', 'TapsModel', 'JQMListView', 'ListPresenter', 'JQMEditView', 'EditPresenter', 'FollowingPresenter', 'SettingsPage'], function(Twitter, TwitterConfirmer, TapsModel, JQMListView, ListPresenter, JQMEditView, EditPresenter, FollowingPresenter, SettingsPage) { function BeerTap(twitterProxy) { this.twitter = new Twitter(localStorage, twitterProxy); var listModel = new TapsModel(this.twitter); var listView = new JQMListView("listPage"); var listPresenter = new ListPresenter("listPage", listModel, listView); var editView = new JQMEditView("editPage"); var editModel = new TapsModel(new TwitterConfirmer(this.twitter, editView.page)); var editPresenter = new EditPresenter("editPage", editModel, editView); var settingsPresenter = new SettingsPage("settings", this.twitter); this.mainPage = new FollowingPresenter("main", this.twitter, listPresenter, editPresenter, settingsPresenter); $(document).ajaxStart(function() { $.mobile.loading( 'show' ); }); $(document).ajaxStop(function() { $.mobile.loading( 'hide' ); }); $(document).ajaxError(function() { alert("Error fetching data"); }); $.mobile.changePage("#main"); } return BeerTap; });
define(['Twitter', 'TwitterConfirmer', 'TapsModel', 'JQMListView', 'ListPresenter', 'JQMEditView', 'EditPresenter', 'FollowingPresenter', 'SettingsPage'], function(Twitter, TwitterConfirmer, TapsModel, JQMListView, ListPresenter, JQMEditView, EditPresenter, FollowingPresenter, SettingsPage) { function BeerTap(twitterProxy) { this.twitter = new Twitter(localStorage, twitterProxy); var listModel = new TapsModel(this.twitter); var listView = new JQMListView("listPage"); var listPresenter = new ListPresenter("listPage", listModel, listView); var editView = new JQMEditView("editPage"); var editModel = new TapsModel(new TwitterConfirmer(this.twitter, editView.page)); var editPresenter = new EditPresenter("editPage", editModel, editView); var settingsPresenter = new SettingsPage("settings", this.twitter); this.mainPage = new FollowingPresenter("main", this.twitter, listPresenter, editPresenter, settingsPresenter); $(document).ajaxStart(function() { $.mobile.loading( 'show' ); }); $(document).ajaxStop(function() { $.mobile.loading( 'hide' ); }); $(document).ajaxError(function() { alert("Error fetching data"); }); $.mobile.changePage("#main", { changeHash:false }); } return BeerTap; });
Set readOnly: true on Radios in RadioGroups without onChanges to fix React warning
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export class RadioGroup extends React.Component { static propTypes = { id: PropTypes.string, name: PropTypes.string, onChange: PropTypes.func, value: PropTypes.any }; componentDidMount() { require('../../css/forms'); } render() { const {name, children, onChange, className, value, ...others} = this.props; const radioProps = onChange ? {name, onChange} : {name, readOnly: true}; return ( <div {...{...others, className: classnames('pui-radio-group', className)}}> {React.Children.map(children, child => React.cloneElement(child, {...radioProps, checked: child.props.value === value}))} </div> ); } }
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export class RadioGroup extends React.Component { static propTypes = { id: PropTypes.string, name: PropTypes.string, onChange: PropTypes.func, value: PropTypes.any }; componentDidMount() { require('../../css/forms'); } render() { const {name, children, onChange, className, value, ...others} = this.props; const radioProps = onChange ? {name, onChange} : {name}; return ( <div {...{...others, className: classnames('pui-radio-group', className)}}> {React.Children.map(children, child => React.cloneElement(child, {...radioProps, checked: child.props.value === value}))} </div> ); } }
Add `raises` to linter globals.
module.exports = function(grunt) { grunt.initConfig({ qunit: ['./test/index.html'], lint: ['supermodel.js', './test/*.js'], jshint: { options: { eqnull: true, undef: true }, globals: { // QUnit ok: true, test: true, module: true, raises: true, deepEqual: true, strictEqual: true, // Dependencies _: true, jQuery: true, Backbone: true, Supermodel: true } } }); };
module.exports = function(grunt) { grunt.initConfig({ qunit: ['./test/index.html'], lint: ['supermodel.js', './test/*.js'], jshint: { options: { eqnull: true, undef: true }, globals: { // QUnit ok: true, test: true, module: true, deepEqual: true, strictEqual: true, // Dependencies _: true, jQuery: true, Backbone: true, Supermodel: true } } }); };
Make the console output for downloading the package list more concise
// helper functions var http = require("http"); exports.urlForLibrary = function (library, file, version) { return "//cdnjs.cloudflare.com/ajax/libs/" + library + "/" + version + "/" + file; }; exports.libraryUrls = function (callback) { http.get("http://cdnjs.com/packages.json", function (res) { console.log("Downloading the cdnjs package list... (this might take a minute)"); var data = ""; res.on("data", function (chunk) { data += chunk; }); res.on("end", function () { console.log("Done!"); var libraries = JSON.parse(data).packages; var result = libraries.map(function (data) { return exports.urlForLibrary(data.name, data.filename, data.version); }); callback(result); }); }); };
// helper functions var http = require("http"); exports.urlForLibrary = function (library, file, version) { return "//cdnjs.cloudflare.com/ajax/libs/" + library + "/" + version + "/" + file; }; exports.libraryUrls = function (callback) { http.get("http://cdnjs.com/packages.json", function (res) { var data = ""; var chunkNumber = 1; res.on("data", function (chunk) { data += chunk; console.log("chunk " + chunkNumber++); }); res.on("end", function () { console.log("done"); var libraries = JSON.parse(data).packages; var result = libraries.map(function (data) { return exports.urlForLibrary(data.name, data.filename, data.version); }); callback(result); }); }); };
Add get and post functionality to the auth user stuff.
from django.conf.urls import patterns, include, url from django.contrib import admin from accounts import views as views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_inventory.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^django/inventory/$', 'inventory.views.index'), url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'), url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'), url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'), url(r'^django/create/inventory/$', 'inventory.views.create'), url(r'^django/accounts/users/$', views.UserView.as_view({'get': 'list', 'post': 'create'})), url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'), url(r'^django/admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin from accounts import views as views admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'django_inventory.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^django/inventory/$', 'inventory.views.index'), url(r'^django/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.detail'), url(r'^django/update/inventory/(?P<item_id>[a-zA-Z0-9-]+)/(?P<new_item_count>\d+)/$', 'inventory.views.updatecount'), url(r'^django/delete/inventory/(?P<item_id>[a-zA-Z0-9-]+)/$', 'inventory.views.delete'), url(r'^django/create/inventory/$', 'inventory.views.create'), url(r'^django/accounts/users/$', views.UserView.as_view()), url(r'^django/accounts/auth/$', views.AuthView.as_view(), name='authenticate'), url(r'^django/admin/', include(admin.site.urls)), )
Use curl instead of wget.
#!/usr/bin/env python2 ################################################################################ # broadcast_any_song.py # # Uses the Exfm REST API to broadcast a song, (basically scours Tumblr for an # audio file matching a query then sends it to PiFM.) # # Maintained By: Ryan Jacobs <ryan.mjacobs@gmail.com> # # May 18, 2014 -> Creation date. ################################################################################ # Global Variables NC_HOST="gamma" NC_PORT=1234 CHANNEL=94.3 import os # to execute shell commands import sys # arguments import json # json parsing import urllib2 # url parsing and downloading if not len(sys.argv) > 1: print('Usage: ' + sys.argv[0] + ' <search term>') exit(1) json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:])) parsed_json = json.loads(json_url.read()) song_url = parsed_json["songs"][0]["url"] os.system("curl -#" + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT)) # Reset the terminal to fix the broken state os.system('reset')
#!/usr/bin/env python2 ################################################################################ # broadcast_any_song.py # # Uses the Exfm REST API to broadcast a song, (basically scours Tumblr for an # audio file matching a query then sends it to PiFM.) # # Maintained By: Ryan Jacobs <ryan.mjacobs@gmail.com> # # May 18, 2014 -> Creation date. ################################################################################ # Global Variables NC_HOST="gamma" NC_PORT=1234 CHANNEL=94.3 import os # to execute shell commands import sys # arguments import json # json parsing import urllib2 # url parsing and downloading if not len(sys.argv) > 1: print('Usage: ' + sys.argv[0] + ' <search term>') exit(1) json_url = urllib2.urlopen("http://ex.fm/api/v3/song/search/%s"% "+".join(sys.argv[1:])) parsed_json = json.loads(json_url.read()) song_url = parsed_json["songs"][0]["url"] os.system("wget -O - " + song_url + " | nc " + str(NC_HOST) + " " + str(NC_PORT)) # Reset the terminal to fix the broken state os.system('reset')
Set routes if provided in options.
function Plugin(app, chat, options) { if(!options) { throw new Error('No options specified for plugin.'); } if(!options.name) { throw new Error('No name specified for plugin'); } this.name = options.name; if(!options.version) { throw new Error('No version specified for plugin ' + this.name); } this.version = options.version; if(options.models) { this.models = options.models; } if(options.routes) { this.routes = options.routes; } this.app = app; this.chat = chat; } Plugin.prototype.init = function(callback) { callback(); }; Plugin.prototype.enable = function(callback) { callback(); }; Plugin.prototype.disable = function() { }; module.exports = Plugin;
function Plugin(app, chat, options) { if(!options) { throw new Error('No options specified for plugin.'); } if(!options.name) { throw new Error('No name specified for plugin'); } this.name = options.name; if(!options.version) { throw new Error('No version specified for plugin ' + this.name); } this.version = options.version; if(options.models) { this.models = options.models; } this.app = app; this.chat = chat; } Plugin.prototype.init = function(callback) { callback(); }; Plugin.prototype.enable = function(callback) { callback(); }; Plugin.prototype.disable = function() { }; module.exports = Plugin;
Remove spacebars-compiler -> spacebars test dependency. This fixes a circular build-time dependency when building test slices.
Package.describe({ summary: "Compiler for Spacebars template language" }); Package.on_use(function (api) { api.use('spacebars-common'); api.imply('spacebars-common'); // we attach stuff to the global symbol `HTML`, exported // by `htmljs` via `html-tools`, so we both use and effectively // imply it. api.use('html-tools'); api.imply('html-tools'); api.use('underscore'); api.use('minifiers', ['server']); api.add_files(['tokens.js', 'tojs.js', 'templatetag.js', 'spacebars-compiler.js']); }); Package.on_test(function (api) { api.use('underscore'); api.use('spacebars-compiler'); api.use('tinytest'); api.add_files('spacebars_tests.js'); api.add_files('compile_tests.js'); api.add_files('token_tests.js'); });
Package.describe({ summary: "Compiler for Spacebars template language" }); Package.on_use(function (api) { api.use('spacebars-common'); api.imply('spacebars-common'); // we attach stuff to the global symbol `HTML`, exported // by `htmljs` via `html-tools`, so we both use and effectively // imply it. api.use('html-tools'); api.imply('html-tools'); api.use('underscore'); api.use('minifiers', ['server']); api.add_files(['tokens.js', 'tojs.js', 'templatetag.js', 'spacebars-compiler.js']); }); Package.on_test(function (api) { api.use('underscore'); api.use('spacebars'); api.use('spacebars-compiler'); api.use('tinytest'); api.add_files('spacebars_tests.js'); api.add_files('compile_tests.js'); api.add_files('token_tests.js'); });
Set "X-Droonga-Cached=yes" for cached contents
var Cache = require('./cache'); var Entry = require('./entry'); function generateKey(request) { return request.method + '\n' + request.url; } function sendCachedResponse(response, cached) { response.statusCode = cached.status; Object.keys(cached.headers).forEach(function(key) { response.setHeader(key, cached.headers[key]); }); response.setHeader('X-Droonga-Cached', 'yes'); cached.body.forEach(function(chunk) { response.write(chunk.data, chunk.encoding); }); response.end(); } exports = module.exports = function(options) { var cache = new Cache(options); return function(request, response, next) { var rule = cache.getRule(request); if (!rule) { next(); return; } var cacheKey = generateKey(request); cache.get(cacheKey, function(error, cachedResponse) { if (error) { console.error(error); return; } if (cachedResponse) { sendCachedResponse(response, cachedResponse); } else { var entry = new Entry(); entry.hook(response, function(cachedResponse) { cache.set(cacheKey, cachedResponse, rule.ttlInMilliSeconds); }); next(); } }); }; };
var Cache = require('./cache'); var Entry = require('./entry'); function generateKey(request) { return request.method + '\n' + request.url; } function sendCachedResponse(response, cached) { response.statusCode = cached.status; Object.keys(cached.headers).forEach(function(key) { response.setHeader(key, cached.headers[key]); }); cached.body.forEach(function(chunk) { response.write(chunk.data, chunk.encoding); }); response.end(); } exports = module.exports = function(options) { var cache = new Cache(options); return function(request, response, next) { var rule = cache.getRule(request); if (!rule) { next(); return; } var cacheKey = generateKey(request); cache.get(cacheKey, function(error, cachedResponse) { if (error) { console.error(error); return; } if (cachedResponse) { sendCachedResponse(response, cachedResponse); } else { var entry = new Entry(); entry.hook(response, function(cachedResponse) { cache.set(cacheKey, cachedResponse, rule.ttlInMilliSeconds); }); next(); } }); }; };
Change redirected page when login
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest', ['except' => 'logout']); } }
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest', ['except' => 'logout']); } }
Update name of Bridging-Header file Update name of Bridging-Header file #101
// nS - No Space // lC - Lowercase export function foldersAndFiles(currentAppName, newName) { const nS_CurrentAppName = currentAppName.replace(/\s/g, ''); const nS_NewName = newName.replace(/\s/g, ''); return [ `ios/${nS_CurrentAppName}`, `ios/${nS_CurrentAppName}-tvOS`, `ios/${nS_CurrentAppName}-tvOSTests`, `ios/${nS_CurrentAppName}.xcodeproj`, `ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_CurrentAppName}-tvOS.xcscheme`, `ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_CurrentAppName}.xcscheme`, `ios/${nS_CurrentAppName}Tests`, `ios/${nS_NewName}Tests/${nS_CurrentAppName}Tests.m`, `ios/${nS_CurrentAppName}.xcworkspace`, `ios/${nS_NewName}/${nS_CurrentAppName}.entitlements`, `ios/${nS_CurrentAppName}-Bridging-Header.h`, ]; }
// nS - No Space // lC - Lowercase export function foldersAndFiles(currentAppName, newName) { const nS_CurrentAppName = currentAppName.replace(/\s/g, ''); const nS_NewName = newName.replace(/\s/g, ''); return [ `ios/${nS_CurrentAppName}`, `ios/${nS_CurrentAppName}-tvOS`, `ios/${nS_CurrentAppName}-tvOSTests`, `ios/${nS_CurrentAppName}.xcodeproj`, `ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_CurrentAppName}-tvOS.xcscheme`, `ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_CurrentAppName}.xcscheme`, `ios/${nS_CurrentAppName}Tests`, `ios/${nS_NewName}Tests/${nS_CurrentAppName}Tests.m`, `ios/${nS_CurrentAppName}.xcworkspace`, `ios/${nS_NewName}/${nS_CurrentAppName}.entitlements`, ]; }
Fix rendering before prefs loaded
import React from 'react' export default class Prefs extends React.Component { static propTypes = { prefs: React.PropTypes.object.isRequired, setPrefs: React.PropTypes.func.isRequired, providerRefresh: React.PropTypes.func.isRequired, } toggleEnabled = this.toggleEnabled.bind(this) handleRefresh = this.handleRefresh.bind(this) toggleEnabled(e) { e.preventDefault() let prefs = Object.assign({}, this.props.prefs) prefs.enabled = !prefs.enabled this.props.setPrefs('provider.cdg', prefs) } handleRefresh() { this.props.providerRefresh('cdg') } render() { const { prefs } = this.props if (!prefs) return null const enabled = prefs.enabled === true let paths = prefs.paths || [] paths = paths.map(path => ( <p key={path}>{path}</p> )) return ( <div> <label> <input type='checkbox' checked={enabled} onClick={this.toggleEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button> {paths} </div> ) } }
import React from 'react' export default class Prefs extends React.Component { static propTypes = { prefs: React.PropTypes.object.isRequired, setPrefs: React.PropTypes.func.isRequired, providerRefresh: React.PropTypes.func.isRequired, } toggleEnabled = this.toggleEnabled.bind(this) handleRefresh = this.handleRefresh.bind(this) toggleEnabled(e) { e.preventDefault() let prefs = Object.assign({}, this.props.prefs) prefs.enabled = !prefs.enabled this.props.setPrefs('provider.cdg', prefs) } handleRefresh() { this.props.providerRefresh('cdg') } render() { const { prefs } = this.props let paths = prefs.paths || [] paths = paths.map(path => ( <p key={path}>{path}</p> )) return ( <div> <label> <input type='checkbox' checked={prefs.enabled} onClick={this.toggleEnabled}/> <strong> CD+Graphics</strong> </label> <button onClick={this.handleRefresh}>Refresh</button> {paths} </div> ) } }
Remove vírgulas que não fazem parte do meu estilo
var path = require('path') var pkg = require('./package.json') var UglifyjsPlugin = require('uglifyjs-webpack-plugin') var BannerPlugin = require('webpack').BannerPlugin module.exports = { entry: { 'extenso': './index.js', 'extenso.min': './index.js' }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist'), library: 'extenso', libraryTarget: 'umd' }, module: { rules: [{ test: /\.js$/i, use: 'babel-loader' }] }, plugins: [ new UglifyjsPlugin({ include: /\.min\.js$/, uglifyOptions: { output: { comments: false } } }), new BannerPlugin([ 'Extenso.js ' + pkg.version, '© 2015-' + (new Date()).getFullYear() + ' ' + pkg.author, 'License: ' + pkg.license ].join('\n')) ] }
var path = require('path') var pkg = require('./package.json') var UglifyjsPlugin = require('uglifyjs-webpack-plugin') var BannerPlugin = require('webpack').BannerPlugin module.exports = { entry: { 'extenso': './index.js', 'extenso.min': './index.js' }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist'), library: 'extenso', libraryTarget: 'umd' }, module: { rules: [{ test: /\.js$/i, use: 'babel-loader' }] }, plugins: [ new UglifyjsPlugin({ include: /\.min\.js$/, uglifyOptions: { output: { comments: false, }, }, }), new BannerPlugin([ 'Extenso.js ' + pkg.version, '© 2015-' + (new Date()).getFullYear() + ' ' + pkg.author, 'License: ' + pkg.license ].join('\n')) ] }
Set Flamsteed `schema` to `Flamsteed` instance
require([ "jquery" ], function($) { "use strict"; require([ "lib/core/base", "lib/page/scroll_perf", "flamsteed", "trackjs", "polyfills/function_bind", "polyfills/xdr" ], function(Base, ScrollPerf, Flamsteed) { $(function() { var secure = window.location.protocol === "https:"; new Base(); new ScrollPerf; // Currently we can"t serve Flamsteed over https because of f.staticlp.com // https://trello.com/c/2RCd59vk/201-move-f-staticlp-com-off-cloudfront-and-on-to-fastly-so-we-can-serve-over-https if (!secure) { if (window.lp.getCookie) { window.lp.fs = new Flamsteed({ events: window.lp.fs.buffer, u: window.lp.getCookie("lpUid"), schema: "0.2" }); } require([ "sailthru" ], function() { window.Sailthru.setup({ domain: "horizon.lonelyplanet.com" }); }); } }); }); });
require([ "jquery" ], function($) { "use strict"; require([ "lib/core/base", "lib/page/scroll_perf", "flamsteed", "trackjs", "polyfills/function_bind", "polyfills/xdr" ], function(Base, ScrollPerf, Flamsteed) { $(function() { var secure = window.location.protocol === "https:"; new Base(); new ScrollPerf; // Currently we can"t serve Flamsteed over https because of f.staticlp.com // https://trello.com/c/2RCd59vk/201-move-f-staticlp-com-off-cloudfront-and-on-to-fastly-so-we-can-serve-over-https if (!secure) { if (window.lp.getCookie) { window.lp.fs = new Flamsteed({ events: window.lp.fs.buffer, u: window.lp.getCookie("lpUid") }); } require([ "sailthru" ], function() { window.Sailthru.setup({ domain: "horizon.lonelyplanet.com" }); }); } }); }); });
Fix checkboxes not ticking themselves Closes #1
// Wrap your stuff in this module pattern for dependency injection (function ($, ContentBlocks) { // Add your custom input to the fieldTypes object as a function // The dom variable contains the injected field (from the template) // and the data variable contains field information, properties etc. ContentBlocks.fieldTypes.checkblock = function(dom, data) { var input = { // Some optional variables can be defined here }; // Do something when the input is being loaded input.init = function() { $(dom.find('#checkblock_' + data.generated_id)).prop('checked', data.value); } // Get the data from this input, it has to be a simple object. input.getData = function() { return { value:$(dom.find('#checkblock_' + data.generated_id)).is(':checked') } } // Always return the input variable. return input; } })(vcJquery, ContentBlocks);
// Wrap your stuff in this module pattern for dependency injection (function ($, ContentBlocks) { // Add your custom input to the fieldTypes object as a function // The dom variable contains the injected field (from the template) // and the data variable contains field information, properties etc. ContentBlocks.fieldTypes.checkblock = function(dom, data) { var input = { // Some optional variables can be defined here }; // Do something when the input is being loaded input.init = function() { } // Get the data from this input, it has to be a simple object. input.getData = function() { return { value:$(document.getElementById('checkblock_' + data.generated_id)).is(':checked') } } // Always return the input variable. return input; } })(vcJquery, ContentBlocks);
Revert "Revert "Changed back due to problems, will fix later"" This reverts commit 37fa1b22539dd31b8efc4c22b1ba9269822f77e1. modified: setup.py
from distutils.core import setup import sys import os import re PACKAGENAME = 'OpSimSummary' packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), PACKAGENAME) versionFile = os.path.join(packageDir, 'version.py') # Obtain the package version with open(versionFile, 'r') as f: s = f.read() # Look up the string value assigned to __version__ in version.py using regexp versionRegExp = re.compile("__VERSION__ = \"(.*?)\"") # Assign to __version__ __version__ = versionRegExp.findall(s)[0] print(__version__) setup(# package information name=PACKAGENAME, version=__version__, description='simple repo to study OpSim output summaries', long_description=''' ''', # What code to include as packages packages=[PACKAGENAME], packagedir={PACKAGENAME: 'opsimsummary'}, # What data to include as packages include_package_data=True, package_data={PACKAGENAME:['example_data/*.dat', 'example_data/*.simlib']} )
from distutils.core import setup import sys import os import re PACKAGENAME = 'OpSimSummary' packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opsimsummary') versionFile = os.path.join(packageDir, 'version.py') # Obtain the package version with open(versionFile, 'r') as f: s = f.read() # Look up the string value assigned to __version__ in version.py using regexp versionRegExp = re.compile("__VERSION__ = \"(.*?)\"") # Assign to __version__ __version__ = versionRegExp.findall(s)[0] print(__version__) setup(# package information name=PACKAGENAME, version=__version__, description='simple repo to study OpSim output summaries', long_description=''' ''', # What code to include as packages packages=[PACKAGENAME], packagedir={PACKAGENAME: 'opsimsummary'}, # What data to include as packages include_package_data=True, package_data={PACKAGENAME:['example_data/*.dat', 'example_data/*.simlib']} )
Fix error when npmName return false
'use strict'; var _ = require('lodash'); var path = require('path'); var npmName = require('npm-name'); module.exports = function askName(prompt, generator, cb) { var prompts = [prompt, { type: 'confirm', name: 'askAgain', message: 'The name above already exists on npm, choose another?', default: true, when: function (answers) { var done = this.async(); npmName(answers[prompt.name], function (err, available) { if (available) { done(); } else { done(true); } }); } }]; generator.prompt(prompts, function (props) { if (props.askAgain) { return askName(prompt, generator, cb); } cb(props[prompt.name]); }); };
'use strict'; var _ = require('lodash'); var path = require('path'); var npmName = require('npm-name'); module.exports = function askName(prompt, generator, cb) { var prompts = [prompt, { type: 'confirm', name: 'askAgain', message: 'The name above already exists on npm, choose another?', default: true, when: function (answers) { var done = this.async(); npmName(answers[prompt.name], function (err, available) { if (available) { done(); } else { done(true); } }); } }]; generator.prompt(prompts, function (props) { if (props.askAgain) { return askName(generator); } cb(props[prompt.name]); }); };
Fix python 3 support for exec
import sys # Used to get rid of py2/3 differences # Blatantly stolen from the excellent `six` library # Allows the same calls between python2 and python3 if sys.version_info[0] == 3: exec_ = __builtins__["exec"] raw_input = input else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""")
import sys # Used to get rid of py2/3 differences # Blatantly stolen from the excellent `six` library # Allows the same calls between python2 and python3 if sys.version_info[0] == 3: exec_ = getattr(__builtins__, "exec") raw_input = input else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""")
Fix failing build in 'builtin_assets' mode
// +build builtin_assets package main import ( "context" "net/http" "path" "path/filepath" "strings" ) const ( httpDefaultPath = "html/index.html" ) func (w *httpWorker) httpHandleAsset(ctx context.Context, rw http.ResponseWriter, r *http.Request) { var ct string // Stop handling assets if frontend is disabled if !w.enableFrontend { rw.WriteHeader(http.StatusForbidden) return } // Get file data from built-in assets filePath := strings.TrimPrefix(r.URL.Path, "/assets/") if strings.HasSuffix(filePath, "/") || filepath.Ext(filePath) == "" { filePath = httpDefaultPath } data, err := Asset(filePath) if err != nil { rw.WriteHeader(http.StatusNotFound) return } // Get asset content type switch path.Ext(filePath) { case ".css": ct = "text/css" case ".js": ct = "text/javascript" default: ct = http.DetectContentType(data) } rw.Header().Set("Content-Type", ct) rw.WriteHeader(http.StatusOK) rw.Write(data) }
// +build builtin_assets package main import ( "context" "net/http" "path" "path/filepath" "strings" ) const ( httpDefaultPath = "html/index.html" ) func (w *httpWorker) httpHandleAsset(ctx context.Context, rw http.ResponseWriter, r *http.Request) { var ct string // Stop handling assets if frontend is disabled if w.disableFrontend { rw.WriteHeader(http.StatusForbidden) return } // Get file data from built-in assets filePath := strings.TrimPrefix(r.URL.Path, "/assets/") if strings.HasSuffix(filePath, "/") || filepath.Ext(filePath) == "" { filePath = httpDefaultPath } data, err := Asset(filePath) if err != nil { rw.WriteHeader(http.StatusNotFound) return } // Get asset content type switch path.Ext(filePath) { case ".css": ct = "text/css" case ".js": ct = "text/javascript" default: ct = http.DetectContentType(data) } rw.Header().Set("Content-Type", ct) rw.WriteHeader(http.StatusOK) rw.Write(data) }
Update statistics epoch for easier testing
import socket import datetime hostname = socket.gethostname().split('.')[0] config = { # Consumer stuff "statscache.consumer.enabled": True, "statscache.sqlalchemy.uri": "sqlite:////var/tmp/statscache-dev-db.sqlite", # stats models will go back at least this far (current value arbitrary) "statscache.consumer.epoch": datetime.datetime(year=2015, month=8, day=8), # stats models are updated at this frequency "statscache.producer.frequency": datetime.timedelta(seconds=1), # Turn on logging for statscache "logging": dict( loggers=dict( statscache={ "level": "DEBUG", "propagate": False, "handlers": ["console"], }, statscache_plugins={ "level": "DEBUG", "propagate": False, "handlers": ["console"], }, ), ), }
import socket import datetime hostname = socket.gethostname().split('.')[0] config = { # Consumer stuff "statscache.consumer.enabled": True, "statscache.sqlalchemy.uri": "sqlite:////var/tmp/statscache-dev-db.sqlite", # stats models will go back at least this far (current value arbitrary) "statscache.consumer.epoch": datetime.datetime(year=2015, month=6, day=1), # stats models are updated at this frequency "statscache.producer.frequency": datetime.timedelta(seconds=1), # Turn on logging for statscache "logging": dict( loggers=dict( statscache={ "level": "DEBUG", "propagate": False, "handlers": ["console"], }, statscache_plugins={ "level": "DEBUG", "propagate": False, "handlers": ["console"], }, ), ), }
Use same binary as Fingerprint in the QemuCompatible function
package testutil import ( "os/exec" "runtime" "syscall" "testing" ) func ExecCompatible(t *testing.T) { if runtime.GOOS != "windows" && syscall.Geteuid() != 0 { t.Skip("Must be root on non-windows environments to run test") } } func QemuCompatible(t *testing.T) { // Check if qemu exists bin := "qemu-system-x86_64" if runtime.GOOS == "windows" { bin = "qemu-img" } _, err := exec.Command(bin, "--version").CombinedOutput() if err != nil { t.Skip("Must have Qemu installed for Qemu specific tests to run") } } func RktCompatible(t *testing.T) { if runtime.GOOS == "windows" || syscall.Geteuid() != 0 { t.Skip("Must be root on non-windows environments to run test") } // else see if rkt exists _, err := exec.Command("rkt", "version").CombinedOutput() if err != nil { t.Skip("Must have rkt installed for rkt specific tests to run") } } func MountCompatible(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Windows does not support mount") } if syscall.Geteuid() != 0 { t.Skip("Must be root to run test") } }
package testutil import ( "os/exec" "runtime" "syscall" "testing" ) func ExecCompatible(t *testing.T) { if runtime.GOOS != "windows" && syscall.Geteuid() != 0 { t.Skip("Must be root on non-windows environments to run test") } } func QemuCompatible(t *testing.T) { // Check if qemu exists _, err := exec.Command("qemu-system-x86_64", "-version").CombinedOutput() if err != nil { t.Skip("Must have Qemu installed for Qemu specific tests to run") } } func RktCompatible(t *testing.T) { if runtime.GOOS == "windows" || syscall.Geteuid() != 0 { t.Skip("Must be root on non-windows environments to run test") } // else see if rkt exists _, err := exec.Command("rkt", "version").CombinedOutput() if err != nil { t.Skip("Must have rkt installed for rkt specific tests to run") } } func MountCompatible(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("Windows does not support mount") } if syscall.Geteuid() != 0 { t.Skip("Must be root to run test") } }
Send server error log for debugging
import nodemailer from 'nodemailer'; import config from '../../config.js'; function getSmtpTransport(service, user, pass) { return nodemailer.createTransport('SMTP', { service, auth: { user, pass } }); } export default function sendMail(req, res) { let from = req.body.from, sender = req.body.sender, body = req.body.text; if(!from || !sender || !body) { res.status(400); res.send('Invalid args!'); } let smtpTransport = getSmtpTransport(config.email.service, config.email.user, config.email.password); smtpTransport.sendMail({ from: req.body.from, to: config.email.user, subject: `${config.email.subject} [${req.body.sender}]`, body: req.body.text }, (error) => { if(error) { console.log(error); res.status(500); res.send(error + 'Unable to send mail!'); } else { res.status(200); res.send('Thank you! I will contact you as soon as possible'); } }); }
import nodemailer from 'nodemailer'; import config from '../../config.js'; function getSmtpTransport(service, user, pass) { return nodemailer.createTransport('SMTP', { service, auth: { user, pass } }); } export default function sendMail(req, res) { let from = req.body.from, sender = req.body.sender, body = req.body.text; if(!from || !sender || !body) { res.status(400); res.send('Invalid args!'); } let smtpTransport = getSmtpTransport(config.email.service, config.email.user, config.email.password); smtpTransport.sendMail({ from: req.body.from, to: config.email.user, subject: `${config.email.subject} [${req.body.sender}]`, body: req.body.text }, (error) => { if(error) { console.log(error); res.status(500); res.send('Unable to send mail!'); } else { res.status(200); res.send('Thank you! I will contact you as soon as possible'); } }); }
Throw error if factory is not found
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { var factory = _.findWhere(FactoryBoy._factories, {name: name}); if (! factory) { throw new Error('Could not find the factory by that name'); } return factory; }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; var deepExtend = Npm.require('deep-extend'); // Allow to overwrite the attribute definitions var attr = deepExtend(factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, collection, attrOverwrite) { var factory = this._getFactory(name); return factory.attributes; };
FactoryBoy = {}; FactoryBoy._factories = []; Factory = function (name, collection, attributes) { this.name = name; this.collection = collection; this.attributes = attributes; }; FactoryBoy.define = function (name, collection, attributes) { var factory = new Factory(name, collection, attributes); FactoryBoy._factories.push(factory); }; FactoryBoy._getFactory = function (name) { return _.findWhere(FactoryBoy._factories, {name: name}); }; FactoryBoy.create = function (name, newAttr) { var factory = this._getFactory(name); var collection = factory.collection; var deepExtend = Npm.require('deep-extend'); // Allow to overwrite the attribute definitions var attr = deepExtend(factory.attributes, newAttr); var docId = collection.insert(attr); var doc = collection.findOne(docId); return doc; }; FactoryBoy.build = function (name, collection, attrOverwrite) { var factory = this._getFactory(name); return factory.attributes; };
Add an action to get species by family
/* global angular */ angular .module('speciesApp') .factory('SpeciesService', [ 'API_BASE_URL', '$resource', SpeciesService ]) function SpeciesService (API_BASE_URL, $resource) { return $resource( API_BASE_URL, null, { getKingdoms: { method: 'GET', isArray: false, cache: true, params: { op: 'getkingdomnames' } }, getClasses: { method: 'GET', isArray: false, cache: true, params: { op: 'getclassnames' } }, getFamilies: { method: 'GET', isArray: false, cache: true, params: { op: 'getfamilynames' } }, getSpecies: { method: 'GET', isArray: false, cache: true, params: { op: 'getspecies' } } } ) }
/* global angular */ angular .module('speciesApp') .factory('SpeciesService', [ 'API_BASE_URL', '$resource', SpeciesService ]) function SpeciesService (API_BASE_URL, $resource) { return $resource( API_BASE_URL, null, { getKingdoms: { method: 'GET', isArray: false, cache: true, params: { op: 'getkingdomnames' } }, getClasses: { method: 'GET', isArray: false, cache: true, params: { op: 'getclassnames' } }, getFamilies: { method: 'GET', isArray: false, cache: true, params: { op: 'getfamilynames' } } } ) }
Fix dictionary access pattern for setting auth tokens
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] if 'ACCESS_KEY' in os.environ: # If OAuth integration is available, take it authenticate.setdefault(fam, {})['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) del fam
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] if 'ACCESS_KEY' in os.environ: # If OAuth integration is available, take it authenticate[fam]['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) del fam
Enforce that pbr used is >= 1.8 It otherwise fails if used against older pbr (e.g distro packaging build) Change-Id: I19dbd5d14a9135408ad21a34834f0bd1fb3ea55d
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass setuptools.setup( setup_requires=['pbr>=1.8'], pbr=True)
#!/usr/bin/env python # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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. import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass setuptools.setup( setup_requires=['pbr>=1.3'], pbr=True)
Add mkdn extension to markdown extension list See: https://github.com/sculpin/sculpin/commit/c3b9cbe8827977b4d7759f94a971bb13cc00a226
<?php namespace Bcremer\Sculpin\Bundle\CommonMarkBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder; $rootNode = $treeBuilder->root('sculpin_commonmark'); $rootNode ->children() ->arrayNode('extensions') ->defaultValue(['md', 'mdown', 'mkdn', 'markdown']) ->prototype('scalar')->end() ->end() ->end(); return $treeBuilder; } }
<?php namespace Bcremer\Sculpin\Bundle\CommonMarkBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder; $rootNode = $treeBuilder->root('sculpin_commonmark'); $rootNode ->children() ->arrayNode('extensions') ->defaultValue(['md', 'mdown', 'markdown']) ->prototype('scalar')->end() ->end() ->end(); return $treeBuilder; } }
Make test name less generic.
package uk.ac.ebi.quickgo.annotation.service.converter; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.model.Annotation; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.mockito.Mockito.when; /** * @author Tony Wardell * Date: 29/04/2016 * Time: 17:39 * Created with IntelliJ IDEA. */ @RunWith(MockitoJUnitRunner.class) public class AnnotationDocConverterImplTest { @Test public void convertAssignedBySuccessfully(){ AnnotationDocConverter docConverter = new AnnotationDocConverterImpl(); Annotation model = docConverter.convert( AnnotationDocMocker.createAnnotationDoc("A0A000")); assertThat(model.assignedBy, equalTo("InterPro")); } }
package uk.ac.ebi.quickgo.annotation.service.converter; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker; import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument; import uk.ac.ebi.quickgo.annotation.model.Annotation; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.mockito.Mockito.when; /** * @author Tony Wardell * Date: 29/04/2016 * Time: 17:39 * Created with IntelliJ IDEA. */ @RunWith(MockitoJUnitRunner.class) public class AnnotationDocConverterImplTest { @Test public void convertSuccessfully(){ AnnotationDocConverter docConverter = new AnnotationDocConverterImpl(); Annotation model = docConverter.convert( AnnotationDocMocker.createAnnotationDoc("A0A000")); assertThat(model.assignedBy, equalTo("InterPro")); } }
Update function signature in req handler
var async = require( 'async' ); var Validation = require( './validation' ); var Data = require( './data' ); var Output = require( './output' ); var utils = require( '../utils' ); exports.authenticate = function ( req, res ) { async.waterfall( [ function ( callback ) { Validation.forAuthenticate( req.body, callback ); }, function ( validatedRequest, callback ) { Data.verifyCredentials( req.body.email, req.body.password, callback ); }, function ( userData, callback ) { Output.makeToken( userData, callback ); } ], function ( err, output ) { if ( err ) { return utils.handleRouteError( err, res ); } return res.json( output, 200 ); } ); };
var async = require( 'async' ); var Validation = require( './validation' ); var Data = require( './data' ); var Output = require( './output' ); var utils = require( '../utils' ); exports.authenticate = function ( req, res ) { async.waterfall( [ function ( callback ) { Validation.forAuthenticate( req.body, callback ); }, function ( validatedRequest, callback ) { Data.verifyCredentials( req.body.username, req.body.password ); }, function ( userData, callback ) { Output.makeToken( userData, callback ); } ], function ( err, output ) { if ( err ) { return utils.handleRouteError( err, res ); } return res.json( output, 200 ); } ); };
Add statistics package to component scan.
package uk.ac.ebi.quickgo.annotation; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.rest.controller.CORSFilter; import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * * The RESTful service configuration for Annotations * * @author Tony Wardell * Date: 26/04/2016 * Time: 14:41 * Created with IntelliJ IDEA. */ @SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class}) @ComponentScan({"uk.ac.ebi.quickgo.annotation.controller", "uk.ac.ebi.quickgo.rest", "uk.ac.ebi.quickgo.annotation.service.statistics"}) @Import({SearchServiceConfig.class, SwaggerConfig.class, CORSFilter.class}) public class AnnotationREST { /** * Ensures that placeholders are replaced with property values */ @Bean static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { SpringApplication.run(AnnotationREST.class, args); } }
package uk.ac.ebi.quickgo.annotation; import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.rest.controller.CORSFilter; import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * * The RESTful service configuration for Annotations * * @author Tony Wardell * Date: 26/04/2016 * Time: 14:41 * Created with IntelliJ IDEA. */ @SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class}) @ComponentScan({"uk.ac.ebi.quickgo.annotation.controller", "uk.ac.ebi.quickgo.rest"}) @Import({SearchServiceConfig.class, SwaggerConfig.class, CORSFilter.class}) public class AnnotationREST { /** * Ensures that placeholders are replaced with property values */ @Bean static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static void main(String[] args) { SpringApplication.run(AnnotationREST.class, args); } }
Revert "Inline Validation fails silently if request is malformed" This reverts commit 723e4eb603568d3a60190d8d292cc335a74b79d5.
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
from Products.Archetypes.browser.validation import InlineValidationView as _IVV from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName import json SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference') class InlineValidationView(_IVV): def __call__(self, uid, fname, value): '''Validate a given field. Return any error messages. ''' res = {'errmsg': ''} if value not in self.request: return json.dumps(res) rc = getToolByName(aq_inner(self.context), 'reference_catalog') instance = rc.lookupObject(uid) # make sure this works for portal_factory items if instance is None: instance = self.context field = instance.getField(fname) if field and field.type not in SKIP_VALIDATION_FIELDTYPES: return super(InlineValidationView, self).__call__(uid, fname, value) self.request.response.setHeader('Content-Type', 'application/json') return json.dumps(res)
Remove the fake video stream, add audio
$(document).ready(function () { var provider = new XMPPProvider({webrtc: {video: true, audio: true}}); $('form').submit(function() { var jid = $('#jid').val(); var pass = $('#pass').val(); provider.connect({jid: jid, pass: pass}); return false; }); provider.on('contact-list', function(roster) { var n = roster.length; for (var i = 0; i < n; i++) { $('#contacts ul') .append('<li data-jid="' + roster[i] + '">' + roster[i] + '</li>'); } }); provider.on('presence', function(who, type) { var link = $('<a href="#">' + who.pseudo + '</a>').click(function() { provider.call(who.id); }); $('#contacts ul li[data-jid="' + who.pseudo + '"]').html(link); }); provider.on('stream', function(stream, type, remote) { var video = remote ? $("#remoteVideo")[0] : $("#localVideo")[0]; video.mozSrcObject = stream; video.play(); }); });
$(document).ready(function () { var provider = new XMPPProvider({webrtc: {video: true, fake: true}}); $('form').submit(function() { var jid = $('#jid').val(); var pass = $('#pass').val(); provider.connect({jid: jid, pass: pass}); return false; }); provider.on('contact-list', function(roster) { var n = roster.length; for (var i = 0; i < n; i++) { $('#contacts ul') .append('<li data-jid="' + roster[i] + '">' + roster[i] + '</li>'); } }); provider.on('presence', function(who, type) { var link = $('<a href="#">' + who.pseudo + '</a>').click(function() { provider.call(who.id); }); $('#contacts ul li[data-jid="' + who.pseudo + '"]').html(link); }); provider.on('stream', function(stream, type, remote) { var video = remote ? $("#remoteVideo")[0] : $("#localVideo")[0]; video.mozSrcObject = stream; video.play(); }); });
Handle case where user.role is null when determining the public view status for a user
app.controller("DashboardController", function ($controller, $scope, UserService, NoteRepo, OverallStatusFull, OverallStatusPublic, ServiceRepo) { angular.extend(this, $controller('AppAbstractController', { $scope: $scope })); $scope.overallStatus = $scope.isFullServiceConsumer() ? new OverallStatusFull() : new OverallStatusPublic(); $scope.services = ServiceRepo.getAll(); $scope.showShortList = true; $scope.showPublic = function () { var user = UserService.getCurrentUser(); var publicView = false; if (user.role === undefined || user.role === null) { publicView = true; } else if (user.role === 'ROLE_ANONYMOUS' || user.role === 'ROLE_USER') { publicView = true; } return publicView; }; $scope.showHideShortList = function () { $scope.showShortList = !$scope.showShortList; }; $scope.tableParams = NoteRepo.getTableParams(); NoteRepo.getPageSettings().filters = { active: [true] }; NoteRepo.getPageSettings().sort = [{ property: 'service.name', direction: 'ASC' }, { property: 'lastModified', direction: 'DESC' }]; NoteRepo.page(); });
app.controller("DashboardController", function ($controller, $scope, UserService, NoteRepo, OverallStatusFull, OverallStatusPublic, ServiceRepo) { angular.extend(this, $controller('AppAbstractController', { $scope: $scope })); $scope.overallStatus = $scope.isFullServiceConsumer() ? new OverallStatusFull() : new OverallStatusPublic(); $scope.services = ServiceRepo.getAll(); $scope.showShortList = true; $scope.showPublic = function () { var user = UserService.getCurrentUser(); var publicView = false; if (user.role === undefined) { publicView = true; } else if (user.role === 'ROLE_ANONYMOUS' || user.role === 'ROLE_USER') { publicView = true; } return publicView; }; $scope.showHideShortList = function () { $scope.showShortList = !$scope.showShortList; }; $scope.tableParams = NoteRepo.getTableParams(); NoteRepo.getPageSettings().filters = { active: [true] }; NoteRepo.getPageSettings().sort = [{ property: 'service.name', direction: 'ASC' }, { property: 'lastModified', direction: 'DESC' }]; NoteRepo.page(); });
Remove development auto admin user creation
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
from functools import wraps from flask import request, abort, redirect, url_for, render_template from flask.ext.login import LoginManager, login_user, logout_user, login_required from app import app, db from app.models import User login_manager = LoginManager() login_manager.init_app(app) # required function for flask-login to function @login_manager.user_loader def user_loader(id): return User.query.get(id) # testing: automatically make an admin user if not User.query.first(): u = User('admin', 'password') db.session.add(u) db.session.commit() @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'POST': if request.form['user'] == 'admin' and request.form['password'] == 'password': u = User.query.filter_by(handle=request.form['user']).first() login_user(u) return redirect(url_for('admin_index')) return render_template('login.html') @app.route('/logout/') def logout(): logout_user() return redirect(url_for('index'))
Fix bug that prevented vertical rhythm scaling for 0 values
import ms from 'modularscale' // Calculate box model values that conforms to the established Vertical Rhythm export function boxModelRuleVerticalRhythm ( size, { baseFontSize, lineHeightRatio } ) { if (size === undefined || size == null) { return size } const baseline = Math.floor(lineHeightRatio * baseFontSize) const retval = baseline * size // Compensate for rounding errors that make the return value not divisible const offset = retval % baseline return `${retval - offset}px` } // Calculate typographic values that conforms to the established Vertical Rhythm export function typographyVerticalRhythm ( size, { baseFontSize, lineHeightRatio, scaleRatio } ) { const fontSize = ms(size, scaleRatio) const multiplier = Math.ceil(fontSize / lineHeightRatio) return { fontSize: `${fontSize}rem`, lineHeight: boxModelRuleVerticalRhythm(multiplier, { baseFontSize, lineHeightRatio }) } }
import ms from 'modularscale' // Calculate box model values that conforms to the established Vertical Rhythm export function boxModelRuleVerticalRhythm ( size, { baseFontSize, lineHeightRatio } ) { if (!size) { return null } const baseline = Math.floor(lineHeightRatio * baseFontSize) const retval = baseline * size // Compensate for rounding errors that make the return value not divisible const offset = retval % baseline return `${retval - offset}px` } // Calculate typographic values that conforms to the established Vertical Rhythm export function typographyVerticalRhythm ( size, { baseFontSize, lineHeightRatio, scaleRatio } ) { const fontSize = ms(size, scaleRatio) const multiplier = Math.ceil(fontSize / lineHeightRatio) return { fontSize: `${fontSize}rem`, lineHeight: boxModelRuleVerticalRhythm(multiplier, { baseFontSize, lineHeightRatio }) } }
Set the version from gocd_cli instead of gocd
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) def version(): import gocd_cli return gocd_cli.__version__ setup( name='gocd_cli', author='Björn Andersson', author_email='ba@sanitarium.se', license='MIT License', version=version(), packages=find_packages(exclude=('tests',)), namespace_packages=('gocd_cli', 'gocd_cli.commands',), cmdclass={'test': PyTest}, requires=[ 'gocd_cli', ], tests_require=[ 'pytest', ], )
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) def version(): import gocd return gocd.__version__ setup( name='gocd_cli', author='Björn Andersson', author_email='ba@sanitarium.se', license='MIT License', version=version(), packages=find_packages(exclude=('tests',)), namespace_packages=('gocd_cli', 'gocd_cli.commands',), cmdclass={'test': PyTest}, requires=[ 'gocd_cli', ], tests_require=[ 'pytest', ], )
Change version number to 0.1 ...in preparation for the upcoming release.
# Copyright 2013-2014 Massachusetts Open Cloud Contributors # # 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. from setuptools import setup, find_packages from pip.req import parse_requirements from os import path # requirements_file is the relative path from where setup.py is being # called from, to where requirements.txt resides requirements_file = path.join(path.dirname(__file__), 'requirements.txt') requirements = [str(r.req) for r in parse_requirements(requirements_file)] setup(name='haas', version='0.1', url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], install_requires=requirements, )
# Copyright 2013-2014 Massachusetts Open Cloud Contributors # # 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. from setuptools import setup, find_packages from pip.req import parse_requirements from os import path # requirements_file is the relative path from where setup.py is being # called from, to where requirements.txt resides requirements_file = path.join(path.dirname(__file__), 'requirements.txt') requirements = [str(r.req) for r in parse_requirements(requirements_file)] setup(name='haas', version='1.0', url='https://github.com/CCI-MOC/haas', packages=find_packages(), scripts=['scripts/haas', 'scripts/create_bridges'], install_requires=requirements, )
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105 Patch #3605769 by Legoktm Because of various issues [1], using wikidata.org may cause random problems. Using www.wikidata.org will fix these. [1] https://bugzilla.wikimedia.org/show_bug.cgi?id=45005 git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11106 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', } def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return(None, None) else: return ('wikidata', 'wikidata') if code == 'wikidata' else ('repo', 'wikidata')
Add NUMBER_UPDATE action in settings actons
import { CHECKBOX_UPDATE, RANGE_UPDATE, FUZZY, SEARCH_KEY_UPDATE, SETTINGS_RESET, NUMBER_UPDATE, } from '../../actions/types'; export function updateNumber(key, value) { return { type: NUMBER_UPDATE, payload: { key, value, }, }; } export function updateCheckbox(key, value) { return { type: CHECKBOX_UPDATE, payload: { key, value, }, }; } export function updateFuzzyCheckbox(key, value) { return { type: FUZZY + CHECKBOX_UPDATE, payload: { key, value, }, }; } export function updateFuzzyThresholdRange(value) { return { type: FUZZY + RANGE_UPDATE, payload: { key: 'threshold', value: value / 10, }, }; } export function updateFuzzySearchKeys(value) { return { type: FUZZY + SEARCH_KEY_UPDATE, payload: { key: 'keys', value, }, }; } export function resetSettings() { return { type: SETTINGS_RESET, }; }
import { CHECKBOX_UPDATE, RANGE_UPDATE, FUZZY, SEARCH_KEY_UPDATE, SETTINGS_RESET, } from '../../actions/types'; export function updateCheckbox(key, value) { return { type: CHECKBOX_UPDATE, payload: { key, value, }, }; } export function updateFuzzyCheckbox(key, value) { return { type: FUZZY + CHECKBOX_UPDATE, payload: { key, value, }, }; } export function updateFuzzyThresholdRange(value) { return { type: FUZZY + RANGE_UPDATE, payload: { key: 'threshold', value: value / 10, }, }; } export function updateFuzzySearchKeys(value) { return { type: FUZZY + SEARCH_KEY_UPDATE, payload: { key: 'keys', value, }, }; } export function resetSettings() { return { type: SETTINGS_RESET, }; }
Fix chest using taken ID
package com.jmrapp.terralegion.game.world.block; public enum BlockType { AIR(0), DIRT(1), GRASS(2), STONE(3), DIAMOND(4), TORCH(5), STONE_WALL(6), COAL(8), DIRT_WALL(9), WOOD(10), LEAVES(11), WOOD_CHEST(14); private static final BlockType[] blockTypeArray = values(); private final int id; BlockType(int id) { this.id = id; } public int getId() { return id; } public static BlockType getBlockType(int id) { for (BlockType type : blockTypeArray) { if (type.getId() == id) return type; } return AIR; } }
package com.jmrapp.terralegion.game.world.block; public enum BlockType { AIR(0), DIRT(1), GRASS(2), STONE(3), DIAMOND(4), TORCH(5), STONE_WALL(6), COAL(8), DIRT_WALL(9), WOOD(10), LEAVES(11), WOOD_CHEST(12); private static final BlockType[] blockTypeArray = values(); private final int id; BlockType(int id) { this.id = id; } public int getId() { return id; } public static BlockType getBlockType(int id) { for (BlockType type : blockTypeArray) { if (type.getId() == id) return type; } return AIR; } }
Fix really broken destructible material test.
package com.elmakers.mine.bukkit.plugins.magic; import java.util.Set; import org.bukkit.Material; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public abstract class BlockSpell extends Spell { private Set<Material> indestructible; private Set<Material> destructible; public boolean isIndestructible(Block block) { if (indestructible == null) { return mage.isIndestructible(block); } return indestructible.contains(block.getType()); } public boolean isDestructible(Block block) { if (destructible == null) { return mage.isDestructible(block); } return destructible.contains(block.getType()); } @Override protected void processParameters(ConfigurationNode parameters) { super.processParameters(parameters); indestructible = null; if (parameters.containsKey("indestructible")) { indestructible = parameters.getMaterials("indestructible", ""); } destructible = null; if (parameters.containsKey("destructible")) { destructible = parameters.getMaterials("destructible", ""); } } }
package com.elmakers.mine.bukkit.plugins.magic; import java.util.Set; import org.bukkit.Material; import org.bukkit.block.Block; import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode; public abstract class BlockSpell extends Spell { private Set<Material> indestructible; private Set<Material> destructible; public boolean isIndestructible(Block block) { if (indestructible == null) { return mage.isIndestructible(block); } return indestructible.contains(block); } public boolean isDestructible(Block block) { if (destructible == null) { return mage.isDestructible(block); } return destructible.contains(block); } @Override protected void processParameters(ConfigurationNode parameters) { super.processParameters(parameters); indestructible = null; if (parameters.containsKey("indestructible")) { indestructible = parameters.getMaterials("indestructible", ""); } destructible = null; if (parameters.containsKey("destructible")) { destructible = parameters.getMaterials("destructible", ""); } } }
Fix controller on invalid key press
class Controller { constructor () { this.listeners = [] this.key = null window.addEventListener('keydown', e => { if (e.keyCode === this.key) return this.key = e.keyCode this.listeners.forEach(listener => { listener && Controller.KEYS[this.key] && listener(Controller.KEYS[this.key]) }) }) window.addEventListener('keyup', e => { this.key = null }) } onKey (listener) { var listenerIndex = this.listeners.length this.listeners.push(listener) return function () { this.listeners[listenerIndex] = null } } } Controller.KEYS = { 37: {move: 'left'}, 38: {move: 'up'}, 39: {move: 'right'}, 40: {move: 'down'}, 65: {rotate: 'left'}, 83: {rotate: 'right'}, 32: {pause: true} }
class Controller { constructor () { this.listeners = [] this.key = null window.addEventListener('keydown', e => { if (e.keyCode === this.key) return this.key = e.keyCode this.listeners.forEach(listener => { listener && listener(Controller.KEYS[this.key]) }) }) window.addEventListener('keyup', e => { this.key = null }) } onKey (listener) { var listenerIndex = this.listeners.length this.listeners.push(listener) return function () { this.listeners[listenerIndex] = null } } } Controller.KEYS = { 37: {move: 'left'}, 38: {move: 'up'}, 39: {move: 'right'}, 40: {move: 'down'}, 65: {rotate: 'left'}, 83: {rotate: 'right'}, 32: {pause: true} }
Use CTC term for notification description SVN-Revision: 428
package gov.nih.nci.cabig.caaers.service; import com.semanticbits.aenotification.AENotification; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.domain.AdverseEventReport; import gov.nih.nci.cabig.caaers.esb.client.MessageBroadcastService; import gov.nih.nci.cabig.caaers.utils.XMLUtil; /** * * @author Sujith Vellat Thayyilthodi * */ public class InteroperationServiceImpl implements InteroperationService { private MessageBroadcastService messageBroadcastService; public void pushToStudyCalendar(AdverseEventReport aeReport) throws CaaersSystemException { AENotification aeNotification = new AENotification(); aeNotification.setRegistrationGridId( aeReport.getAssignment().getGridId()); aeNotification.setDetectionDate( new java.sql.Date(aeReport.getPrimaryAdverseEvent().getDetectionDate().getTime())); // TODO: verify that this is sufficient aeNotification.setDescription(aeReport.getPrimaryAdverseEvent().getCtcTerm().getFullName()); getMessageBroadcastService().broadcast(XMLUtil.getXML(aeNotification)); } public MessageBroadcastService getMessageBroadcastService() { return messageBroadcastService; } public void setMessageBroadcastService( MessageBroadcastService messageBroadcastService) { this.messageBroadcastService = messageBroadcastService; } }
package gov.nih.nci.cabig.caaers.service; import com.semanticbits.aenotification.AENotification; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.domain.AdverseEventReport; import gov.nih.nci.cabig.caaers.esb.client.MessageBroadcastService; import gov.nih.nci.cabig.caaers.utils.XMLUtil; /** * * @author Sujith Vellat Thayyilthodi * */ public class InteroperationServiceImpl implements InteroperationService { private MessageBroadcastService messageBroadcastService; public void pushToStudyCalendar(AdverseEventReport aeReport) throws CaaersSystemException { AENotification aeNotification = new AENotification(); aeNotification.setRegistrationGridId( aeReport.getAssignment().getGridId()); aeNotification.setDetectionDate( new java.sql.Date(aeReport.getPrimaryAdverseEvent().getDetectionDate().getTime())); aeNotification.setDescription(aeReport.getPrimaryAdverseEvent().getDetailsForOther()); getMessageBroadcastService().broadcast(XMLUtil.getXML(aeNotification)); } public MessageBroadcastService getMessageBroadcastService() { return messageBroadcastService; } public void setMessageBroadcastService( MessageBroadcastService messageBroadcastService) { this.messageBroadcastService = messageBroadcastService; } }
Add current user object to rootScope
angular.module('bolt.profile', ['bolt.auth']) .controller('ProfileController', function ($scope, Auth, Profile) { $rootScope.user = {}; $scope.newInfo = {}; var getUserInfo = function () { Profile.getUser() .then(function (user) { $rootScope.user = user; }); }; $scope.signout = function () { Auth.signout(); }; $scope.update = function () { var newProperties = {}; for (var property in $scope.newInfo) { newProperties[property] = $scope.newInfo[property]; $scope.newInfo[property] = ''; } Profile.updateUser(newProperties, $rootScope.user.username) .then( function(user) { $rootScope.user = user; getUserInfo(); }); }; $scope.$on('$routeChangeSuccess', function () { getUserInfo(); console.log('loading!'); // do something }); });
angular.module('bolt.profile', ['bolt.auth']) .controller('ProfileController', function ($scope, Auth, Profile) { $scope.user = {}; $scope.newInfo = {}; var getUserInfo = function () { Profile.getUser() .then(function (user) { $scope.user = user; }); }; $scope.signout = function () { Auth.signout(); }; $scope.update = function () { var newProperties = {}; for (var property in $scope.newInfo) { newProperties[property] = $scope.newInfo[property]; $scope.newInfo[property] = ''; } Profile.updateUser(newProperties, $scope.user.username) .then( function(user) { $scope.user = user; getUserInfo(); }); }; $scope.$on('$routeChangeSuccess', function () { getUserInfo(); console.log('loading!'); // do something }); });
Expand 5xx coverage; log exceptions
from __future__ import absolute_import import opentracing.ext.tags as ext import instana import opentracing import wrapt @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: span = instana.internal_tracer.start_span("urllib3") span.set_tag(ext.HTTP_URL, args[1]) span.set_tag(ext.HTTP_METHOD, args[0]) instana.internal_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"]) rv = wrapped(*args, **kwargs) span.set_tag(ext.HTTP_STATUS_CODE, rv.status) if 500 <= rv.status <= 599: span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) except Exception as e: span.log_kv({'message': e}) span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) raise else: span.finish() return rv
import opentracing.ext.tags as ext import opentracing import wrapt @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: span = opentracing.global_tracer.start_span("urllib3") span.set_tag(ext.HTTP_URL, args[1]) span.set_tag(ext.HTTP_METHOD, args[0]) opentracing.global_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"]) rv = wrapped(*args, **kwargs) span.set_tag(ext.HTTP_STATUS_CODE, rv.status) if 500 <= rv.status <= 511: span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) except Exception as e: print("found error:", e) span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) raise else: span.finish() return rv
Improve tag usage in logging helper Tags can be now specified before the message. Nice logger automatically recognices tags specified as a string or as an array. Closes #2
<?php class Log { public static function emergency($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_EMERGENCY); } public static function alert($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_ALERT); } public static function critical($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_CRITICAL); } public static function error($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_ERROR); } public static function warning($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_WARNING); } public static function notice($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_NOTICE); } public static function info($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_INFO); } public static function debug($tag, $message = "") { self::invoke_watchdog($tag, $message, WATCHDOG_DEBUG); } private static function invoke_watchdog($tag, $message, $severity) { if (!$message) { // Only message with no tags watchdog("", $tag, [], $severity); } else if (is_array($tag)) { // Tags specified as an array watchdog(implode($tag, ' '), $message, [], $severity); } else { // Tags specified as a string watchdog($tag, $message, [], $severity); } } }
<?php class Log { public static function emergency($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_EMERGENCY); } public static function alert($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_ALERT); } public static function critical($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_CRITICAL); } public static function error($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_ERROR); } public static function warning($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_WARNING); } public static function notice($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_NOTICE); } public static function info($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_INFO); } public static function debug($message, $tag = "") { self::invoke_watchdog($message, $tag, WATCHDOG_DEBUG); } private static function invoke_watchdog($message, $tag, $severity) { watchdog($tag, $message, [], $severity); } }
:art: Use Disposable instead of constructing one manually
'use babel' import Communication from 'sb-communication' import {CompositeDisposable, Disposable} from 'sb-event-kit' class ProcessCommunication { constructor(process, debug) { if (typeof process.send !== 'function') { throw new Error('Invalid process specified') } this.process = process this.communication = new Communication(debug) this.subscriptions = new CompositeDisposable(this.communication) this.communication.onShouldSend(data => { this.process.send(data) }) const callback = message => { this.communication.parseMessage(message) } this.process.addListener('message', callback) this.subscriptions.add(new Disposable(function() { process.removeListener('message', callback) })) } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } kill(sig) { this.process.kill(sig) this.dispose() } dispose() { this.subscriptions.dispose() } } export {ProcessCommunication as Communication}
'use babel' import Communication from 'sb-communication' import {CompositeDisposable} from 'sb-event-kit' class ProcessCommunication { constructor(process, debug) { if (typeof process.send !== 'function') { throw new Error('Invalid process specified') } this.process = process this.communication = new Communication(debug) this.subscriptions = new CompositeDisposable(this.communication) this.communication.onShouldSend(data => { this.process.send(data) }) const callback = message => { this.communication.parseMessage(message) } this.process.addListener('message', callback) this.subscriptions.add({ dispose: function() { process.removeListener('message', callback) } }) } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } kill(sig) { this.process.kill(sig) this.dispose() } dispose() { this.subscriptions.dispose() } } export {ProcessCommunication as Communication}
Add a the missing "blaze" runtime dependency
Package.describe({ summary: "Jade template language", version: "0.4.3_1", name: "mquandalle:jade", git: "https://github.com/mquandalle/meteor-jade.git", documentation: "../../README.md" }); Package.registerBuildPlugin({ name: "compileJade", use: [ "underscore@1.0.0", "htmljs@1.0.0", "minifiers@1.0.0", "spacebars-compiler@1.0.0", "mquandalle:jade-compiler@0.4.3" ], sources: [ "plugin/handler.js", ] }); Package.onUse(function (api) { api.use("blaze@2.0.0"); }); Package.onTest(function (api) { api.versionsFrom("METEOR@0.9.0"); api.use("tinytest"); api.use(["mquandalle:jade", "ui", "spacebars", "templating"]); api.addFiles([ "tests/match.jade", "tests/match.html", "tests/runtime.jade", "tests/body.tpl.jade", "tests/img_tag_here.tpl.jade" ]); api.addFiles(["tests/match.js", "tests/runtime.js"], "client"); });
Package.describe({ summary: "Jade template language", version: "0.4.3", name: "mquandalle:jade", git: "https://github.com/mquandalle/meteor-jade.git", documentation: "../../README.md" }); Package.registerBuildPlugin({ name: "compileJade", use: [ "underscore@1.0.0", "htmljs@1.0.0", "minifiers@1.0.0", "spacebars-compiler@1.0.0", "mquandalle:jade-compiler@0.4.3" ], sources: [ "plugin/handler.js", ] }); Package.onTest(function (api) { api.versionsFrom("METEOR@0.9.0"); api.use("tinytest"); api.use(["mquandalle:jade", "ui", "spacebars", "templating"]); api.addFiles([ "tests/match.jade", "tests/match.html", "tests/runtime.jade", "tests/body.tpl.jade", "tests/img_tag_here.tpl.jade" ]); api.addFiles(["tests/match.js", "tests/runtime.js"], "client"); });
Correct path to access to config file
<?php namespace Bogardo\Mailgun; use Illuminate\Support\ServiceProvider; class MailgunServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../../config/config.php' => config_path('mailgun.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app['mailgun'] = $this->app->share(function($app){ return new Mailgun($app['view']); }); $this->app->booting(function(){ $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias('Mailgun', 'Bogardo\Mailgun\Facades\Mailgun'); }); $this->mergeConfigFrom( __DIR__.'/../../config/config.php', 'mailgun' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('mailgun'); } }
<?php namespace Bogardo\Mailgun; use Illuminate\Support\ServiceProvider; class MailgunServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../config/config.php' => config_path('mailgun.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app['mailgun'] = $this->app->share(function($app){ return new Mailgun($app['view']); }); $this->app->booting(function(){ $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias('Mailgun', 'Bogardo\Mailgun\Facades\Mailgun'); }); $this->mergeConfigFrom( __DIR__.'/../config/config.php', 'mailgun' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('mailgun'); } }
[varLib.featureVars] Enable test now that it passes
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.varLib.featureVars import ( overlayFeatureVariations) def test_explosion(n = 10): conds = [] for i in range(n): end = i / n start = end - 1. region = [{'axis': (start, end)}] subst = {'g%.2g'%start: 'g%.2g'%end} conds.append((region, subst)) overlaps = overlayFeatureVariations(conds) assert len(overlaps) == 2 * n - 1, overlaps return conds, overlaps if __name__ == "__main__": import sys from pprint import pprint quiet = False args = {} if len(sys.argv) > 1: if sys.argv[1] == '-q': quiet = True del sys.argv[1] args['n'] = int(sys.argv[1]) input, output = test_explosion(**args) if quiet: print(len(output)) else: print("Input:") pprint(input) print() print("Output:") pprint(output)
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.varLib.featureVars import ( overlayFeatureVariations) def test_explosion(n = 10): conds = [] for i in range(n): end = i / n start = end - 1. region = [{'axis': (start, end)}] subst = {'g%.2g'%start: 'g%.2g'%end} conds.append((region, subst)) overlaps = overlayFeatureVariations(conds) # XXX Currently fails for n > 2! #assert len(overlaps) == 2 * n - 1, overlaps return conds, overlaps if __name__ == "__main__": import sys from pprint import pprint quiet = False args = {} if len(sys.argv) > 1: if sys.argv[1] == '-q': quiet = True del sys.argv[1] args['n'] = int(sys.argv[1]) input, output = test_explosion(**args) if quiet: print(len(output)) else: print("Input:") pprint(input) print() print("Output:") pprint(output)
Add `rejectUnknown` option to body parser. Defaults to `true`. Makes the behavior introduced in c7c7d4e33e19f5541d8e1e7ec5a06ba6cfb316ec optional, by explicitly setting `false`.
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.method !== 'POST' && req.method !== 'PUT') return next(); if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else if (options.rejectUnknown !== false) { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
// Copyright 2012 Mark Cavage, Inc. All rights reserved. var jsonParser = require('./json_body_parser'); var formParser = require('./form_body_parser'); var multipartParser = require('./multipart_parser'); var errors = require('../errors'); var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError; function bodyParser(options) { var parseForm = formParser(options); var parseJson = jsonParser(options); var parseMultipart = multipartParser(options); return function parseBody(req, res, next) { if (req.method !== 'POST' && req.method !== 'PUT') return next(); if (req.contentLength === 0 && !req.chunked) return next(); if (req.contentType === 'application/json') { return parseJson(req, res, next); } else if (req.contentType === 'application/x-www-form-urlencoded') { return parseForm(req, res, next); } else if (req.contentType === 'multipart/form-data') { return parseMultipart(req, res, next); } else { return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType)); } return next(); }; } module.exports = bodyParser;
Create a user if they don't exist
var hemera = require('./index'); var controller; /** * Every time a user posts a message, we update their slack profile so we can stay up to date on their profile * @param {Object} bot * @param {Object} message */ module.exports = function updateSlackProfile(bot, message) { controller = hemera.getController(); controller.storage.users.get(message.user, function(err, user) { if (err) { return console.error(err); } bot.api.users.info({user: message.user}, function(err, res) { if (err) { return console.error(err); } if (!user) { user = { id: message.user, }; } user.slackUser = res.user; controller.storage.users.save(user, function() {}); }); }); };
var hemera = require('./index'); var controller; /** * Every time a user posts a message, we update their slack profile so we can stay up to date on their profile * @param {Object} bot * @param {Object} message */ module.exports = function updateSlackProfile(bot, message) { controller = hemerga.getController(); controller.storage.users.get(message.user, function(err, user) { if (err) { return console.error(err); } bot.api.users.info({user: message.user}, function(err, res) { if (err) { return console.error(err); } user.slackUser = res.user; controller.storage.users.save(user, function() {}); }); }); };
Fix node crash (server is not defined) Probably a copy-paste error. The express server variable is called `app'.
var express = require('express'); var bodyParser = require('body-parser'); var redis = require('redis'); var swig = require('swig'); var app = express(); var client = redis.createClient(6379, "redis"); app.engine('html', swig.renderFile); app.set('view engine', 'html'); app.set('views', __dirname + '/view'); app.use(bodyParser.urlencoded({ extended: true })); app.get('/', function (req, res) { client.lrange('guestbook-node-messages', 0, -1, function (err, msgs) { if (err) { console.log(err); } res.render('list', { messages: msgs }) }); }); app.post('/post', function(req, res) { if (!req.body.msg) { res.redirect('/'); } client.rpush('guestbook-node-messages', req.body.msg, function (err) { if (err) { console.log(err); } res.redirect('/'); }); }); client.on("error", function (err) { console.log("Error " + err); }); process.on("SIGTERM", function () { client.quit(); app.close(function () { process.exit(0); }); }); app.listen(3000);
var express = require('express'); var bodyParser = require('body-parser'); var redis = require('redis'); var swig = require('swig'); var app = express(); var client = redis.createClient(6379, "redis"); app.engine('html', swig.renderFile); app.set('view engine', 'html'); app.set('views', __dirname + '/view'); app.use(bodyParser.urlencoded({ extended: true })); app.get('/', function (req, res) { client.lrange('guestbook-node-messages', 0, -1, function (err, msgs) { if (err) { console.log(err); } res.render('list', { messages: msgs }) }); }); app.post('/post', function(req, res) { if (!req.body.msg) { res.redirect('/'); } client.rpush('guestbook-node-messages', req.body.msg, function (err) { if (err) { console.log(err); } res.redirect('/'); }); }); client.on("error", function (err) { console.log("Error " + err); }); process.on("SIGTERM", function () { client.quit(); server.close(function () { process.exit(0); }); }); app.listen(3000);
Disable auto detect for highlight by default
'use strict'; module.exports = { // Site title: 'Hexo', subtitle: '', description: '', author: 'John Doe', language: '', timezone: '', // URL url: 'http://yoursite.com', root: '/', permalink: ':year/:month/:day/:title/', permalink_defaults: {}, // Directory source_dir: 'source', public_dir: 'public', tag_dir: 'tags', archive_dir: 'archives', category_dir: 'categories', code_dir: 'downloads/code', i18n_dir: ':lang', skip_render: [], // Writing new_post_name: ':title.md', default_layout: 'post', titlecase: false, external_link: true, filename_case: 0, render_drafts: false, post_asset_folder: false, relative_link: false, future: true, highlight: { enable: true, auto_detect: false, line_number: true, tab_replace: '' }, // Category & Tag default_category: 'uncategorized', category_map: {}, tag_map: {}, // Date / Time format date_format: 'YYYY-MM-DD', time_format: 'HH:mm:ss', // Pagination per_page: 10, pagination_dir: 'page', // Extensions theme: 'landscape', // Deployment deploy: {} };
'use strict'; module.exports = { // Site title: 'Hexo', subtitle: '', description: '', author: 'John Doe', language: '', timezone: '', // URL url: 'http://yoursite.com', root: '/', permalink: ':year/:month/:day/:title/', permalink_defaults: {}, // Directory source_dir: 'source', public_dir: 'public', tag_dir: 'tags', archive_dir: 'archives', category_dir: 'categories', code_dir: 'downloads/code', i18n_dir: ':lang', skip_render: [], // Writing new_post_name: ':title.md', default_layout: 'post', titlecase: false, external_link: true, filename_case: 0, render_drafts: false, post_asset_folder: false, relative_link: false, future: true, highlight: { enable: true, auto_detect: true, // Maintain consistent with previous version. line_number: true, tab_replace: '' }, // Category & Tag default_category: 'uncategorized', category_map: {}, tag_map: {}, // Date / Time format date_format: 'YYYY-MM-DD', time_format: 'HH:mm:ss', // Pagination per_page: 10, pagination_dir: 'page', // Extensions theme: 'landscape', // Deployment deploy: {} };
Improve the internalCallException to use Exception chaining
<?php namespace Napp\Core\Api\Exceptions\Exceptions; use Symfony\Component\HttpFoundation\Response; class ApiInternalCallException extends \RuntimeException { /** * @var Response */ protected $response; /** * @var string */ protected $exceptionMessage; /** * @var \Exception */ protected $previousException; /** * @param Response $response * @param string $message */ public function __construct(Response $response, $message = 'There was an error while processing your request') { $this->response = $response; $this->exceptionMessage = $message; $this->message = $message; $this->previousException = $response->exception; } /** * @return Response */ public function getResponse() { return $this->response; } /** * @return string */ public function getExceptionMessage() { return $this->exceptionMessage; } /** * @return \Exception */ public function getPreviousException() { return $this->previousException; } }
<?php namespace Napp\Core\Api\Exceptions\Exceptions; use Symfony\Component\HttpFoundation\Response; class ApiInternalCallException extends \RuntimeException { /** * @var Response */ protected $response; /** * @var string */ protected $exceptionMessage; /** * @param Response $response * @param string $message */ public function __construct(Response $response, $message = 'There was an error while processing your request') { $this->response = $response; $this->exceptionMessage = $message; } /** * @return Response */ public function getResponse() { return $this->response; } /** * @return string */ public function getExceptionMessage() { return $this->exceptionMessage; } }
Revert to old entry point.
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) # str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
#!/usr/bin/env python3 # Single entry point / dispatcher for simplified running of 'pman' import os from argparse import RawTextHelpFormatter from argparse import ArgumentParser str_desc = """ NAME docker-entrypoint.py SYNOPSIS docker-entrypoint.py [optional cmd args for pman] DESCRIPTION 'docker-entrypoint.py' is the main entrypoint for running the pman container. """ def pman_do(args, unknown): str_otherArgs = ' '.join(unknown) str_CMD = "/usr/local/bin/pman %s" % (str_otherArgs) str_CMD = "/usr/local/pman/bin/pman %s" % (str_otherArgs) return str_CMD parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--msg', action = 'store', dest = 'msg', default = '', help = 'JSON msg payload' ) args, unknown = parser.parse_known_args() if __name__ == '__main__': try: fname = 'pman_do(args, unknown)' str_cmd = eval(fname) print(str_cmd) os.system(str_cmd) except: print("Misunderstood container app... exiting.")
Change openerp --> odoo in hook.py
# -*- coding: utf-8 -*- # © 2017 Ecosoft (ecosoft.co.th). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import ast from odoo import api, SUPERUSER_ID def post_init_hook(cr, registry): """ Set value for is_order on old records """ cr.execute(""" update sale_order set is_order = true where state not in ('draft', 'cancel') """) def uninstall_hook(cr, registry): """ Restore sale.order action, remove context value """ with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) for action_id in ['sale.action_quotations', 'sale.action_orders']: action = env.ref(action_id) ctx = ast.literal_eval(action.context) del ctx['is_order'] dom = ast.literal_eval(action.domain) dom = [x for x in dom if x[0] != 'is_order'] action.write({'context': ctx, 'domain': dom})
# -*- coding: utf-8 -*- # © 2017 Ecosoft (ecosoft.co.th). # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import ast from openerp import api, SUPERUSER_ID def post_init_hook(cr, registry): """ Set value for is_order on old records """ cr.execute(""" update sale_order set is_order = true where state not in ('draft', 'cancel') """) def uninstall_hook(cr, registry): """ Restore sale.order action, remove context value """ with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) for action_id in ['sale.action_quotations', 'sale.action_orders']: action = env.ref(action_id) ctx = ast.literal_eval(action.context) del ctx['is_order'] dom = ast.literal_eval(action.domain) dom = [x for x in dom if x[0] != 'is_order'] action.write({'context': ctx, 'domain': dom})
Fix not injecting fallback rule for singular rules
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import java.util.List; import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.source.SourceSection; public class RuleFactory { public static Rule createRule(DynSemLanguage lang, SourceSection source, List<? extends Rule> rules, String arrowName, Class<?> dispatchClass) { CompilerAsserts.neverPartOfCompilation(); if (rules.size() == 0) { return new FallbackRule(lang, source, arrowName, dispatchClass); } else { Rule tail = createRule(lang, source, rules.subList(1, rules.size()), arrowName, dispatchClass); return new Rules(lang, source, rules.get(0), tail); } } }
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import java.util.List; import org.metaborg.meta.lang.dynsem.interpreter.DynSemLanguage; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.source.SourceSection; public class RuleFactory { public static Rule createRule(DynSemLanguage lang, SourceSection source, List<? extends Rule> rules, String arrowName, Class<?> dispatchClass) { CompilerAsserts.neverPartOfCompilation(); if (rules.size() == 0) { return new FallbackRule(lang, source, arrowName, dispatchClass); } else if (rules.size() == 1) { return rules.get(0); } else { Rule tail = createRule(lang, source, rules.subList(1, rules.size()), arrowName, dispatchClass); return new Rules(lang, source, rules.get(0), tail); } } }
Send app and router instance to template
<?php class PhpTemplate { protected $_dir = Null; protected $_data = Array(); public $app = Null; public $router = Null; public function __construct() { $this->_dir = '..'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR; $this->app = App::instance(); $this->router = Router::instance(); } public function render($__view, $data = Array()) { $content = $this->renderPartial($__view, $data); echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content)); } public function renderPartial($__view, $__data = Array()) { $this->_data = array_merge($__data, $this->_data); ob_start(); include($this->_dir.$__view.'.php'); $content = ob_get_contents(); ob_clean(); return $content; } public function __set($key, $value) { $this->_data[$key] = $value; } public function __get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : Null; } }
<?php class PhpTemplate { protected $_dir = Null; protected $_data = Array(); public function __construct() { $this->_dir = '..'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR; } public function render($__view, $data = Array()) { $content = $this->renderPartial($__view, $data); echo $this->renderPartial(App::instance()->config['default_layout'], array('content' => $content)); } public function renderPartial($__view, $__data = Array()) { $this->_data = array_merge($__data, $this->_data); ob_start(); include($this->_dir.$__view.'.php'); $content = ob_get_contents(); ob_clean(); return $content; } public function __set($key, $value) { $this->_data[$key] = $value; } public function __get($key) { return isset($this->_data[$key]) ? $this->_data[$key] : Null; } }
t285: Order language tree by key name
<?php class CM_Tree_Language extends CM_Tree_Abstract { protected $_rootId = '.'; /** * @param array|null $params */ public function __construct($params = null) { parent::__construct('CM_TreeNode_Language', $params); } protected function _load() { $result = CM_Mysql::select(TBL_CM_LANGUAGEKEY, 'name', 'name LIKE ".%"', 'name ASC'); while ($section = $result->fetchAssoc()) { $this->_addLanguageNode($section['name']); } } /** * @param string $languageKey * @throws CM_Exception_Invalid */ private function _addLanguageNode($languageKey) { if (!preg_match('#^(.*)\.([^\.]+)$#', $languageKey , $matches)) { throw new CM_Exception_Invalid('Invalid Language Key found: `' . $languageKey . '`'); } list($id, $parentId, $name) = $matches; if ($parentId && !array_key_exists($parentId, $this->_nodesTmp)) { $this->_addLanguageNode($parentId); } if (!$parentId) { $parentId = $this->_rootId; } parent::_addNode($id, $name, $parentId); } }
<?php class CM_Tree_Language extends CM_Tree_Abstract { protected $_rootId = '.'; /** * @param array|null $params */ public function __construct($params = null) { parent::__construct('CM_TreeNode_Language', $params); } protected function _load() { $result = CM_Mysql::select(TBL_CM_LANGUAGEKEY, 'name', 'name LIKE ".%"'); while ($section = $result->fetchAssoc()) { $this->_addLanguageNode($section['name']); } } /** * @param string $languageKey * @throws CM_Exception_Invalid */ private function _addLanguageNode($languageKey) { if (!preg_match('#^(.*)\.([^\.]+)$#', $languageKey , $matches)) { throw new CM_Exception_Invalid('Invalid Language Key found: `' . $languageKey . '`'); } list($id, $parentId, $name) = $matches; if ($parentId && !array_key_exists($parentId, $this->_nodesTmp)) { $this->_addLanguageNode($parentId); } if (!$parentId) { $parentId = $this->_rootId; } parent::_addNode($id, $name, $parentId); } }
Fix issue with base input class
import Component from '@glimmer/component'; import { action } from '@ember/object'; import { arg, string, bool } from 'ember-arg-types'; export default class FormControlsFfInputComponent extends Component { @arg(bool) live = false; @arg(bool) readonly = true; @arg(string) inputType = 'text'; @action handleClick(event) { if (this.args.onClick) { return this.args.onClick(event.target.value); } } @action handleFocus(event) { if (this.args.onFocus) { return this.args.onFocus(event.target.value); } } @action handleBlur(event) { if (this.args.onBlur) { return this.args.onBlur(event.target.value); } } @action handleKeyUp(event) { if (this.readonly) { event.preventDefault(); } if (this.live) { this.handleChange(event); } } @action handleKeyDown(event) { if (this.readonly) { event.preventDefault(); } } @action handleCut(event) { if (this.readonly) { event.preventDefault(); } } @action handleChange(event) { if (this.args.onChange) { return this.args.onChange(event.target.value); } } }
import Component from '@glimmer/component'; import { action } from '@ember/object'; import { arg, string, bool } from 'ember-arg-types'; export default class FormControlsFfInputComponent extends Component { @arg(bool) live = false; @arg(bool) readonly = true; @arg(string) inputType = true; @action handleClick(event) { if (this.args.onClick) { return this.args.onClick(event.target.value); } } @action handleFocus(event) { if (this.args.onFocus) { return this.args.onFocus(event.target.value); } } @action handleBlur(event) { if (this.args.onBlur) { return this.args.onBlur(event.target.value); } } @action handleKeyUp(event) { if (this.readonly) { event.preventDefault(); } if (this.live) { this.handleChange(event); } } @action handleKeyDown(event) { if (this.readonly) { event.preventDefault(); } } @action handleCut(event) { if (this.readonly) { event.preventDefault(); } } @action handleChange(event) { if (this.args.onChange) { return this.args.onChange(event.target.value); } } }
Change Escape:$sAllowTags to private + add missing phpdoc comment
<?php /** * @title Escape Exception Trait * @desc Escape the exception message. * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, 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/ Framework / Error / CException * @version 1.1 */ namespace PH7\Framework\Error\CException; defined('PH7') or exit('Restricted access'); trait Escape { /** @var string */ private $sAllowTags = '<br><i><em><b><strong><u>'; /** * Escape the exception message. * * @param string $sMsg */ protected function strip($sMsg) { $this->message = strip_tags($sMsg, $this->sAllowTags); } }
<?php /** * @title Escape Exception Trait * @desc Escape the exception message. * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, 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/ Framework / Error / CException * @version 1.1 */ namespace PH7\Framework\Error\CException; defined('PH7') or exit('Restricted access'); trait Escape { protected $sAllowTags = '<br><i><em><b><strong><u>'; /** * Escape the exception message. * * @param string $sMsg */ protected function strip($sMsg) { $this->message = strip_tags($sMsg, $this->sAllowTags); } }
Copy builded file to example/js/ on build
var gulp = require('gulp') var uglify = require('gulp-uglify') var rename = require('gulp-rename') var header = require('gulp-header') var ghPages = require('gulp-gh-pages') var pkg = require('./package.json') var banner = [ '/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' *', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @author <%= pkg.author %>', ' * @license <%= pkg.license %>', ' */', ''].join('\n') gulp.task('build', function () { return gulp.src('src/*') .pipe(uglify()) .pipe(header(banner, {pkg: pkg})) .pipe(rename('blooming-menu.min.js')) .pipe(gulp.dest('build')) .pipe(gulp.dest('example/js')) }) gulp.task('deploy:ghpages', function () { gulp .src('./build/blooming-menu.min.js') .pipe(gulp.dest('./example/js')) return gulp .src('./example/**/*') .pipe(ghPages()) })
var gulp = require('gulp') var uglify = require('gulp-uglify') var rename = require('gulp-rename') var header = require('gulp-header') var ghPages = require('gulp-gh-pages') var pkg = require('./package.json') var banner = [ '/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' *', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @author <%= pkg.author %>', ' * @license <%= pkg.license %>', ' */', ''].join('\n') gulp.task('build', function () { return gulp.src('src/*') .pipe(uglify()) .pipe(header(banner, {pkg: pkg})) .pipe(rename('blooming-menu.min.js')) .pipe(gulp.dest('build')) }) gulp.task('deploy:ghpages', function () { gulp .src('./build/blooming-menu.min.js') .pipe(gulp.dest('./example/js')) return gulp .src('./example/**/*') .pipe(ghPages()) })
Update the Dutch example test
# Dutch Language Test from seleniumbase.translate.dutch import Testgeval class MijnTestklasse(Testgeval): def test_voorbeeld_1(self): self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina") self.controleren_element('a[title*="hoofdpagina gaan"]') self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom") self.typ("#searchInput", "Stroopwafel") self.klik("#searchButton") self.controleren_tekst("Stroopwafel", "#firstHeading") self.controleren_element('img[src*="Stroopwafels"]') self.typ("#searchInput", "Rijksmuseum Amsterdam") self.klik("#searchButton") self.controleren_tekst("Rijksmuseum", "#firstHeading") self.controleren_element('img[src*="Rijksmuseum"]') self.terug() self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen()) self.vooruit() self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
# Dutch Language Test from seleniumbase.translate.dutch import Testgeval class MijnTestklasse(Testgeval): def test_voorbeeld_1(self): self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina") self.controleren_element('a[title*="hoofdpagina gaan"]') self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom") self.typ("#searchInput", "Stroopwafel") self.klik("#searchButton") self.controleren_tekst("Stroopwafel", "#firstHeading") self.controleren_element('img[alt="Stroopwafels"]') self.typ("#searchInput", "Rijksmuseum Amsterdam") self.klik("#searchButton") self.controleren_tekst("Rijksmuseum", "#firstHeading") self.controleren_element('img[alt="Het Rijksmuseum"]') self.terug() self.controleren_ware("Stroopwafel" in self.huidige_url_ophalen()) self.vooruit() self.controleren_ware("Rijksmuseum" in self.huidige_url_ophalen())
Add a sample of setParallaxOffset().
package me.yokeyword.sample.demo_wechat.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.View; import me.yokeyword.fragmentation_swipeback.SwipeBackFragment; import me.yokeyword.sample.R; /** * Created by YoKeyword on 16/2/7. */ public class BaseBackFragment extends SwipeBackFragment { private static final String TAG = "Fragmentation"; @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setParallaxOffset(0.5f); } protected void initToolbarNav(Toolbar toolbar) { toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _mActivity.onBackPressed(); } }); } }
package me.yokeyword.sample.demo_wechat.base; import android.support.v7.widget.Toolbar; import android.view.View; import me.yokeyword.fragmentation_swipeback.SwipeBackFragment; import me.yokeyword.sample.R; /** * Created by YoKeyword on 16/2/7. */ public class BaseBackFragment extends SwipeBackFragment { private static final String TAG = "Fragmentation"; protected void initToolbarNav(Toolbar toolbar) { toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _mActivity.onBackPressed(); } }); } }
Revert "remove name mangling to make testing easier" This reverts commit c0647badcab661e0ac6e0499c36868e516dcd2e6.
# -*- coding: utf-8 -*- class Heap(object): """Implements a heap data structure in Python. The underlying data structure used to hold the data is a list. """ __heap = [] def __init__(self, initial=None): """Creates a new heap. Args: initial: (Optional): A continguous list containing the data with which to initialize the new heap. """ if isinstance(initial, list) or isinstance(initial, tuple): self.__heap = initial elif initial is not None: raise TypeError( 'Illegal type submitted for heap data; use a list or tuple instead.') def __unicode__(self): if not self.__heap: return 'Empty' return 'Root: %s' % self.__heap[0]
# -*- coding: utf-8 -*- class Heap(object): """Implements a heap data structure in Python. The underlying data structure used to hold the data is a list. """ _heap = [] def __init__(self, initial=None): """Creates a new heap. Args: initial: (Optional): A continguous list containing the data with which to initialize the new heap. """ if isinstance(initial, list) or isinstance(initial, tuple): self._heap = initial elif initial is not None: raise TypeError( 'Illegal type submitted for heap data; use a list or tuple instead.') def __unicode__(self): if not self._heap: return 'Empty' return 'Root: %s' % self.__heap[0]
Change to rpio and add clean
import configparser import time import RPi.GPIO as GPIO from client import MumbleClient class InterCom: def __init__(self): config = configparser.ConfigParser() config.read('intercom.ini') self.mumble_client = MumbleClient(config['mumbleclient']) self.exit = False self.send_input = False if config['general']['gpiotype'] == 'BCM': GPIO.setmode(GPIO.BCM) self.button = int(config['general']['button']) GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def run(self): while not self.exit: if GPIO.input(self.button): self.mumble_client.send_input_audio() if __name__ == '__main__': try: InterCom().run() except Exception as e: raise e finally: GPIO.cleanup()
import configparser import time import RPIO as GPIO from client import MumbleClient class InterCom: def __init__(self): config = configparser.ConfigParser() config.read('intercom.ini') self.mumble_client = MumbleClient(config['mumbleclient']) self.exit = False self.send_input = False if config['general']['gpiotype'] == 'BCM': GPIO.setmode(GPIO.BCM) self.button = int(config['general']['button']) GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def run(self): while not self.exit: if GPIO.input(self.button): self.mumble_client.send_input_audio() if __name__ == '__main__': InterCom().run()
Use new octal syntax in comment
"use strict"; let platform = require('git-node-platform'); let jsGit = require('../.')(platform); let fsDb = require('git-fs-db')(platform); let fs = platform.fs; let run = require('gen-run'); // Create a filesystem backed bare repo let repo = jsGit(fsDb(fs("test.git"))); let mock = require('./mock.js'); run(function *() { yield repo.setBranch("master"); console.log("Git database Initialized"); let head; console.log(yield* map(mock.commits, function* (files, message) { return head = yield repo.saveAs("commit", { tree: yield repo.saveAs("tree", yield* map(files, function* (contents) { return { mode: 33188, // 0o100644, hash: yield repo.saveAs("blob", contents) }; })), parent: head, author: mock.author, committer: mock.committer, message: message }); })); yield repo.updateHead(head); console.log("Done"); }); function* map(object, onItem) { let obj = {}; for (let key in object) { let value = object[key]; obj[key] = yield* onItem(value, key); } return obj; }
"use strict"; let platform = require('git-node-platform'); let jsGit = require('../.')(platform); let fsDb = require('git-fs-db')(platform); let fs = platform.fs; let run = require('gen-run'); // Create a filesystem backed bare repo let repo = jsGit(fsDb(fs("test.git"))); let mock = require('./mock.js'); run(function *() { yield repo.setBranch("master"); console.log("Git database Initialized"); let head; console.log(yield* map(mock.commits, function* (files, message) { return head = yield repo.saveAs("commit", { tree: yield repo.saveAs("tree", yield* map(files, function* (contents) { return { mode: 33188, // 0100644, hash: yield repo.saveAs("blob", contents) }; })), parent: head, author: mock.author, committer: mock.committer, message: message }); })); yield repo.updateHead(head); console.log("Done"); }); function* map(object, onItem) { let obj = {}; for (let key in object) { let value = object[key]; obj[key] = yield* onItem(value, key); } return obj; }
fix: Return useful data from App creation
"""AWS Spinnaker Application.""" from pprint import pformat from foremast.app import base from foremast.utils import wait_for_task class SpinnakerApp(base.BaseApp): """Create AWS Spinnaker Application.""" provider = 'aws' def create(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config)) self.log.debug('App info:\n%s', pformat(self.appinfo)) jsondata = self.render_application_template() wait_for_task(jsondata) self.log.info("Successfully created %s application", self.appname) return jsondata def delete(self): """Delete AWS Spinnaker Application.""" return False def update(self): """Update AWS Spinnaker Application.""" return False
"""AWS Spinnaker Application.""" from pprint import pformat from foremast.app import base from foremast.utils import wait_for_task class SpinnakerApp(base.BaseApp): """Create AWS Spinnaker Application.""" provider = 'aws' def create(self): """Send a POST to spinnaker to create a new application with class variables. Raises: AssertionError: Application creation failed. """ self.appinfo['accounts'] = self.get_accounts() self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config)) self.log.debug('App info:\n%s', pformat(self.appinfo)) jsondata = self.render_application_template() wait_for_task(jsondata) self.log.info("Successfully created %s application", self.appname) return def delete(self): """Delete AWS Spinnaker Application.""" return False def update(self): """Update AWS Spinnaker Application.""" return False
Make login the default view Signed-off-by: Josua Grawitter <c028c213ed5efcf30c3f4fc7361dbde0c893c5b7@greyage.org>
<?php require_once('config.inc.php'); require_once('misc.inc.php'); require_once('db.inc.php'); require_once('html.inc.php'); date_default_timezone_set('Europe/Berlin'); setlocale(LC_TIME, 'de_DE'); session_start(); // Actual content generation: $db = new db(); switch ($_GET['view']) { case 'public': authenticate(VIEW_PUBLIC, 'index.php?view=public'); $source = new ovp_public($db); break; case 'print': authenticate(VIEW_PRINT, 'index.php?view=print'); if (isset($_GET['date'])) { $source = new ovp_print($db, $_GET['date']); } else { $source = new ovp_print($db); } break; case 'author': authenticate(VIEW_AUTHOR, 'index.php?view=author'); $source = new ovp_author($db); break; case 'admin': authenticate(VIEW_ADMIN, 'index.php?view=admin'); $source = new ovp_admin($db); break; case 'login': default: $source = new ovp_login($db); } $page = new ovp_page($source); exit($page->get_html()); ?>
<?php require_once('config.inc.php'); require_once('misc.inc.php'); require_once('db.inc.php'); require_once('html.inc.php'); date_default_timezone_set('Europe/Berlin'); setlocale(LC_TIME, 'de_DE'); session_start(); // Actual content generation: $db = new db(); switch ($_GET['view']) { case 'login': $source = new ovp_login($db); break; case 'print': authenticate(VIEW_PRINT, 'index.php?view=print'); if (isset($_GET['date'])) { $source = new ovp_print($db, $_GET['date']); } else { $source = new ovp_print($db); } break; case 'author': authenticate(VIEW_AUTHOR, 'index.php?view=author'); $source = new ovp_author($db); break; case 'admin': authenticate(VIEW_ADMIN, 'index.php?view=admin'); $source = new ovp_admin($db); break; case 'public': default: authenticate(VIEW_PUBLIC, 'index.php?view=public'); $source = new ovp_public($db); } $page = new ovp_page($source); exit($page->get_html()); ?>
Fix storage_access in the test config
from parsl.config import Config from parsl.data_provider.scheme import GlobusScheme from parsl.executors.threads import ThreadPoolExecutor from parsl.tests.utils import get_rundir # If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py # If you are a user copying-and-pasting this as an example, make sure to either # 1) create a local `user_opts.py`, or # 2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value # (i.e., user_opts['swan']['username'] -> 'your_username') from .user_opts import user_opts config = Config( executors=[ ThreadPoolExecutor( label='local_threads_globus', storage_access=[GlobusScheme( endpoint_uuid=user_opts['globus']['endpoint'], endpoint_path=user_opts['globus']['path'] )[, working_dir=user_opts['globus']['path'] ) ], run_dir=get_rundir() )
from parsl.config import Config from parsl.data_provider.scheme import GlobusScheme from parsl.executors.threads import ThreadPoolExecutor from parsl.tests.utils import get_rundir # If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py # If you are a user copying-and-pasting this as an example, make sure to either # 1) create a local `user_opts.py`, or # 2) delete the user_opts import below and replace all appearances of `user_opts` with the literal value # (i.e., user_opts['swan']['username'] -> 'your_username') from .user_opts import user_opts config = Config( executors=[ ThreadPoolExecutor( label='local_threads_globus', storage_access=GlobusScheme( endpoint_uuid=user_opts['globus']['endpoint'], endpoint_path=user_opts['globus']['path'] ), working_dir=user_opts['globus']['path'] ) ], run_dir=get_rundir() )
Reorder imports to satisfy ESLint. Part of STRIPES-100
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import { createLogger } from 'redux-logger'; import initialReducers from './initialReducers'; import enhanceReducer from './enhanceReducer'; import epics from './epics'; export default function configureStore(initialState, stripesLogger) { const logger = createLogger({ // Show logging unless explicitly set false predicate: () => stripesLogger.hasCategory('redux'), }); const reducer = enhanceReducer(combineReducers(initialReducers)); const middleware = applyMiddleware(thunk, logger, epics.middleware); /* eslint-disable no-underscore-dangle */ const createStoreWithMiddleware = compose( middleware, window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f, ); /* eslint-enable */ return createStoreWithMiddleware(createStore)(reducer, initialState, middleware); }
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import initialReducers from './initialReducers'; import enhanceReducer from './enhanceReducer'; import epics from './epics'; import { createLogger } from 'redux-logger'; export default function configureStore(initialState, stripesLogger) { const logger = createLogger({ // Show logging unless explicitly set false predicate: () => stripesLogger.hasCategory('redux'), }); const reducer = enhanceReducer(combineReducers(initialReducers)); const middleware = applyMiddleware(thunk, logger, epics.middleware); /* eslint-disable no-underscore-dangle */ const createStoreWithMiddleware = compose( middleware, window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f, ); /* eslint-enable */ return createStoreWithMiddleware(createStore)(reducer, initialState, middleware); }
Support either DOM elements or ids in dynamicEllipsis script
(function() { var ellipsisIntervals = {}; var tempId = 0; this.dynamicEllipsis = { start: function(elementOrId, durationBetween, maxEllipsis) { var elementId; var element; var text; var count = 0; var max = maxEllipsis || 5; var duration = durationBetween || 200; if (typeof elementOrId === 'string') { elementId = elementOrId; element = document.getElementById(elementId); } else { element = elementOrId; if (element.id) { elementId = element.id; } else { elementId = element.id = 'temp-' + tempId++; } } text = element.innerText; ellipsisIntervals[elementId] = setInterval(function() { var displayText = text; count++; if (count > max) count = 0; for (i = 0; i < count; i++) displayText += '.'; element.innerText = displayText; }, duration); }, stop: function(elementOrId) { var elementId = typeof elementOrId === 'string' ? elementOrId : elementOrId.id; clearInterval(ellipsisIntervals[elementId]); } }; }).call(window);
(function() { var ellipsisIntervals = {}; this.dynamicEllipsis = { start: function(elementId, durationBetween, maxEllipsis) { var element = document.getElementById(elementId); var text = element.innerText; var count = 0; var max = maxEllipsis || 5; var duration = durationBetween || 200; ellipsisIntervals[elementId] = setInterval(function() { var displayText = text; count++; if (count > max) count = 0; for (i = 0; i < count; i++) displayText += '.'; element.innerText = displayText; }, duration); }, stop: function(elementId) { clearInterval(ellipsisIntervals[elementId]); } }; }).call(window);