text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix import and tokenizer exceptions
# coding: utf-8 from __future__ import unicode_literals from ...language import Language from ...attrs import LANG from ...fr.stop_words import STOP_WORDS from ...fr.tokenizer_exceptions import TOKENIZER_EXCEPTIONS from ...language_data.punctuation import TOKENIZER_INFIXES, ALPHA from ...util import update_exc import pytest @pytest.fixture def fr_tokenizer_w_infix(): SPLIT_INFIX = r'(?<=[{a}]\')(?=[{a}])'.format(a=ALPHA) # create new Language subclass to add to default infixes class French(Language): lang = 'fr' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'fr' tokenizer_exceptions = update_exc(TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS infixes = TOKENIZER_INFIXES + [SPLIT_INFIX] return French.Defaults.create_tokenizer() @pytest.mark.parametrize('text,expected_tokens', [("l'avion", ["l'", "avion"]), ("j'ai", ["j'", "ai"])]) def test_issue768(fr_tokenizer_w_infix, text, expected_tokens): """Allow zero-width 'infix' token during the tokenization process.""" tokens = fr_tokenizer_w_infix(text) assert len(tokens) == 2 assert [t.text for t in tokens] == expected_tokens
# coding: utf-8 from __future__ import unicode_literals from ...language import Language from ...attrs import LANG from ...fr.language_data import get_tokenizer_exceptions, STOP_WORDS from ...language_data.punctuation import TOKENIZER_INFIXES, ALPHA import pytest @pytest.fixture def fr_tokenizer_w_infix(): SPLIT_INFIX = r'(?<=[{a}]\')(?=[{a}])'.format(a=ALPHA) # create new Language subclass to add to default infixes class French(Language): lang = 'fr' class Defaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: 'fr' tokenizer_exceptions = get_tokenizer_exceptions() stop_words = STOP_WORDS infixes = TOKENIZER_INFIXES + [SPLIT_INFIX] return French.Defaults.create_tokenizer() @pytest.mark.parametrize('text,expected_tokens', [("l'avion", ["l'", "avion"]), ("j'ai", ["j'", "ai"])]) def test_issue768(fr_tokenizer_w_infix, text, expected_tokens): """Allow zero-width 'infix' token during the tokenization process.""" tokens = fr_tokenizer_w_infix(text) assert len(tokens) == 2 assert [t.text for t in tokens] == expected_tokens
Improve error logging for ct
const logger = require('logger'); const ErrorSerializer = require('serializers/errorSerializer'); function init() { } function middleware(app, plugin) { app.use(async(ctx, next) => { try { await next(); } catch (error) { logger.error(error); ctx.status = error.status || 500; if (process.env.NODE_ENV === 'prod' && ctx.status === 500) { if (plugin.config.jsonAPIErrors) { ctx.response.type = 'application/vnd.api+json'; ctx.body = ErrorSerializer.serializeError(ctx.status, 'Unexpected error'); } else { ctx.body = 'Unexpected error'; } return; } if (plugin.config.jsonAPIErrors) { ctx.response.type = 'application/vnd.api+json'; ctx.body = ErrorSerializer.serializeError(ctx.status, error.message); return; } ctx.response.type = 'application/json'; ctx.body = { error: error.message, }; } }); } module.exports = { middleware, init, };
const logger = require('logger'); const ErrorSerializer = require('serializers/errorSerializer'); function init() { } function middleware(app, plugin) { app.use(async(ctx, next) => { try { await next(); } catch (error) { ctx.status = error.status || 500; if (process.env.NODE_ENV === 'prod' && ctx.status === 500) { if (plugin.config.jsonAPIErrors) { ctx.response.type = 'application/vnd.api+json'; ctx.body = ErrorSerializer.serializeError(ctx.status, 'Unexpected error'); return; } ctx.body = 'Unexpected error'; return; } if (plugin.config.jsonAPIErrors) { ctx.response.type = 'application/vnd.api+json'; ctx.body = ErrorSerializer.serializeError(ctx.status, error.message); return; } ctx.response.type = 'application/json'; if (process.env.NODE_ENV !== 'prod') { logger.error(error); } else if (ctx.status === 500) { ctx.body = 'Unexpected error'; return; } ctx.body = { error: error.message, }; } }); } module.exports = { middleware, init, };
Add header comment for class and change isMutating to true
package seedu.address.logic.commands; import javafx.collections.ObservableList; import seedu.address.commons.exceptions.InvalidUndoCommandException; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.undo.UndoManager; import seedu.address.model.datastructure.UndoPair; import seedu.address.model.label.Label; import seedu.address.model.task.ReadOnlyTask; //@@author A0162877N /** * Undo the most recent mutating command from the task manager, * returning the data to the previous state */ public class UndoCommand extends Command { public static final String COMMAND_WORD = "undo"; public static final String MESSAGE_SUCCESS = "Undo-ed previous command successfully!\n" + "To Redo past command, hit the up arrow key."; public static final String MESSAGE_USAGE = COMMAND_WORD; public static final String MESSAGE_UNSUCCESSFUL_UNDO = "No previous command to undo."; @Override public CommandResult execute() throws CommandException { assert model != null; try { if (!UndoManager.getInstance().isEmpty()) { UndoPair<ObservableList<ReadOnlyTask>, ObservableList<Label>> pair = UndoManager.getInstance().getUndoData(); model.undoPrevious(pair.getLeft(), pair.getRight()); return new CommandResult(String.format(MESSAGE_SUCCESS)); } else { throw new InvalidUndoCommandException(MESSAGE_UNSUCCESSFUL_UNDO); } } catch (InvalidUndoCommandException e) { throw new CommandException(e.getMessage()); } } @Override public boolean isMutating() { return true; } }
package seedu.address.logic.commands; import javafx.collections.ObservableList; import seedu.address.commons.exceptions.InvalidUndoCommandException; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.undo.UndoManager; import seedu.address.model.datastructure.UndoPair; import seedu.address.model.label.Label; import seedu.address.model.task.ReadOnlyTask; //@@author A0162877N public class UndoCommand extends Command { public static final String COMMAND_WORD = "undo"; public static final String MESSAGE_SUCCESS = "Undo-ed previous command successfully!\n" + "To Redo past command, hit the up arrow key."; public static final String MESSAGE_USAGE = COMMAND_WORD; public static final String MESSAGE_UNSUCCESSFUL_UNDO = "No previous command to undo."; @Override public CommandResult execute() throws CommandException { assert model != null; try { if (!UndoManager.getInstance().isEmpty()) { UndoPair<ObservableList<ReadOnlyTask>, ObservableList<Label>> pair = UndoManager.getInstance().getUndoData(); model.undoPrevious(pair.getLeft(), pair.getRight()); return new CommandResult(String.format(MESSAGE_SUCCESS)); } else { throw new InvalidUndoCommandException(MESSAGE_UNSUCCESSFUL_UNDO); } } catch (InvalidUndoCommandException e) { throw new CommandException(e.getMessage()); } } @Override public boolean isMutating() { return false; } }
build(webpack): Remove babel-polyfill from vendor bundle
/* eslint-disable global-require */ const path = require('path'); const CircularDependencyPlugin = require('circular-dependency-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const babelConfig = require('../../package.json').babel; module.exports = { entry: { app: path.join(__dirname, '../index.js'), vendor: [ 'lodash', ], }, module: { rules: [ { enforce: 'pre', test: /\.js$/, exclude: /node_modules/, use: { loader: 'eslint-loader', options: { quiet: true, }, }, }, { exclude: /node_modules/, test: /\.js$/, use: { loader: 'babel-loader', options: babelConfig, }, }, ], }, output: { filename: '[name].[chunkhash].bundle.js', path: path.resolve(__dirname, '../dist'), }, plugins: [ new CleanWebpackPlugin([ path.join(__dirname, '../dist'), ]), new HtmlWebpackPlugin({ appMountId: 'root', baseHref: '/', inject: false, title: 'dawww Testing', template: require('html-webpack-template'), }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', }), new webpack.optimize.CommonsChunkPlugin({ name: 'runtime', }), new CircularDependencyPlugin({ exclude: /node_modules/, failOnError: true, }), ], };
/* eslint-disable global-require */ const path = require('path'); const CircularDependencyPlugin = require('circular-dependency-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); const babelConfig = require('../../package.json').babel; module.exports = { entry: { app: path.join(__dirname, '../index.js'), vendor: [ 'babel-polyfill', 'lodash', ], }, module: { rules: [ { enforce: 'pre', test: /\.js$/, exclude: /node_modules/, use: { loader: 'eslint-loader', options: { quiet: true, }, }, }, { exclude: /node_modules/, test: /\.js$/, use: { loader: 'babel-loader', options: babelConfig, }, }, ], }, output: { filename: '[name].[chunkhash].bundle.js', path: path.resolve(__dirname, '../dist'), }, plugins: [ new CleanWebpackPlugin([ path.join(__dirname, '../dist'), ]), new HtmlWebpackPlugin({ appMountId: 'root', baseHref: '/', inject: false, title: 'dawww Testing', template: require('html-webpack-template'), }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', }), new webpack.optimize.CommonsChunkPlugin({ name: 'runtime', }), new CircularDependencyPlugin({ exclude: /node_modules/, failOnError: true, }), ], };
Check that request id can be null
package com.github.arteam.simplejsonrpc.core.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ValueNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Date: 07.06.14 * Time: 12:24 * <p>Representation of a JSON-RPC request</p> */ public class Request { @Nullable private final String jsonrpc; @Nullable private final String method; @NotNull private final JsonNode params; @Nullable private final ValueNode id; public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @NotNull JsonNode params, @JsonProperty("id") @Nullable ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Nullable public String getJsonrpc() { return jsonrpc; } @Nullable public String getMethod() { return method; } @NotNull public ValueNode getId() { return id != null ? id : NullNode.getInstance(); } @NotNull public JsonNode getParams() { return params; } @Override public String toString() { return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}"; } }
package com.github.arteam.simplejsonrpc.core.domain; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ValueNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Date: 07.06.14 * Time: 12:24 * <p>Representation of a JSON-RPC request</p> */ public class Request { @Nullable private final String jsonrpc; @Nullable private final String method; @NotNull private final JsonNode params; @NotNull private final ValueNode id; public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc, @JsonProperty("method") @Nullable String method, @JsonProperty("params") @NotNull JsonNode params, @JsonProperty("id") @NotNull ValueNode id) { this.jsonrpc = jsonrpc; this.method = method; this.id = id; this.params = params; } @Nullable public String getJsonrpc() { return jsonrpc; } @Nullable public String getMethod() { return method; } @NotNull public ValueNode getId() { return id; } @NotNull public JsonNode getParams() { return params; } @Override public String toString() { return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}"; } }
Remove method that maintain’s scroll parity Since we don’t anticipate placeholder textboxes ever scrolling in the future, this can be removed.
(function(Modules) { "use strict"; if ( !('oninput' in document.createElement('input')) ) return; const tagPattern = /\(\([^\)\(]+\)\)/g; Modules.HighlightTags = function() { this.start = function(textarea) { this.$textbox = $(textarea) .wrap(` <div class='textbox-highlight-wrapper' /> `) .after(this.$backgroundMaskForeground = $(` <div class="textbox-highlight-background" aria-hidden="true" /> <div class="textbox-highlight-mask" aria-hidden="true" /> <div class="textbox-highlight-foreground" aria-hidden="true" /> `)) .on("input", this.update); this.initialHeight = this.$textbox.height(); this.$backgroundMaskForeground.width( this.$textbox.width() ); this.$textbox .trigger("input"); }; this.resize = () => this.$textbox.height( Math.max( this.initialHeight, this.$backgroundMaskForeground.outerHeight() ) ); this.replacePlaceholders = () => this.$backgroundMaskForeground.html( $('<div/>').text(this.$textbox.val()).html().replace( tagPattern, match => `<span class='tag'>${match}</span>` ) ); this.update = () => ( this.replacePlaceholders() && this.resize() ); }; })(window.GOVUK.Modules);
(function(Modules) { "use strict"; if ( !('oninput' in document.createElement('input')) ) return; const tagPattern = /\(\([^\)\(]+\)\)/g; Modules.HighlightTags = function() { this.start = function(textarea) { this.$textbox = $(textarea) .wrap(` <div class='textbox-highlight-wrapper' /> `) .after(this.$backgroundMaskForeground = $(` <div class="textbox-highlight-background" aria-hidden="true" /> <div class="textbox-highlight-mask" aria-hidden="true" /> <div class="textbox-highlight-foreground" aria-hidden="true" /> `)) .on("input", this.update) .on("scroll", this.maintainScrollParity); this.initialHeight = this.$textbox.height(); this.$backgroundMaskForeground.width( this.$textbox.width() ); this.$textbox .trigger("input"); }; this.resize = () => this.$textbox.height( Math.max( this.initialHeight, this.$backgroundMaskForeground.outerHeight() ) ); this.replacePlaceholders = () => this.$backgroundMaskForeground.html( $('<div/>').text(this.$textbox.val()).html().replace( tagPattern, match => `<span class='tag'>${match}</span>` ) ) this.update = () => ( this.replacePlaceholders() && this.resize() ) this.maintainScrollParity = () => this.$backgroundMaskForeground.scrollTop( this.$textbox.scrollTop() ); }; })(window.GOVUK.Modules);
Fix context given to mailutils
from django.shortcuts import render, redirect from django.conf import settings from django.views import View from members.programmes import DEGREE_PROGRAMME_CHOICES from registration.forms import RegistrationForm from registration.mailutils import mailApplicantSubmission class BaseView(View): context = {'DEBUG': settings.DEBUG} class HomeView(BaseView): template = 'registration.html' def get(self, request): self.context['programmes'] = DEGREE_PROGRAMME_CHOICES self.context['form'] = RegistrationForm() return render(request, self.template, self.context) class SubmitView(BaseView): template = 'submit.html' def get(self, request, **kwargs): previous_context = request.session.pop('context', None) if not previous_context: return redirect('registration.views.home') return render(request, self.template, previous_context) def post(self, request): form = RegistrationForm(request.POST) if form.is_valid(): registration = form.instance next_context = { 'name': registration.preferred_name or registration.given_names.split(' ')[0], 'email': registration.email, } # FIXME: handle situation where email is not sent (e.g. admin log tool) mailApplicantSubmission(next_context) registration.save() request.session['context'] = next_context return redirect('registration.views.submit') else: self.context['form'] = form return render(request, HomeView.template, self.context, status=400)
from django.shortcuts import render, redirect from django.conf import settings from django.views import View from members.programmes import DEGREE_PROGRAMME_CHOICES from registration.forms import RegistrationForm from registration.mailutils import mailApplicantSubmission class BaseView(View): context = {'DEBUG': settings.DEBUG} class HomeView(BaseView): template = 'registration.html' def get(self, request): self.context['programmes'] = DEGREE_PROGRAMME_CHOICES self.context['form'] = RegistrationForm() return render(request, self.template, self.context) class SubmitView(BaseView): template = 'submit.html' def get(self, request, **kwargs): previous_context = request.session.pop('context', None) if not previous_context: return redirect('registration.views.home') return render(request, self.template, previous_context) def post(self, request): form = RegistrationForm(request.POST) if form.is_valid(): registration = form.instance next_context = { 'name': registration.preferred_name or registration.given_names.split(' ')[0], 'email': registration.email, } # FIXME: handle situation where email is not sent (e.g. admin log tool) mailApplicantSubmission(self.context) registration.save() request.session['context'] = next_context return redirect('registration.views.submit') else: self.context['form'] = form return render(request, HomeView.template, self.context, status=400)
Enable service search filter tests
describe('Service Search Filters', function () { context('Filters services table', function () { beforeEach(function () { cy.configureCluster({ mesos: '1-for-each-health', nodeHealth: true }); cy.visitUrl({url: '/services'}); }); it('filters correctly on search string', function () { cy.get('tbody tr').should('to.have.length', 6); cy.get('.filter-input-text').as('filterInputText'); cy.get('@filterInputText').type('unhealthy'); cy.get('tbody tr').should('to.have.length', 3); }); it('sets the correct search string filter query params', function () { cy.get('.filter-input-text').as('filterInputText'); cy.get('@filterInputText').type('cassandra-healthy'); cy.location().its('href').should(function (href) { var queries = href.split('?')[1]; expect(decodeURIComponent(queries)) .to.equal('searchString=cassandra-healthy'); }); }); it('will clear filters by clear all link click', function () { cy.get('.filter-input-text').as('filterInputText'); cy.get('@filterInputText').type('cassandra-healthy'); cy.get('.h4.clickable .small').click(); cy.location().its('href').should(function (href) { var queries = href.split('?')[1]; expect(queries).to.equal(undefined); }); cy.get('tbody tr').should('to.have.length', 6); }); }); });
xdescribe('Service Search Filters', function () { context('Filters services table', function () { beforeEach(function () { cy.configureCluster({ mesos: '1-for-each-health', nodeHealth: true }); cy.visitUrl({url: '/services'}); }); it('filters correctly on search string', function () { cy.get('tbody tr').should('to.have.length', 6); cy.get('.filter-input-text').as('filterInputText'); cy.get('@filterInputText').type('unhealthy'); cy.get('tbody tr').should('to.have.length', 3); }); it('sets the correct search string filter query params', function () { cy.get('.filter-input-text').as('filterInputText'); cy.get('@filterInputText').type('cassandra-healthy'); cy.location().its('href').should(function (href) { var queries = href.split('?')[1]; expect(decodeURIComponent(queries)) .to.equal('searchString=cassandra-healthy'); }); }); it('will clear filters by clear all link click', function () { cy.get('.filter-input-text').as('filterInputText'); cy.get('@filterInputText').type('cassandra-healthy'); cy.get('.h4.clickable .small').click(); cy.location().its('href').should(function (href) { var queries = href.split('?')[1]; expect(queries).to.equal(undefined); }); cy.get('tbody tr').should('to.have.length', 6); }); }); });
UI: Convert users page to LightComponent
import React from "react"; import { AppMenu } from "ui-components/app_menu"; import LightComponent from "ui-lib/light_component"; class Page extends LightComponent { render() { this.log("render", this.props, this.state); const pathname = this.getPathname(); const items = this.props.route.childRoutes.map((route) => { const pn = `${pathname}/${route.path}`; const active = this.context.router.location.pathname.startsWith(pn); return { label: route.label, pathname: pn, active: active }; }); return ( <div> <AppMenu primaryText="Collaborators" icon="group" items={items} /> <div className={this.props.theme.content}> {this.props.children && React.cloneElement(this.props.children, { theme: this.props.theme })} </div> </div> ); } } Page.propTypes = { theme: React.PropTypes.object, children: React.PropTypes.node, route: React.PropTypes.object.isRequired }; Page.contextTypes = { router: React.PropTypes.object.isRequired }; export default Page;
import React from "react"; import { AppMenu } from "ui-components/app_menu"; import Component from "ui-lib/component"; class Page extends Component { constructor(props) { super(props, true); } render() { this.log("render", this.props, this.state); const pathname = this.getPathname(); const items = this.props.route.childRoutes.map((route) => { const pn = `${pathname}/${route.path}`; const active = this.context.router.location.pathname.startsWith(pn); return { label: route.label, pathname: pn, active: active }; }); return ( <div> <AppMenu primaryText="Collaborators" icon="group" items={items} /> <div className={this.props.theme.content}> {this.props.children && React.cloneElement(this.props.children, { theme: this.props.theme })} </div> </div> ); } } Page.propTypes = { theme: React.PropTypes.object, children: React.PropTypes.node, route: React.PropTypes.object.isRequired }; Page.contextTypes = { router: React.PropTypes.object.isRequired }; export default Page;
Remove card on home page
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; // import Img from './Img'; // import Headshot from './headshot.png'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="page-header"> <h1><FormattedMessage {...messages.name} /> <small><FormattedMessage {...messages.title} /></small></h1> <FormattedMessage {...messages.header} /> </div> </div> </div> {/* <div className="row"> <div className="col-xs-12"> <div className="panel panel-primary"> <div className="panel-body"> <FormattedMessage {...messages.header} /> </div> </div> </div> </div> */} </div> ); } }
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; // import Img from './Img'; // import Headshot from './headshot.png'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="container"> <div className="row"> <div className="col-xs-12"> <div className="page-header"> <h1><FormattedMessage {...messages.name} /> <small><FormattedMessage {...messages.title} /></small></h1> <FormattedMessage {...messages.header} /> </div> </div> </div> <div className="row"> <div className="col-xs-12"> <div className="panel panel-primary"> <div className="panel-body"> <FormattedMessage {...messages.header} /> </div> </div> </div> </div> </div> ); } }
Fix logic for determining if a header decorator is empty
package ca.antonious.viewcelladapter.decorators; import ca.antonious.viewcelladapter.AbstractSection; import ca.antonious.viewcelladapter.AbstractViewCell; import ca.antonious.viewcelladapter.decorators.SectionDecorator; /** * Created by George on 2016-12-17. */ public class HeaderSectionDecorator extends SectionDecorator { private AbstractViewCell headerViewCell; private boolean showHeaderIfEmpty = true; public HeaderSectionDecorator(AbstractSection decoratedSection, AbstractViewCell headerViewCell) { super(decoratedSection); this.headerViewCell = headerViewCell; } @Override public AbstractViewCell get(int position) { if (position == 0) { return headerViewCell; } return getDecoratedSection().get(position - 1); } @Override public void remove(int position) { getDecoratedSection().remove(position - 1); } @Override public int getItemCount() { if (isSectionEmpty()) { return 0; } return getDecoratedSection().getItemCount() + 1; } public boolean shouldShowHeaderIfEmpty() { return showHeaderIfEmpty; } public void setShowHeaderIfEmpty(boolean showHeaderIfEmpty) { this.showHeaderIfEmpty = showHeaderIfEmpty; } private boolean isSectionEmpty() { return getDecoratedSection().isEmpty() && !shouldShowHeaderIfEmpty(); } }
package ca.antonious.viewcelladapter.decorators; import ca.antonious.viewcelladapter.AbstractSection; import ca.antonious.viewcelladapter.AbstractViewCell; import ca.antonious.viewcelladapter.decorators.SectionDecorator; /** * Created by George on 2016-12-17. */ public class HeaderSectionDecorator extends SectionDecorator { private AbstractViewCell headerViewCell; private boolean showHeaderIfEmpty = true; public HeaderSectionDecorator(AbstractSection decoratedSection, AbstractViewCell headerViewCell) { super(decoratedSection); this.headerViewCell = headerViewCell; } @Override public AbstractViewCell get(int position) { if (position == 0) { return headerViewCell; } return getDecoratedSection().get(position - 1); } @Override public void remove(int position) { getDecoratedSection().remove(position - 1); } @Override public int getItemCount() { if (isSectionEmpty()) { return 0; } return getDecoratedSection().getItemCount() + 1; } public boolean shouldShowHeaderIfEmpty() { return showHeaderIfEmpty; } public void setShowHeaderIfEmpty(boolean showHeaderIfEmpty) { this.showHeaderIfEmpty = showHeaderIfEmpty; } private boolean isSectionEmpty() { int count = getDecoratedSection().getItemCount(); return count == 0 || (count == 1 && !showHeaderIfEmpty); } }
Use base64 strings instead of byte arrays
package com.reactlibrary; import android.util.Base64; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import org.tensorflow.Graph; public class RNTensorflowGraphModule extends ReactContextBaseJavaModule { private Graph graph; public RNTensorflowGraphModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "TensorflowGraph"; } @ReactMethod public void init(Graph graph) { this.graph = graph; } @ReactMethod public void importGraphDef(String graphDef) { this.graph.importGraphDef(Base64.decode(graphDef, Base64.DEFAULT)); } @ReactMethod public void importGraphDef(String graphDef, String prefix) { this.graph.importGraphDef(Base64.decode(graphDef, Base64.DEFAULT), prefix); } @ReactMethod public void toGraphDef(Promise promise) { try { promise.resolve(Base64.encodeToString(this.graph.toGraphDef(), Base64.DEFAULT)); } catch (Exception e) { promise.resolve(e); } } @ReactMethod public void operation(String name, Promise promise) { try { promise.resolve(this.graph.operation(name)); } catch (Exception e) { promise.resolve(e); } } @ReactMethod public void close(Graph graph) { this.graph.close(); } }
package com.reactlibrary; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import org.tensorflow.Graph; public class RNTensorflowGraphModule extends ReactContextBaseJavaModule { private Graph graph; public RNTensorflowGraphModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "TensorflowGraph"; } @ReactMethod public void init(Graph graph) { this.graph = graph; } @ReactMethod public void importGraphDef(byte[] graphDef) { this.graph.importGraphDef(graphDef); } @ReactMethod public void importGraphDef(byte[] graphDef, String prefix) { this.graph.importGraphDef(graphDef, prefix); } @ReactMethod public void toGraphDef(Promise promise) { try { promise.resolve(this.graph.toGraphDef()); } catch (Exception e) { promise.resolve(e); } } @ReactMethod public void operation(String name, Promise promise) { try { promise.resolve(this.graph.operation(name)); } catch (Exception e) { promise.resolve(e); } } @ReactMethod public void close(Graph graph) { this.graph.close(); } }
Move filter and set fixed precision
var ds18b20 = require('../services/ds18b20.js'); var logger = require('../services/logger.js'); var _ = require('lodash'); var sensors; var config; var init = function (cfg) { config = cfg || {}; logger.init(config); }; var run = function () { if (!config) { console.log('MONITOR', 'No configuration present'); return; } config.sensors.forEach(function (sensor) { if (!sensor.isActive) return; if (sensor.type == 'temperature') { ds18b20.read(sensor) .then(function (result) { logger.log('MONITOR\tREADING\t' + result.sensor.displayName + '\t' + result.reading.F.toFixed(2) + '°F'); if (result.sensor.allowedRange) { if (result.reading.F < result.sensor.allowedRange.low || result.reading.F > result.sensor.allowedRange.high) { logger.warn(result.sensor.displayName + ' is out of allowed range: ' + result.reading.F.toFixed(2) + '°F'); } } }) .catch(function (error) { logger.error('MONITOR\tERROR\t' + error); }); } }); }; exports.init = init; exports.run = run;
var ds18b20 = require('../services/ds18b20.js'); var logger = require('../services/logger.js'); var _ = require('lodash'); var sensors; var config; var init = function (cfg) { config = cfg || {}; sensors = _.filter(config.sensors, function (sensor) { return sensor.isActive; }); logger.init(config); }; var run = function () { if (!config) { console.log('MONITOR', 'No configuration present'); return; } sensors.forEach(function (sensor) { if (sensor.type == 'temperature') { ds18b20.read(sensor) .then(function (result) { logger.log('MONITOR\tREADING\t' + result.sensor.displayName + '\t' + result.reading.F + '°F'); if (result.sensor.allowedRange) { if (result.reading.F < result.sensor.allowedRange.low || result.reading.F > result.sensor.allowedRange.high) { logger.warn(result.sensor.displayName + ' is out of allowed range: ' + result.reading.F + '°F'); } } }) .catch(function (error) { logger.error('MONITOR\tERROR\t' + error); }); } }); }; exports.init = init; exports.run = run;
Remove unused lodash.find reference in duplicateProperty
'use strict'; var path = require('path'); module.exports = function (options) { var filename = path.basename(options.path); var config = options.config; var node = options.node; var properties = []; var errors = []; // Bail if the linter isn't wanted if (config.duplicateProperty && !config.duplicateProperty.enabled) { return null; } // Not applicable, bail if (node.type !== 'block') { return null; } node.forEach('declaration', function (declaration) { var property = declaration.first('property').content[0]; if (property && property.type !== 'ident') { return; } if (properties.indexOf(property.content) !== -1) { errors.push({ message: 'Duplicate property: "' + property.content + '".', column: property.start.column, line: property.start.line }); } properties.push(property.content); }); if (errors.length) { return errors.map(function (error) { return { column: error.column, file: filename, line: error.line, linter: 'duplicateProperty', message: error.message }; }); } return true; };
'use strict'; var find = require('lodash.find'); var path = require('path'); module.exports = function (options) { var filename = path.basename(options.path); var config = options.config; var node = options.node; var properties = []; var errors = []; // Bail if the linter isn't wanted if (config.duplicateProperty && !config.duplicateProperty.enabled) { return null; } // Not applicable, bail if (node.type !== 'block') { return null; } node.forEach('declaration', function (declaration) { var property = declaration.first('property').content[0]; if (property && property.type !== 'ident') { return; } if (properties.indexOf(property.content) !== -1) { errors.push({ message: 'Duplicate property: "' + property.content + '".', column: property.start.column, line: property.start.line }); } properties.push(property.content); }); if (errors.length) { return errors.map(function (error) { return { column: error.column, file: filename, line: error.line, linter: 'duplicateProperty', message: error.message }; }); } return true; };
Make sure Catalysis benchmark sets up between each iteration Probably why it was so erratic.
package etomica.simulation; import etomica.modules.catalysis.Catalysis; import etomica.space3d.Space3D; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; @State(Scope.Benchmark) @Fork(1) public class BenchSimCatalysis { private Catalysis sim; @Param("20") private int nCellsZ; @Setup(Level.Iteration) public void setup() { sim = new Catalysis(Space3D.getInstance(), nCellsZ); sim.integrator.reset(); } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Warmup(time = 3, iterations = 5) @Measurement(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 3) public long integratorStep() { sim.integrator.doStep(); return sim.integrator.getStepCount(); } public static void main(String[] args) throws RunnerException { Options opts = new OptionsBuilder() .include(BenchSimCatalysis.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opts).run(); } }
package etomica.simulation; import etomica.modules.catalysis.Catalysis; import etomica.space3d.Space3D; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; @State(Scope.Benchmark) @Fork(1) public class BenchSimCatalysis { private Catalysis sim; @Param("20") private int nCellsZ; @Setup public void setup() { sim = new Catalysis(Space3D.getInstance(), nCellsZ); sim.integrator.reset(); } @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Warmup(time = 3, iterations = 5) @Measurement(time = 10, timeUnit = TimeUnit.SECONDS, iterations = 3) public long integratorStep() { sim.integrator.doStep(); return sim.integrator.getStepCount(); } public static void main(String[] args) throws RunnerException { Options opts = new OptionsBuilder() .include(BenchSimCatalysis.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opts).run(); } }
Remove unused moa exception class.
''' * when dispatching events, returning True stops it. ''' __all__ = ('MoaBase', ) from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. '''
''' * when dispatching events, returning True stops it. ''' from weakref import ref from kivy.event import EventDispatcher from kivy.properties import StringProperty, OptionProperty, ObjectProperty import logging class MoaException(Exception): pass class MoaBase(EventDispatcher): named_moas = {} ''' A weakref.ref to the named moa instances. Read only. ''' _last_name = '' def __init__(self, **kwargs): super(MoaBase, self).__init__(**kwargs) def verfiy_name(instance, value): named_moas = MoaBase.named_moas old_name = self._last_name if value == old_name: return if old_name: del named_moas[old_name] if value: if value in named_moas and named_moas[value]() is not None: raise ValueError('Moa instance with name {} already ' 'exists: {}'.format(value, named_moas[value]())) else: named_moas[value] = ref(self) self._last_name = value self.bind(name=verfiy_name) verfiy_name(self, self.name) name = StringProperty('') ''' Unique name across all Moa objects ''' logger = ObjectProperty(logging.getLogger('moa'), baseclass=logging.Logger) source = StringProperty('') ''' E.g. a filename to load that interpreted by the subclass. '''
Fix order cancellation in FIX gateway All orders do not have an OrigClOrdID(41). Thanks to Pekka Enberg for reporting the failure.
package com.paritytrading.parity.fix; import java.util.ArrayList; import java.util.List; class Orders { private List<Order> orders; public Orders() { orders = new ArrayList<>(); } public void add(Order order) { orders.add(order); } public Order findByClOrdID(String clOrdId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (clOrdId.equals(order.getClOrdID())) return order; } return null; } public Order findByOrigClOrdID(String origClOrdId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (origClOrdId.equals(order.getOrigClOrdID())) return order; } return null; } public Order findByOrderEntryID(String orderEntryId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (orderEntryId.equals(order.getOrderEntryID())) return order; } return null; } public void removeByOrderEntryID(String orderEntryId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (orderEntryId.equals(order.getOrderEntryID())) { orders.remove(i); break; } } } }
package com.paritytrading.parity.fix; import java.util.ArrayList; import java.util.List; class Orders { private List<Order> orders; public Orders() { orders = new ArrayList<>(); } public void add(Order order) { orders.add(order); } public Order findByClOrdID(String clOrdId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (order.getClOrdID().equals(clOrdId)) return order; } return null; } public Order findByOrigClOrdID(String origClOrdId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (order.getOrigClOrdID().equals(origClOrdId)) return order; } return null; } public Order findByOrderEntryID(String orderEntryId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (order.getOrderEntryID().equals(orderEntryId)) return order; } return null; } public void removeByOrderEntryID(String orderEntryId) { for (int i = 0; i < orders.size(); i++) { Order order = orders.get(i); if (order.getOrderEntryID().equals(orderEntryId)) { orders.remove(i); break; } } } }
Add .dev to version name in about dialog
package fr.masciulli.drinks.fragment; import android.app.AlertDialog; import android.app.Dialog; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import fr.masciulli.drinks.BuildConfig; import fr.masciulli.drinks.R; public class AboutDialogFragment extends DialogFragment { @InjectView(R.id.version_name) TextView mVersionNameView; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = getActivity().getLayoutInflater(); View root = inflater.inflate(R.layout.dialog_about, null); ButterKnife.inject(this, root); try { PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); String versionNameText = pInfo.versionName; if (BuildConfig.DEBUG) { versionNameText += ".dev"; } mVersionNameView.setText(versionNameText); } catch (PackageManager.NameNotFoundException e) { mVersionNameView.setText(getString(R.string.unknown_version)); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(root); return builder.create(); } @OnClick(R.id.ok) void dismissDialog() { dismiss(); } }
package fr.masciulli.drinks.fragment; import android.app.AlertDialog; import android.app.Dialog; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import fr.masciulli.drinks.R; public class AboutDialogFragment extends DialogFragment { @InjectView(R.id.version_name) TextView mVersionNameView; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = getActivity().getLayoutInflater(); View root = inflater.inflate(R.layout.dialog_about, null); ButterKnife.inject(this, root); try { PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); mVersionNameView.setText(pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { mVersionNameView.setText(getString(R.string.unknown_version)); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(root); return builder.create(); } @OnClick(R.id.ok) void dismissDialog() { dismiss(); } }
Add space at end of error message
package com.jstanier; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.googlecode.jcsv.CSVStrategy; import com.googlecode.jcsv.reader.CSVReader; import com.googlecode.jcsv.reader.internal.CSVReaderBuilder; @Component public class InputParser { @Autowired private InputReader inputReader; public List<TweetToSchedule> parseInput(String pathToCsvFile) { return parseCsvFile(pathToCsvFile); } private List<TweetToSchedule> parseCsvFile(String pathToCsvFile) { List<TweetToSchedule> csvData = null; try { Reader reader = inputReader.getInputReader(pathToCsvFile); CSVReader<TweetToSchedule> csvParser = new CSVReaderBuilder(reader) .strategy(CSVStrategy.UK_DEFAULT) .entryParser(new TweetToScheduleEntryParser()).build(); csvData = csvParser.readAll(); } catch (FileNotFoundException e) { exitWithError("File not found at " + pathToCsvFile); } catch (IOException e) { exitWithError("IO exception when reading " + pathToCsvFile); } return csvData; } private void exitWithError(String error) { System.err.println(error); System.exit(1); } }
package com.jstanier; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.googlecode.jcsv.CSVStrategy; import com.googlecode.jcsv.reader.CSVReader; import com.googlecode.jcsv.reader.internal.CSVReaderBuilder; @Component public class InputParser { @Autowired private InputReader inputReader; public List<TweetToSchedule> parseInput(String pathToCsvFile) { return parseCsvFile(pathToCsvFile); } private List<TweetToSchedule> parseCsvFile(String pathToCsvFile) { List<TweetToSchedule> csvData = null; try { Reader reader = inputReader.getInputReader(pathToCsvFile); CSVReader<TweetToSchedule> csvParser = new CSVReaderBuilder(reader) .strategy(CSVStrategy.UK_DEFAULT) .entryParser(new TweetToScheduleEntryParser()).build(); csvData = csvParser.readAll(); } catch (FileNotFoundException e) { exitWithError("File not found at " + pathToCsvFile); } catch (IOException e) { exitWithError("IO exception when reading" + pathToCsvFile); } return csvData; } private void exitWithError(String error) { System.err.println(error); System.exit(1); } }
Add null check on help generation
import Plugin from "./Plugin"; export default class MasterPlugin extends Plugin { static get plugin() { return { name: "MasterPlugin", description: "", help: "This plugin has access to PluginManager and will perform all the 'meta'/'super' actions.", type: Plugin.Type.SPECIAL, visibility: Plugin.Visibility.HIDDEN, needs: { database: true, utils: true } }; } constructor(listener, pluginManager) { super(listener); this.pluginManager = pluginManager; } onCommand({message, command, args}, reply) { if (command !== "help") return; const data = this.pluginManager.plugins .map(pl => pl.plugin) .filter(pl => pl.visibility !== Plugin.Visibility.HIDDEN); if (args.length === 0) { reply({ type: "text", text: data .map(pl => `*${pl.name}*: ${pl.description}`) .join("\n"), options: { parse_mode: "markdown", disable_web_page_preview: true } }); } else { const pluginName = args[0].toLowerCase(); const plugin = data .filter(pl => pl.name.toLowerCase() === pluginName)[0]; if (plugin) { reply({ type: "text", text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`, options: { parse_mode: "markdown", disable_web_page_preview: true } }); } } } }
import Plugin from "./Plugin"; export default class MasterPlugin extends Plugin { static get plugin() { return { name: "MasterPlugin", description: "", help: "This plugin has access to PluginManager and will perform all the 'meta'/'super' actions.", type: Plugin.Type.SPECIAL, visibility: Plugin.Visibility.HIDDEN, needs: { database: true, utils: true } }; } constructor(listener, pluginManager) { super(listener); this.pluginManager = pluginManager; } onCommand({message, command, args}, reply) { if (command !== "help") return; const data = this.pluginManager.plugins .map(pl => pl.plugin) .filter(pl => pl.visibility !== Plugin.Visibility.HIDDEN); if (args.length === 0) { reply({ type: "text", text: data .map(pl => `*${pl.name}*: ${pl.description}`) .join("\n"), options: { parse_mode: "markdown", disable_web_page_preview: true } }); } else { const pluginName = args[0].toLowerCase(); const plugin = data .filter(pl => pl.name.toLowerCase() === pluginName)[0]; reply({ type: "text", text: `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`, options: { parse_mode: "markdown", disable_web_page_preview: true } }); } } }
Add monitoring logo in form
# -*- coding: utf-8 -*- from atom.ext.crispy_forms.forms import FormHorizontalMixin, SingleButtonMixin from braces.forms import UserKwargModelFormMixin from dal import autocomplete from django import forms from tinymce.widgets import TinyMCE from django.utils.translation import ugettext_lazy as _ from ..institutions.models import Institution from .models import Monitoring from .utils import M2MFieldFormMixin class MonitoringForm(UserKwargModelFormMixin, FormHorizontalMixin, SingleButtonMixin, M2MFieldFormMixin, forms.ModelForm): institutions = forms.ModelMultipleChoiceField(queryset=Institution.objects.all(), label=_("Institutions"), required=False, widget=autocomplete.ModelSelect2Multiple(url='institutions:autocomplete')) def __init__(self, *args, **kwargs): super(MonitoringForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['institutions'].initial = self.instance.institutions.all() if not self.instance.user_id: self.instance.user = self.user def save(self, *args, **kwargs): super(MonitoringForm, self).save(*args, **kwargs) self.save_m2m_field(field='institutions', left='monitoring', right='institution') return self.instance class Meta: model = Monitoring fields = ['name', 'logo', 'description', 'active', 'max_point', ] widgets = { 'description': TinyMCE(attrs={'cols': 80, 'rows': 30}), }
# -*- coding: utf-8 -*- from atom.ext.crispy_forms.forms import FormHorizontalMixin, SingleButtonMixin from braces.forms import UserKwargModelFormMixin from dal import autocomplete from django import forms from tinymce.widgets import TinyMCE from django.utils.translation import ugettext_lazy as _ from ..institutions.models import Institution from .models import Monitoring from .utils import M2MFieldFormMixin class MonitoringForm(UserKwargModelFormMixin, FormHorizontalMixin, SingleButtonMixin, M2MFieldFormMixin, forms.ModelForm): institutions = forms.ModelMultipleChoiceField(queryset=Institution.objects.all(), label=_("Institutions"), required=False, widget=autocomplete.ModelSelect2Multiple(url='institutions:autocomplete')) def __init__(self, *args, **kwargs): super(MonitoringForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['institutions'].initial = self.instance.institutions.all() if not self.instance.user_id: self.instance.user = self.user def save(self, *args, **kwargs): super(MonitoringForm, self).save(*args, **kwargs) self.save_m2m_field(field='institutions', left='monitoring', right='institution') return self.instance class Meta: model = Monitoring fields = ['name', 'description', 'active', 'max_point', ] widgets = { 'description': TinyMCE(attrs={'cols': 80, 'rows': 30}), }
Add disk and memory stats to dashboard
<?php namespace Emergence\SiteAdmin; use Site; use Person; use User; use Emergence\Util\ByteSize; class DashboardRequestHandler extends \RequestHandler { public static function handleRequest() { $GLOBALS['Session']->requireAccountLevel('Administrator'); // get available memory $availableMemory = null; $availableSwap = null; $memoryOutput = explode(PHP_EOL, trim(shell_exec('free -b'))); array_shift($memoryOutput); foreach ($memoryOutput AS $line) { $line = preg_split('/\s+/', $line); if ($line[0] == 'Mem:') { $availableMemory = $line[3]; } elseif ($line[0] == 'Swap:') { $availableSwap = $line[3]; } } // render return static::respond('dashboard', [ 'metrics' => [ [ 'label' => 'People', 'value' => Person::getCount(), 'link' => '/people' ], [ 'label' => 'Users', 'value' => User::getCount(['Username IS NOT NULL']), 'link' => '/people?q=class:User' ], [ 'label' => 'Administrators', 'value' => User::getCount(['AccountLevel' => 'Administrator']), 'link' => '/people?q=accountlevel:Administrator' ], [ 'label' => 'Developers', 'value' => User::getCount(['AccountLevel' => 'Developer']), 'link' => '/people?q=accountlevel:Developer' ], [ 'label' => 'Available Storage', 'value' => ByteSize::format(exec('df --output=avail ' . escapeshellarg(Site::$rootPath))) ], [ 'label' => 'Available Memory', 'value' => $availableMemory ? ByteSize::format($availableMemory) : null ], [ 'label' => 'Available Swap', 'value' => $availableSwap ? ByteSize::format($availableSwap) : null ] ] ]); } }
<?php namespace Emergence\SiteAdmin; use Person; use User; class DashboardRequestHandler extends \RequestHandler { public static function handleRequest() { $GLOBALS['Session']->requireAccountLevel('Administrator'); return static::respond('dashboard', [ 'metrics' => [ [ 'label' => 'People', 'value' => Person::getCount(), 'link' => '/people' ], [ 'label' => 'Users', 'value' => User::getCount(['Username IS NOT NULL']), 'link' => '/people?q=class:User' ], [ 'label' => 'Administrators', 'value' => User::getCount(['AccountLevel' => 'Administrator']), 'link' => '/people?q=accountlevel:Administrator' ], [ 'label' => 'Developers', 'value' => User::getCount(['AccountLevel' => 'Developer']), 'link' => '/people?q=accountlevel:Developer' ] ] ]); } }
Fix typo in constructor and remove set_integrator method
import hoomd.integrate class Operations: def __init__(self, simulation=None): self.simulation = simulation self._auto_schedule = False self._compute = list() def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._integrator = op else: raise ValueError("Operation is not of the correct type to add to" " Operations.") @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) def _store_reader(self, reader): # TODO pass
import hoomd._integrator class Operations: def __init__(self, simulation=None): self.simulation = None self._auto_schedule = False self._compute = list() def add(self, op): if isinstance(op, hoomd.integrate._integrator): self._set_integrator(op) else: raise ValueError("Operation is not of the correct type to add to" " Operations.") def _set_integrator(self, integrator): self._integrator = integrator @property def _operations(self): op = list() if hasattr(self, '_integrator'): op.append(self._integrator) return op @property def _sys_init(self): if self.simulation is None or self.simulation.state is None: return False else: return True def schedule(self): if not self._sys_init: raise RuntimeError("System not initialized yet") sim = self.simulation for op in self._operations: new_objs = op.attach(sim) if isinstance(op, hoomd.integrate._integrator): sim._cpp_sys.setIntegrator(op._cpp_obj) if new_objs is not None: self._compute.extend(new_objs) def _store_reader(self, reader): # TODO pass
Add output file path to final log
'use strict'; var fs = require('fs'); var split = require('split'); var argv = require('minimist')(process.argv.slice(2)); if (!argv.hasOwnProperty('input')) { console.log('Usage: node index.js --input <path to line delimited GeoJSON FeatureCollections>'); } else { mergeStream(argv.input, argv.output); } function mergeStream(inputFile, outputFile) { if (!outputFile) { outputFile = argv.input.split('.')[0] + '-merged.json'; } var inputStream = fs.createReadStream(inputFile, {encoding: 'utf8'}).pipe(split()); var start = '{\'type\': \'FeatureCollection\', \'features\': ['; fs.appendFileSync(outputFile, start, {encoding: 'utf8'}); var comma = ''; var line = 0; inputStream.on('data', function (chunk) { line = line + 1; process.stderr.cursorTo(0); process.stderr.write('Processing line: ' + String(line)); if (chunk) { var features = JSON.parse(chunk).features; features.forEach(function (feature) { fs.appendFileSync(outputFile, comma + JSON.stringify(feature), {encoding: 'utf8'}); if (!comma) { comma = ','; } }); } }); inputStream.on('end', function () { var end = ']}'; fs.appendFileSync(outputFile, end, {encoding: 'utf8'}); console.log('\nMerged features in %s', outputFile); }); } module.exports = {'mergeStream': mergeStream};
'use strict'; var fs = require('fs'); var split = require('split'); var argv = require('minimist')(process.argv.slice(2)); if (!argv.hasOwnProperty('input')) { console.log('Usage: node index.js --input <path to line delimited GeoJSON FeatureCollections>'); } else { mergeStream(argv.input, argv.output); } function mergeStream(inputFile, outputFile) { if (!outputFile) { outputFile = argv.input.split('.')[0] + '-merged.json'; } var inputStream = fs.createReadStream(inputFile, {encoding: 'utf8'}).pipe(split()); var start = '{\'type\': \'FeatureCollection\', \'features\': ['; fs.appendFileSync(outputFile, start, {encoding: 'utf8'}); var comma = ''; var line = 0; inputStream.on('data', function (chunk) { line = line + 1; process.stderr.cursorTo(0); process.stderr.write('Processing line: ' + String(line)); if (chunk) { var features = JSON.parse(chunk).features; features.forEach(function (feature) { fs.appendFileSync(outputFile, comma + JSON.stringify(feature), {encoding: 'utf8'}); if (!comma) { comma = ','; } }); } }); inputStream.on('end', function () { var end = ']}'; fs.appendFileSync(outputFile, end, {encoding: 'utf8'}); console.log('\ndone'); }); } module.exports = {'mergeStream': mergeStream};
Remove Button, only in Download Menu
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function initialize () { } var load_ipython_extension = function() { /* Add an entry in the download menu */ var dwm = $("#download_menu") var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>') dwm.append(downloadEntry) downloadEntry.click(function () { Jupyter.menubar._nbconvert('html_embed', true); }); /* Add also a Button, currently disabled */ /* Jupyter.toolbar.add_buttons_group([{ id : 'export_embeddedhtml', label : 'Embedded HTML Export', icon : 'fa-save', callback : function() { Jupyter.menubar._nbconvert('html_embed', true); } }]); */ if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function initialize () { console.log("Embedded HTML Exporter loaded!"); } var load_ipython_extension = function() { var dwm = $("#download_menu") var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>') dwm.append(downloadEntry) downloadEntry.click(function () { Jupyter.menubar._nbconvert('html_embed', true); }); Jupyter.toolbar.add_buttons_group([{ id : 'export_embeddedhtml', label : 'Embedded HTML Export', icon : 'fa-save', callback : function() { Jupyter.menubar._nbconvert('html_embed', true); } }]); if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
Fix string == null error
package nuclibook.routes; import nuclibook.constants.P; import nuclibook.entity_utils.ExportUtils; import nuclibook.entity_utils.PatientUtils; import nuclibook.entity_utils.SecurityUtils; import nuclibook.models.Patient; import nuclibook.server.HtmlRenderer; import spark.Request; import spark.Response; import java.util.List; public class ExportRoute extends DefaultRoute { @Override public Object handle(Request request, Response response) throws Exception { // necessary prelim routine prepareToHandle(); String[] fileSplit = request.params(":file:").split("\\.", 2); String table = fileSplit[0]; String type = ""; try { type = fileSplit[1]; } catch (ArrayIndexOutOfBoundsException e) { return null; } String exportData = null; if (table.equals("patients")) { if (SecurityUtils.requirePermission(P.VIEW_PATIENT_LIST, response)) { if (type.equals("csv")) { exportData = ExportUtils.exportCSV(Patient.class); } } } if (exportData != null) { response.header("Content-Disposition", "attachment"); } return exportData; } }
package nuclibook.routes; import nuclibook.constants.P; import nuclibook.entity_utils.ExportUtils; import nuclibook.entity_utils.PatientUtils; import nuclibook.entity_utils.SecurityUtils; import nuclibook.models.Patient; import nuclibook.server.HtmlRenderer; import spark.Request; import spark.Response; import java.util.List; public class ExportRoute extends DefaultRoute { @Override public Object handle(Request request, Response response) throws Exception { // necessary prelim routine prepareToHandle(); String[] fileSplit = request.params(":file:").split("\\.", 2); String table = fileSplit[0]; String type = ""; try { type = fileSplit[1]; } catch (ArrayIndexOutOfBoundsException e) { return null; } String exportData = null; if (table.equals("patients")) { if (SecurityUtils.requirePermission(P.VIEW_PATIENT_LIST, response)) { if (type.equals("csv")) { return ExportUtils.exportCSV(Patient.class); } } } if (exportData != null) { response.header("Content-Disposition", "attachment"); } return exportData; } }
Fix displaying legend for fieldset
<?php namespace Jasny\FormBuilder; /** * Representation of an HTML <fieldset>. * * @option legend <legend> of the fieldset */ class Fieldset extends Group { /** * @var string */ protected $tagname = 'fieldset'; /** * Class constructor. * * @param array $options Element options * @param array $attr HTML attributes */ public function __construct(array $options=[], array $attr=[]) { parent::__construct($options, $attr); } /** * Set the legend of the fieldset. * * @param string $legend * @return Boostrap\Fieldset $this */ public function setLegend($legend) { $this->setOption('legend', $legend); return $this; } /** * Get the legend of the fieldset. * * @return string */ public function getLegend() { return $this->getOption('legend'); } /** * Render the fieldset to HTML. * * @return string */ public function open() { $html = "<fieldset {$this->attr}>"; if ($this->getLegend()) $html .= "\n<legend>" . $this->getLegend() . "</legend>"; return $html; } }
<?php namespace Jasny\FormBuilder; /** * Representation of an HTML <fieldset>. * * @option legend <legend> of the fieldset */ class Fieldset extends Group { /** * @var string */ protected $tagname = 'fieldset'; /** * Class constructor. * * @param array $options Element options * @param array $attr HTML attributes */ public function __construct(array $options=[], array $attr=[]) { parent::__construct($options, $attr); } /** * Set the legend of the fieldset. * * @param string $legend * @return Boostrap\Fieldset $this */ public function setLegend($legend) { $this->legend = $legend; return $this; } /** * Get the legend of the fieldset. * * @return string */ public function getLegend() { return $this->legend; } /** * Render the fieldset to HTML. * * @return string */ public function open() { $html = "<fieldset {$this->attr}>"; if (isset($this->legend)) $html .= "\n<legend>" . $this->legend . "</legend>"; return $html; } }
Set min boxCount to be 0 Don’t allow negative.
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Tiles from 'grommet/components/Tiles'; import Box from 'grommet/components/Box'; import Button from 'grommet/components/Button'; import Animate from 'grommet/components/Animate'; import Example from '../../Example'; export default class BoxesAnimation extends Component { constructor (props) { super(props); this.state = { boxCount: 3 }; } render () { const { boxCount } = this.state; return ( <div> <Button label="Add" primary={true} onClick={() => this.setState({boxCount: boxCount + 1})} /> <Button label="Remove" onClick={() => this.setState({boxCount: boxCount ? boxCount - 1 : 0})} /> <Example name="Boxes" code={ <Animate enter={{ animation: 'slide-up', duration: 1000 }} component={Tiles} > {(this.state.boxCount > 0) && new Array(this.state.boxCount).fill().map((c, i) => { return <Box key={`box-${i}`} style={{ width: 50, height: 50 }} colorIndex="brand" />; }) } </Animate> } /> </div> ); } };
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Tiles from 'grommet/components/Tiles'; import Box from 'grommet/components/Box'; import Button from 'grommet/components/Button'; import Animate from 'grommet/components/Animate'; import Example from '../../Example'; export default class BoxesAnimation extends Component { constructor (props) { super(props); this.state = { boxCount: 3 }; } render () { return ( <div> <Button label="Add" primary={true} onClick={() => this.setState({boxCount: this.state.boxCount + 1})} /> <Button label="Remove" onClick={() => this.setState({boxCount: this.state.boxCount - 1})} /> <Example name="Boxes" code={ <Animate enter={{ animation: 'slide-up', duration: 1000 }} component={Tiles} > {(this.state.boxCount > 0) && new Array(this.state.boxCount).fill().map((c, i) => { return <Box key={`box-${i}`} style={{ width: 50, height: 50 }} colorIndex="brand" />; }) } </Animate> } /> </div> ); } };
Fix Guzzle client in DisponsableCheck Test
<?php /* * This file is part of EmailChecker. * * (c) Corrado Ronci <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace sorciulus\EmailChecker\Tests; use PHPUnit\Framework\TestCase; use GuzzleHttp\Client; use sorciulus\EmailChecker\DisponsableChecker; use sorciulus\EmailChecker\Exception\DisponsableException; class DisponsableCheckerTest extends TestCase { public function testDisponsableCheckerInstanceTrue() { $instance = new DisponsableChecker(); $this->assertInstanceOf(DisponsableChecker::class, $instance); } public function testIsEnableIsBooleanTrue() { $instance = new DisponsableChecker(); $this->assertInternalType("boolean", $instance->isEnable()); } public function testApiCall() { $client = new Client([ "base_uri" => "https://open.kickbox.io" ]); $response = $client->get("/v1/disposable/gmail.com"); $body = (string)$response->getBody(); $data = json_decode($body, true); $this->assertInternalType("string", $body); $this->assertInternalType("array", $data); $this->assertArrayHasKey("disposable", $data); $this->assertInternalType("boolean", $data["disposable"]); } }
<?php /* * This file is part of EmailChecker. * * (c) Corrado Ronci <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace sorciulus\EmailChecker\Tests; use PHPUnit\Framework\TestCase; use GuzzleHttp\Client; use sorciulus\EmailChecker\DisponsableChecker; use sorciulus\EmailChecker\Exception\DisponsableException; class DisponsableCheckerTest extends TestCase { public function testDisponsableCheckerInstanceTrue() { $instance = new DisponsableChecker(); $this->assertInstanceOf(DisponsableChecker::class, $instance); } public function testIsEnableIsBooleanTrue() { $instance = new DisponsableChecker(); $this->assertInternalType("boolean", $instance->isEnable()); } public function testApiCall() { $client = new Client("https://open.kickbox.io", array( 'request.options' => array( 'exceptions' => false, ) )); $response = $client->get("/v1/disposable/gmail.com"); $body = (string)$response->getBody(); $data = json_decode($body, true); $this->assertInternalType("string", $body); $this->assertInternalType("array", $data); $this->assertArrayHasKey("disposable", $data); $this->assertInternalType("boolean", $data["disposable"]); } }
Remove @xstate/vue from the whitelisted automatically publishable packages
const { exec } = require('@actions/exec'); const getWorkspaces = require('get-workspaces').default; async function execWithOutput(command, args, options) { let myOutput = ''; let myError = ''; return { code: await exec(command, args, { listeners: { stdout: data => { myOutput += data.toString(); }, stderr: data => { myError += data.toString(); } }, ...options }), stdout: myOutput, stderr: myError }; } const publishablePackages = ['xstate', '@xstate/fsm', '@xstate/test']; (async () => { const currentBranchName = (await execWithOutput('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ])).stdout.trim(); if (!/^changeset-release\//.test(currentBranchName)) { return; } const latestCommitMessage = (await execWithOutput('git', [ 'log', '-1', '--pretty=%B' ])).stdout.trim(); await exec('git', ['reset', '--mixed', 'HEAD~1']); const workspaces = await getWorkspaces(); for (let workspace of workspaces) { if (publishablePackages.includes(workspace.name)) { continue; } await exec('git', ['checkout', '--', workspace.dir]); } await exec('git', ['add', '.']); await exec('git', ['commit', '-m', latestCommitMessage]); await exec('git', ['push', 'origin', currentBranchName, '--force']); })();
const { exec } = require('@actions/exec'); const getWorkspaces = require('get-workspaces').default; async function execWithOutput(command, args, options) { let myOutput = ''; let myError = ''; return { code: await exec(command, args, { listeners: { stdout: data => { myOutput += data.toString(); }, stderr: data => { myError += data.toString(); } }, ...options }), stdout: myOutput, stderr: myError }; } const publishablePackages = [ 'xstate', '@xstate/fsm', '@xstate/test', '@xstate/vue' ]; (async () => { const currentBranchName = (await execWithOutput('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ])).stdout.trim(); if (!/^changeset-release\//.test(currentBranchName)) { return; } const latestCommitMessage = (await execWithOutput('git', [ 'log', '-1', '--pretty=%B' ])).stdout.trim(); await exec('git', ['reset', '--mixed', 'HEAD~1']); const workspaces = await getWorkspaces(); for (let workspace of workspaces) { if (publishablePackages.includes(workspace.name)) { continue; } await exec('git', ['checkout', '--', workspace.dir]); } await exec('git', ['add', '.']); await exec('git', ['commit', '-m', latestCommitMessage]); await exec('git', ['push', 'origin', currentBranchName, '--force']); })();
test(Effects): Fix fade test with RAF Because of wrong mock implementation
import * as effects from 'src/effects' /** * @jest-environment jsdom */ jest.useFakeTimers() describe('Effects', () => { let element beforeEach(() => { element = document.createElement('div') document.body.appendChild(element) }) afterEach(() => { document.body.innerHTML = '' }) test('Fade in', () => { element.style.opacity = 1 effects.fadeIn(element, 100) expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(0) jest.runAllTimers() expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { global.requestAnimationFrame = jest.fn() effects.fadeIn(element, 1) jest.runAllTimers() expect(global.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() expect(global.requestAnimationFrame).toBeCalled() delete global.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0 effects.fadeOut(element, 100) expect(Number(element.style.opacity)).toBeLessThanOrEqual(1) jest.runAllTimers() expect(Number(element.style.opacity)).toBeLessThanOrEqual(0) }) test('Hide', () => { effects.hide(element) expect(element.style.display).toBe('none') }) test('Show', () => { effects.show(element) expect(element.style.display).toBe('') }) })
import * as effects from 'src/effects' /** * @jest-environment jsdom */ jest.useFakeTimers() describe('Effects', () => { let element beforeEach(() => { element = document.createElement('div') document.body.appendChild(element) }) afterEach(() => { document.body.innerHTML = '' }) test('Fade in', () => { element.style.opacity = 1 effects.fadeIn(element, 100) expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(0) jest.runAllTimers() expect(Number(element.style.opacity)).toBeGreaterThanOrEqual(1) }) test('RAF fade in', () => { window.requestAnimationFrame = jest.fn(fn => setTimeout(fn, 1)) effects.fadeIn(element, 1) jest.runAllTimers() expect(window.requestAnimationFrame).toBeCalled() effects.fadeIn(element) jest.runAllTimers() expect(window.requestAnimationFrame).toBeCalled() delete window.requestAnimationFrame }) test('Fade out', () => { element.style.opacity = 0 effects.fadeOut(element, 100) expect(Number(element.style.opacity)).toBeLessThanOrEqual(1) jest.runAllTimers() expect(Number(element.style.opacity)).toBeLessThanOrEqual(0) }) test('Hide', () => { effects.hide(element) expect(element.style.display).toBe('none') }) test('Show', () => { effects.show(element) expect(element.style.display).toBe('') }) })
Fix package tag in docblock
<?php namespace DB\Driver; /** * Database driver for MYSQL using MYSQLI rather than default and deprecated * MYSQL which is recommended by most PHP developer. * * @package DB\Driver */ class MYSQLI implements IDriver { private $mysqli; public function connect($host, $user, $password) { $this->mysqli = new \mysqli($host, $user, $password); } public function database($name) { $this->mysqli->select_db($name); } public function query($sql) { } public function bind($sql, $data=[]) { $length = count($data); for ($i=0;$i<$length;$i++) { $data[$i] = mysqli_escape_string($data[$i]); } $subs = 0; while (($pos = strpos($sql, '?')) !== false) { $sql = substr_replace($sql, $data[$subs], $pos); $subs++; } return $sql; } } ?>
<?php namespace DB\Driver; /** * Database driver for MYSQL using MYSQLI rather than default and deprecated * MYSQL which is recommended by most PHP developer. * * @package Core */ class MYSQLI implements IDriver { private $mysqli; public function connect($host, $user, $password) { $this->mysqli = new \mysqli($host, $user, $password); } public function database($name) { $this->mysqli->select_db($name); } public function query($sql) { } public function bind($sql, $data=[]) { $length = count($data); for ($i=0;$i<$length;$i++) { $data[$i] = mysqli_escape_string($data[$i]); } $subs = 0; while (($pos = strpos($sql, '?')) !== false) { $sql = substr_replace($sql, $data[$subs], $pos); $subs++; } return $sql; } } ?>
Increase gRenderer frame max to 240
gRenderer = { frame: 0, render: function() { this.context.fillStyle = '#000'; this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height); switch (gScene.scene) { case 'title': gScene.renderTitle(); break; case 'hangar': case 'game': gScene.renderBack(); if (gPlayer.life > 0) gPlayer.render(); gScene.renderFore(); gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this)); if (gScene.inTransition) gScene.renderTransition(); break; case 'levelTitle': gScene.renderLevelTitle(); break; } if (!gScene.inTransition) gInput.render(); // Debug display // this.context.font = '16px monospace'; // this.context.textAlign = 'left'; // this.context.fillStyle = '#FFF'; // this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12); // this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36); this.frame = (this.frame + 1) % 240; } }
gRenderer = { frame: 0, render: function() { this.context.fillStyle = '#000'; this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height); switch (gScene.scene) { case 'title': gScene.renderTitle(); break; case 'hangar': case 'game': gScene.renderBack(); if (gPlayer.life > 0) gPlayer.render(); gScene.renderFore(); gPlayer.projectiles.forEach(function(p) { p.render() }.bind(this)); if (gScene.inTransition) gScene.renderTransition(); break; case 'levelTitle': gScene.renderLevelTitle(); break; } if (!gScene.inTransition) gInput.render(); // Debug display // this.context.font = '16px monospace'; // this.context.textAlign = 'left'; // this.context.fillStyle = '#FFF'; // this.context.fillText('gCamera: ' + gCamera.x + ', ' + gCamera.y + ' vel: ' + gCamera.xVel + ', ' + gCamera.yVel, 12, 12); // this.context.fillText('gPlayer: ' + gPlayer.x + ', ' + gPlayer.y + ' vel: ' + gPlayer.xVel + ', ' + gPlayer.yVel, 12, 36); this.frame = (this.frame + 1) % 60; } }
Upgrade orderedmultidict dependency to v0.7.2.
import os import re import sys from sys import version_info from os.path import dirname, join as pjoin from setuptools import setup, find_packages with open(pjoin(dirname(__file__), 'furl', '__init__.py')) as fd: VERSION = re.compile( r".*__version__ = '(.*?)'", re.S).match(fd.read()).group(1) if sys.argv[-1] == 'publish': """ Publish to PyPi. """ os.system('python setup.py sdist upload') sys.exit() long_description = ( 'Information and documentation at https://github.com/gruns/furl.') setup(name='furl', version=VERSION, author='Arthur Grunseid', author_email='[email protected]', url='https://github.com/gruns/furl', license='Unlicense', description='URL manipulation made simple.', long_description=long_description, packages=find_packages(), include_package_data=True, platforms=['any'], classifiers=['Topic :: Internet', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: Freely Distributable', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], install_requires=['orderedmultidict >= 0.7.2'], test_suite='tests', tests_require=[] if version_info[0:2] >= [2, 7] else ['unittest2'], )
import os import re import sys from os.path import dirname, join as pjoin from sys import version_info from setuptools import setup, find_packages with open(pjoin(dirname(__file__), 'furl', '__init__.py')) as fd: VERSION = re.compile( r".*__version__ = '(.*?)'", re.S).match(fd.read()).group(1) if sys.argv[-1] == 'publish': ''' Publish to PyPi. ''' os.system('python setup.py sdist upload') sys.exit() long_description = ( 'Information and documentation at https://github.com/gruns/furl.') setup(name='furl', version=VERSION, author='Arthur Grunseid', author_email='[email protected]', url='https://github.com/gruns/furl', license='Unlicense', description='URL manipulation made simple.', long_description=long_description, packages=find_packages(), include_package_data=True, platforms=['any'], classifiers=['Topic :: Internet', 'Natural Language :: English', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: Freely Distributable', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], install_requires=['orderedmultidict >= 0.7.1'], test_suite='tests', tests_require=[] if version_info[0:2] >= [2, 7] else ['unittest2'], )
Fix url for otalk.im websocket endpoint
var parts = window.location.hash.slice(1).split('&'); parts.forEach(function (value) { if (value.substr(0, 12) === "access_token") { var token = value.substr(13); $.ajax({ type: 'get', url: 'https://api.andbang.com/me', dataType: 'json', headers: { 'Authorization': 'Bearer ' + token }, success: function (user) { localStorage.config = JSON.stringify({ jid: user.username.toLowerCase() + "@otalk.im", server: "otalk.im", wsURL: "wss://otalk.im:5281/xmpp-websocket", credentials: { username: user.username.toLowerCase(), password: token } }); window.location = '/'; }, error: function () { window.location = '/logout'; } }); } });
var parts = window.location.hash.slice(1).split('&'); parts.forEach(function (value) { if (value.substr(0, 12) === "access_token") { var token = value.substr(13); $.ajax({ type: 'get', url: 'https://api.andbang.com/me', dataType: 'json', headers: { 'Authorization': 'Bearer ' + token }, success: function (user) { localStorage.config = JSON.stringify({ jid: user.username.toLowerCase() + "@otalk.im", server: "otalk.im", wsURL: "wss://otalk.im/xmpp-websocket", credentials: { username: user.username.toLowerCase(), password: token } }); window.location = '/'; }, error: function () { window.location = '/logout'; } }); } });
Add 'config' option for PhpSpec
<?php namespace RMiller\BehatSpec; use Behat\Testwork\ServiceContainer\Extension; use Behat\Testwork\ServiceContainer\ExtensionManager; use RMiller\ErrorExtension\ErrorExtension; use RMiller\PhpSpecExtension\PhpSpecExtension as BehatPhpSpecExtension; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; class BehatExtension implements Extension { private $extensions = []; public function __construct() { $this->extensions = [ new BehatPhpSpecExtension(), new ErrorExtension(), ]; } public function process(ContainerBuilder $container) { foreach ($this->extensions as $extension) { $extension->process($container); } } public function initialize(ExtensionManager $extensionManager) { foreach ($this->extensions as $extension) { $extension->initialize($extensionManager); } } public function load(ContainerBuilder $container, array $config) { foreach ($this->extensions as $extension) { $extension->load($container, $config); } } public function getConfigKey() { return 'behatspec'; } public function configure(ArrayNodeDefinition $builder) { $builder ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('bin/phpspec')->end() ->scalarNode('config')->defaultNull()->end() ->end() ->end(); } }
<?php namespace RMiller\BehatSpec; use Behat\Testwork\ServiceContainer\Extension; use Behat\Testwork\ServiceContainer\ExtensionManager; use RMiller\ErrorExtension\ErrorExtension; use RMiller\PhpSpecExtension\PhpSpecExtension as BehatPhpSpecExtension; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; class BehatExtension implements Extension { private $extensions = []; public function __construct() { $this->extensions = [ new BehatPhpSpecExtension(), new ErrorExtension(), ]; } public function process(ContainerBuilder $container) { foreach ($this->extensions as $extension) { $extension->process($container); } } public function initialize(ExtensionManager $extensionManager) { foreach ($this->extensions as $extension) { $extension->initialize($extensionManager); } } public function load(ContainerBuilder $container, array $config) { foreach ($this->extensions as $extension) { $extension->load($container, $config); } } public function getConfigKey() { return 'behatspec'; } public function configure(ArrayNodeDefinition $builder) { $builder ->addDefaultsIfNotSet() ->children() ->scalarNode('path')->defaultValue('bin/phpspec')->end() ->end() ->end(); } }
[BUGFIX] Check for existance of $releasesList[0] before using
<?php namespace Deployer; task('buffer:stop', function () { $releasesList = get('releases_list'); // Remove lock files also from previous release because it can be still read by apache/nginx after switching. // get('releases_list') is cached by deployer on first call in other task so it does not have the latest release // this is why $releasesList[0] have last release and not current. $overwriteReleases = ['current']; if (!empty($releasesList[0])) { $overwriteReleases[] = $releasesList[0]; } foreach ($overwriteReleases as $overwriteRelease) { $overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease; foreach (get('buffer_config') as $key => $buffer) { if (!isset($buffer['entrypoint_filename'])) { throw new \RuntimeException('entrypoint_filename not set for buffer_data'); } $entrypointFilename = $buffer['entrypoint_filename']; if (isset($buffer['locker_filename'])) { $lockerFilename = $buffer['locker_filename']; } else { $lockerFilename = 'buffer.lock'; } if (dirname($entrypointFilename) != '.') { $entrypointDirectory = dirname($entrypointFilename) . '/'; } else { $entrypointDirectory = ''; } run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename); } } })->desc('Stop buffering reqests to application entrypoints.');
<?php namespace Deployer; task('buffer:stop', function () { $releasesList = get('releases_list'); // Remove lock files also from previous release because it can be still read by apache/nginx after switching. // get('releases_list') is cached by deployer on first call in other task so it does not have the latest release // this is why $releasesList[0] have last release and not current. $overwriteReleases = ['current']; if (!empty($releasesList)) { $overwriteReleases[] = $releasesList[0]; } foreach ($overwriteReleases as $overwriteRelease) { $overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease; foreach (get('buffer_config') as $key => $buffer) { if (!isset($buffer['entrypoint_filename'])) { throw new \RuntimeException('entrypoint_filename not set for buffer_data'); } $entrypointFilename = $buffer['entrypoint_filename']; if (isset($buffer['locker_filename'])) { $lockerFilename = $buffer['locker_filename']; } else { $lockerFilename = 'buffer.lock'; } if (dirname($entrypointFilename) != '.') { $entrypointDirectory = dirname($entrypointFilename) . '/'; } else { $entrypointDirectory = ''; } run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename); } } })->desc('Stop buffering reqests to application entrypoints.');
Exclude all except staging and production
const Client = require('../binary/base/client').Client; const getLanguage = require('../binary/base/language').getLanguage; const url_for_static = require('../binary/base/url').url_for_static; const Pushwoosh = require('web-push-notifications').Pushwoosh; const BinaryPushwoosh = (() => { const pw = new Pushwoosh(); let initialised = false; const init = () => { const hostname = window.location.hostname; if (!(hostname.match(/^(www.binary.com|staging.binary.com)$/))) return; if (!initialised) { pw.push(['init', { logLevel : 'none', // or debug applicationCode : 'D04E6-FA474', safariWebsitePushID : 'web.com.binary', defaultNotificationTitle: 'Binary.com', defaultNotificationImage: 'https://style.binary.com/images/logo/logomark.png', serviceWorkerUrl : url_for_static('/') + 'pushwoosh-service-worker-light.js', }]); initialised = true; sendTags(); } }; const sendTags = () => { pw.push((api) => { api.getTags().then((result) => { if (!result.result['Login ID'] || !result.result['Site Language']) { // send login id and site language return api.setTags({ 'Login ID' : Client.get('loginid'), 'Site Language': getLanguage(), }); } return null; }); }); }; return { init: init, }; })(); module.exports = BinaryPushwoosh;
const Client = require('../binary/base/client').Client; const getLanguage = require('../binary/base/language').getLanguage; const url_for_static = require('../binary/base/url').url_for_static; const Pushwoosh = require('web-push-notifications').Pushwoosh; const BinaryPushwoosh = (() => { const pw = new Pushwoosh(); let initialised = false; const init = () => { if (!initialised) { pw.push(['init', { logLevel : 'none', // or debug applicationCode : 'D04E6-FA474', safariWebsitePushID : 'web.com.binary', defaultNotificationTitle: 'Binary.com', defaultNotificationImage: 'https://style.binary.com/images/logo/logomark.png', serviceWorkerUrl : url_for_static('/') + 'pushwoosh-service-worker-light.js', }]); initialised = true; sendTags(); } }; const sendTags = () => { pw.push((api) => { api.getTags().then((result) => { if (!result.result['Login ID'] || !result.result['Site Language']) { // send login id and site language return api.setTags({ 'Login ID' : Client.get('loginid'), 'Site Language': getLanguage(), }); } return null; }); }); }; return { init: init, }; })(); module.exports = BinaryPushwoosh;
Send back the socket id with the pong message
var ds = require('./discovery') var rb = require('./rubygems') var sc = require('./scrape') var WebSocketServer = require('ws').Server var wss = new WebSocketServer({host: 'localhost', port: 3001}) var clients = {} wss.on('connection', (ws) => { ws.on('message', (data) => { var req = JSON.parse(data) if (req.message === 'ping') { ws.id = req.id clients[ws.id] = ws clients[ws.id].send(JSON.stringify({message: 'pong', id: ws.id})) } else if (req.message === 'gems') { ds.run(req.gem, (gem) => { if (!clients[req.id]) { return true } clients[req.id].send(JSON.stringify({message: 'node', gem: gem})) }, (err, gems) => { if (!clients[req.id]) { return true } clients[req.id].send(JSON.stringify({message: 'done', gems: gems})) } ) } else if (req.message === 'owners') { sc.owners('gems/' + req.gem, (err, owners) => { if (!clients[req.id]) { return true } clients[req.id].send(JSON.stringify({ message: 'owners', owners: owners, gem: req.gem })) }) } }) ws.on('close', () => delete clients[ws.id]) }) exports.clients = clients
var ds = require('./discovery') var rb = require('./rubygems') var sc = require('./scrape') var WebSocketServer = require('ws').Server var wss = new WebSocketServer({host: 'localhost', port: 3001}) var clients = {} wss.on('connection', (ws) => { ws.on('message', (data) => { var req = JSON.parse(data) if (req.message === 'ping') { ws.id = req.id clients[ws.id] = ws clients[ws.id].send(JSON.stringify({message: 'pong'})) } else if (req.message === 'gems') { ds.run(req.gem, (gem) => { if (!clients[req.id]) { return true } clients[req.id].send(JSON.stringify({message: 'node', gem: gem})) }, (err, gems) => { if (!clients[req.id]) { return true } clients[req.id].send(JSON.stringify({message: 'done', gems: gems})) } ) } else if (req.message === 'owners') { sc.owners('gems/' + req.gem, (err, owners) => { if (!clients[req.id]) { return true } clients[req.id].send(JSON.stringify({ message: 'owners', owners: owners, gem: req.gem })) }) } }) ws.on('close', () => delete clients[ws.id]) }) exports.clients = clients
Add node-style-guide to list of rules
'use babel'; import path from 'path' export default { jscsPath: { title: 'Path to JSCS binary', type: 'string', default: path.join(__dirname, '..', 'node_modules', 'jscs', 'bin', 'jscs') }, jscsConfigPath: { title: 'Path to custom .jscsrc file', type: 'string', default: path.join(__dirname, '~/', '.jscsrc') }, defaultPreset: { title: 'Default preset', description: 'What preset to use if no rules file is found.', enum: [ 'airbnb', 'crockford', 'google', 'grunt', 'jquery', 'mdcs', 'node-style-guide', 'wikimedia', 'yandex' ], type: 'string', default: 'google', }, esprima: { title: 'ES2015 and JSX Support', description: `Attempts to parse your ES2015 and JSX code using the esprima-fb version of the esprima parser.`, type: 'boolean', default: false }, esprimaPath: { title: 'Path to esprima parser folder', type: 'string', default: path.join(__dirname, '..', 'node_modules', 'esprima-fb') }, notifications: { title: 'Enable editor notifications', description: `If enabled, notifications will be shown after each attempt to fix a file. Shows both success and error messages.`, type: 'boolean', default: true } }
'use babel'; import path from 'path' export default { jscsPath: { title: 'Path to JSCS binary', type: 'string', default: path.join(__dirname, '..', 'node_modules', 'jscs', 'bin', 'jscs') }, jscsConfigPath: { title: 'Path to custom .jscsrc file', type: 'string', default: path.join(__dirname, '~/', '.jscsrc') }, defaultPreset: { title: 'Default preset', description: 'What preset to use if no rules file is found.', enum: [ 'airbnb', 'crockford', 'google', 'grunt', 'jquery', 'mdcs', 'wikimedia', 'yandex' ], type: 'string', default: 'google', }, esprima: { title: 'ES2015 and JSX Support', description: `Attempts to parse your ES2015 and JSX code using the esprima-fb version of the esprima parser.`, type: 'boolean', default: false }, esprimaPath: { title: 'Path to esprima parser folder', type: 'string', default: path.join(__dirname, '..', 'node_modules', 'esprima-fb') }, notifications: { title: 'Enable editor notifications', description: `If enabled, notifications will be shown after each attempt to fix a file. Shows both success and error messages.`, type: 'boolean', default: true } }
Remove HTML from output() return documentation
<?php /** * RocketPHP (http://rocketphp.io) * * @package RocketPHP * @link https://github.com/rocketphp/html * @license http://opensource.org/licenses/MIT MIT */ namespace RocketPHP\HTML; /** * Declaration * * Creates a declaration node. */ class Declaration extends Node_Abstract { /** * @access protected * @var string Output */ protected $_output; /** * Constructor * * @param string $name Name * @param null|string $value Data */ public function __construct($name, $data = null) { switch ($name) { case 'doctype': $data = isset($data) ? $data : 'html'; $this->_output = "<!DOCTYPE $data>\n"; break; case 'comment': $data = isset($data) ? $data : ""; $this->_output = "<!-- $data -->\n"; break; default: throw new BadMethodCallException( "Unknown HTML declaration", 1 ); break; } } /** * Return text output * * @return string */ public function output() { return $this->_output; } }
<?php /** * RocketPHP (http://rocketphp.io) * * @package RocketPHP * @link https://github.com/rocketphp/html * @license http://opensource.org/licenses/MIT MIT */ namespace RocketPHP\HTML; /** * Declaration * * Creates a declaration node. */ class Declaration extends Node_Abstract { /** * @access protected * @var string Output */ protected $_output; /** * Constructor * * @param string $name Name * @param null|string $value Data */ public function __construct($name, $data = null) { switch ($name) { case 'doctype': $data = isset($data) ? $data : 'html'; $this->_output = "<!DOCTYPE $data>\n"; break; case 'comment': $data = isset($data) ? $data : ""; $this->_output = "<!-- $data -->\n"; break; default: throw new BadMethodCallException( "Unknown HTML declaration", 1 ); break; } } /** * Return text output * * @return string HTML */ public function output() { return $this->_output; } }
Add unicode to image helpers
<?php namespace HeyUpdate\EmojiBundle\Twig\Extension; use HeyUpdate\Emoji\Emoji; class EmojiExtension extends \Twig_Extension { protected $emoji; public function __construct(Emoji $emoji) { $this->emoji = $emoji; } /** * {@inheritdoc} */ public function getFunctions() { return [ new \Twig_SimpleFunction('emoji', [$this->emoji, 'replaceEmojiWithImages'], [ 'is_safe' => ['html'], ]), new \Twig_SimpleFunction('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [ 'is_safe' => ['html'], ]), new \Twig_SimpleFunction('emoji_unicode_image', [$this->emoji, 'getEmojiImageByUnicode'], [ 'is_safe' => ['html'], ]), ]; } /** * {@inheritdoc} */ public function getFilters() { return [ new \Twig_SimpleFilter('emoji', [$this->emoji, 'replaceEmojiWithImages'], [ 'is_safe' => ['html'], ]), new \Twig_SimpleFilter('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [ 'is_safe' => ['html'], ]), new \Twig_SimpleFilter('emoji_unicode_image', [$this->emoji, 'getEmojiImageByUnicode'], [ 'is_safe' => ['html'], ]), ]; } /** * Returns the name of the extension. * * @return string The extension name */ public function getName() { return 'emoji'; } }
<?php namespace HeyUpdate\EmojiBundle\Twig\Extension; use HeyUpdate\Emoji\Emoji; class EmojiExtension extends \Twig_Extension { protected $emoji; public function __construct(Emoji $emoji) { $this->emoji = $emoji; } /** * {@inheritdoc} */ public function getFunctions() { return [ new \Twig_SimpleFunction('emoji', [$this->emoji, 'replaceEmojiWithImages'], [ 'is_safe' => ['html'], ]), new \Twig_SimpleFunction('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [ 'is_safe' => ['html'], ]), ]; } /** * {@inheritdoc} */ public function getFilters() { return [ new \Twig_SimpleFilter('emoji', [$this->emoji, 'replaceEmojiWithImages'], [ 'is_safe' => ['html'], ]), new \Twig_SimpleFilter('emoji_name_image', [$this->emoji, 'getEmojiImageByName'], [ 'is_safe' => ['html'], ]), ]; } /** * Returns the name of the extension. * * @return string The extension name */ public function getName() { return 'emoji'; } }
Comment out military advisor for now
<div class="box"> <div class="box-header with-border"> <h3 class="box-title"><i class="fa fa-group"></i> Consult advisor</h3> </div> <div class="box-body"> <div class="row"> <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.production') }}" class="btn btn-app btn-block"> <i class="fa fa-industry"></i> Production </a> </div> {{--<div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.military') }}" class="btn btn-app btn-block"> <i class="ra ra-crossed-swords"></i> Military </a> </div>--}} <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.land') }}" class="btn btn-app btn-block"> <i class="ra ra-honeycomb"></i> Land </a> </div> <div class="visible-xs">&nbsp;</div> <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.construction') }}" class="btn btn-app btn-block"> <i class="fa fa-home"></i> Construction </a> </div> </div> </div> </div>
<div class="box"> <div class="box-header with-border"> <h3 class="box-title"><i class="fa fa-group"></i> Consult advisor</h3> </div> <div class="box-body"> <div class="row"> <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.production') }}" class="btn btn-app btn-block"> <i class="fa fa-industry"></i> Production </a> <div class="spacer"></div> </div> <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.military') }}" class="btn btn-app btn-block"> <i class="ra ra-crossed-swords"></i> Military </a> </div> <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.land') }}" class="btn btn-app btn-block"> <i class="ra ra-honeycomb"></i> Land </a> </div> <div class="col-xs-6 col-sm-3"> <a href="{{ route('dominion.advisors.construction') }}" class="btn btn-app btn-block"> <i class="fa fa-home"></i> Construction </a> </div> </div> </div> </div>
Add another configuration array to the orginal
<?php namespace Vela\Core; /** * Config class * * Simple class to store or get elements from configuration registry */ class Config { /** @var array $data Data configuration array */ private $data = []; /** * Class constructor * @param array $data List of values to add to the configuration registry */ public function __construct(array $data = []) { $this->data = $data; } /** * Add another array to original configuration array * @param array * @throw \Exception */ public function add(array $array) { if (!empty(array_intersect_key($this->data, $array))) { throw new \Exception ('Duplicate config key'); } return array_merge($this->data, $array); } /** * Retrieves elements from config array * * @param string $key The configuration key to find. Supports dot notation * @return string|array returns a config value * @throws \InvalidArgumentException when no $key found */ public function get($key) { $data = $this->data; $parts = explode('.', $key); foreach ($parts as $part) { if (isset($data[$part])) { $data = $data[$part]; } else { throw new \InvalidArgumentException('Cannot find configuration key: ' . $key); } } return $data; } /** * Return true if value is empty for given key * * @param string $key * @return bool */ public function isEmpty($key) { return empty($this->data[$key]); } }
<?php namespace Vela\Core; /** * Config class * * Simple class to store or get elements from configuration registry */ class Config { /** @var array $data Data configuration array */ private $data = []; /** * Class constructor * @param array $data List of values to add to the configuration registry */ public function __construct(array $data = []) { $this->data = $data; } /** * Retrieves elements from config array * * @param string $key The configuration key to find. Supports dot notation * @return string|array returns a config value * @throws \InvalidArgumentException when no $key found */ public function get($key) { $data = $this->data; $parts = explode('.', $key); foreach ($parts as $part) { if (isset($data[$part])) { $data = $data[$part]; } else { throw new \InvalidArgumentException('Cannot find configuration key: ' . $key); } } return $data; } /** * Return true if value is empty for given key * * @param string $key * @return bool */ public function isEmpty($key) { return empty($this->data[$key]); } }
Stop ulmo caching for suds-jurko compliance Previously we were using ulmo with suds-jurko 0.6, which is the current latest release, but it is 4 years old. Most recent work on suds-jurko has been done on the development branch, including optimizations to memory use (which we need). Unfortunately, the development branch also includes some breaking changes, including one which "cleans up" the caching module: https://bitbucket.org/jurko/suds/commits/6b24afe3206fc648605cc8d19f7c58c605d9df5f?at=default This change renames .setduration() to .__set_duration(), which is called by ulmo here: https://github.com/emiliom/ulmo/blob/90dbfe31f38a72ea4cee9a52e572cfa8f8484adc/ulmo/cuahsi/wof/core.py#L290 By explicitly setting the caching to None, we ensure that line isn't executed and those errors don't crop up. The performance improvements we get from using the development branch of suds-jurko outweigh the benefits of caching for one day, since it is unlikely we will be accessing the exact same content repeatedly.
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site, None) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date, None)
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from datetime import date, timedelta from rest_framework.exceptions import ValidationError DATE_FORMAT = '%m/%d/%Y' def details(wsdl, site): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_site_info(wsdl, site) def values(wsdl, site, variable, from_date=None, to_date=None): if not wsdl: raise ValidationError({ 'error': 'Required argument: wsdl'}) if not site: raise ValidationError({ 'error': 'Required argument: site'}) if not variable: raise ValidationError({ 'error': 'Required argument: variable'}) if not to_date: # Set to default value of today to_date = date.today().strftime(DATE_FORMAT) if not from_date: # Set to default value of one week ago from_date = (date.today() - timedelta(days=7)).strftime(DATE_FORMAT) if not wsdl.upper().endswith('?WSDL'): wsdl += '?WSDL' from ulmo.cuahsi import wof return wof.get_values(wsdl, site, variable, from_date, to_date)
Resolve reactive props animation issue. A small consequence of replacing the entire dataset in the mixins files is that it causes certain charts to completely re-render even if only the 'data' attribute of a dataset is changing. In my case, I set up a reactive doughnut chart with two data points but whenever the data values change, instead of shifting the fill coloring, it completely re-renders the entire chart. You can see the issue in this fiddle (note the constant re-rendering): https://jsfiddle.net/sg0c82ev/11/ To solve the issue, I instead run a diff between the new and old dataset keys, remove keys that aren't present in the new data, and update the rest of the attributes individually. After making these changes my doughnut chart is animating as expected (even when adding and removing new dataset attributes). A fiddle with my changes: https://jsfiddle.net/sg0c82ev/12/ Perhaps this is too specific of a scenario to warrant a complexity increase like this (and better suited for a custom watcher) but I figured it would be better to dump it here and make it available for review. Let me know what you think.
module.exports = { props: { chartData: { required: true } }, watch: { 'chartData': { handler (newData, oldData) { if (oldData) { let chart = this._chart // Get new and old DataSet Labels let newDatasetLabels = newData.datasets.map((dataset) => { return dataset.label }) let oldDatasetLabels = oldData.datasets.map((dataset) => { return dataset.label }) // Stringify 'em for easier compare const oldLabels = JSON.stringify(oldDatasetLabels) const newLabels = JSON.stringify(newDatasetLabels) // Check if Labels are equal and if dataset length is equal if (newLabels === oldLabels && oldData.datasets.length === newData.datasets.length) { newData.datasets.forEach((dataset, i) => { // Get new and old dataset keys const oldDatasetKeys = Object.keys(oldData.datasets[i]) const newDatasetKeys = Object.keys(dataset) // Get keys that aren't present in the new data const deletionKeys = oldDatasetKeys.filter((key) => { return key !== '_meta' && newDatasetKeys.indexOf(key) === -1 }) // Remove outdated key-value pairs deletionKeys.forEach((deletionKey) => { delete chart.data.datasets[i][deletionKey] }) // Update attributes individually to avoid re-rendering the entire chart for (const attribute in dataset) { if (dataset.hasOwnProperty(attribute)) { chart.data.datasets[i][attribute] = dataset[attribute] } } }) chart.data.labels = newData.labels chart.update() } else { chart.destroy() this.renderChart(this.chartData, this.options) } } } } } }
module.exports = { props: { chartData: { required: true } }, watch: { 'chartData': { handler (newData, oldData) { if (oldData) { let chart = this._chart // Get new and old DataSet Labels let newDatasetLabels = newData.datasets.map((dataset) => { return dataset.label }) let oldDatasetLabels = oldData.datasets.map((dataset) => { return dataset.label }) // Stringify 'em for easier compare const oldLabels = JSON.stringify(oldDatasetLabels) const newLabels = JSON.stringify(newDatasetLabels) // Check if Labels are equal and if dataset length is equal if (newLabels === oldLabels && oldData.datasets.length === newData.datasets.length) { newData.datasets.forEach((dataset, i) => { chart.data.datasets[i] = dataset }) chart.data.labels = newData.labels chart.update() } else { chart.destroy() this.renderChart(this.chartData, this.options) } } } } } }
Fix for ServiceManager's Di Integration's before/after usage Addition of nested configuration of controllers in ControllerLoader
<?php namespace Zend\ServiceManager\Di; use Zend\ServiceManager\AbstractFactoryInterface, Zend\ServiceManager\ServiceLocatorInterface, Zend\Di\Di; class DiAbstractServiceFactory extends DiServiceFactory implements AbstractFactoryInterface { /** * @param \Zend\Di\Di $di * @param null|string|\Zend\Di\InstanceManager $useServiceLocator */ public function __construct(Di $di, $useServiceLocator = self::USE_SL_NONE) { $this->di = $di; if (in_array($useServiceLocator, array(self::USE_SL_BEFORE_DI, self::USE_SL_AFTER_DI, self::USE_SL_NONE))) { $this->useServiceLocator = $useServiceLocator; } // since we are using this in a proxy-fashion, localize state $this->definitions = $this->di->definitions; $this->instanceManager = $this->di->instanceManager; } /** * @param ServiceLocatorInterface $serviceLocator * @param $serviceName * @param null $requestedName * @return object */ public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $serviceName, $requestedName = null) { $this->serviceLocator = $serviceLocator; if ($requestedName) { return $this->get($requestedName, array(), true); } else { return $this->get($serviceName, array(), true); } } /** * @param $name * @return null */ public function canCreateServiceWithName($name) { return null; // not sure } }
<?php namespace Zend\ServiceManager\Di; use Zend\ServiceManager\AbstractFactoryInterface, Zend\ServiceManager\ServiceLocatorInterface, Zend\Di\Di; class DiAbstractServiceFactory extends DiServiceFactory implements AbstractFactoryInterface { /** * @param \Zend\Di\Di $di * @param null|string|\Zend\Di\InstanceManager $useServiceLocator */ public function __construct(Di $di, $useServiceLocator = self::USE_SL_NONE) { $this->di = $di; if (in_array($useServiceLocator, array(self::USE_SL_BEFORE_DI, self::USE_SL_AFTER_DI, self::USE_SL_NONE))) { $this->useServiceManager = $useServiceLocator; } // since we are using this in a proxy-fashion, localize state $this->definitions = $this->di->definitions; $this->instanceManager = $this->di->instanceManager; } /** * @param ServiceLocatorInterface $serviceLocator * @param $serviceName * @param null $requestedName * @return object */ public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $serviceName, $requestedName = null) { $this->serviceLocator = $serviceLocator; if ($requestedName) { return $this->get($requestedName, array(), true); } else { return $this->get($serviceName, array(), true); } } /** * @param $name * @return null */ public function canCreateServiceWithName($name) { return null; // not sure } }
fix(app): Fix coverage folder for mocha
'use strict'; var gulp = require('gulp'); var runSequence = require('run-sequence'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var gutil = require('gulp-util'); var constants = require('../common/constants')(); gulp.task('mocha', 'Runs the mocha tests.', function() { return gulp.src(constants.mocha.libs) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()) .on('finish', function() { gutil.log(__dirname); gulp.src(constants.mocha.tests) .pipe(mocha({ reporter: 'spec', globals: constants.mocha.globals, timeout: constants.mocha.timeout })) .pipe(istanbul.writeReports({ dir: './coverage/mocha', reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })); }); }); gulp.task('test', 'Runs all the tests.', function(done) { runSequence( 'lint', 'mocha', done ); });
'use strict'; var gulp = require('gulp'); var runSequence = require('run-sequence'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var gutil = require('gulp-util'); var constants = require('../common/constants')(); gulp.task('mocha', 'Runs the mocha tests.', function() { return gulp.src(constants.mocha.libs) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()) .on('finish', function() { gutil.log(__dirname); gulp.src(constants.mocha.tests) .pipe(mocha({ reporter: 'spec', globals: constants.mocha.globals, timeout: constants.mocha.timeout })) .pipe(istanbul.writeReports({ reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })); }); }); gulp.task('test', 'Runs all the tests.', function(done) { runSequence( 'lint', 'mocha', done ); });
Add system support to export talkgroups
import sys import datetime import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils import timezone from radio.models import * class Command(BaseCommand): help = 'Import talkgroup info' def add_arguments(self, parser): parser.add_argument('file') parser.add_argument( '--system', type=int, default=-1, help='Export talkgroups from only this system', ) def handle(self, *args, **options): export_tg_file(options) def export_tg_file(options): ''' Using the talkgroup file from trunk-recorder''' file_name = options['file'] system = options['system'] talkgroups = TalkGroup.objects.all() if system >= 0: talkgroups = talkgroups.filter(system=system) with open(file_name, "w") as tg_file: for t in talkgroups: alpha = t.alpha_tag description = t.description hex_val = str(hex(t.dec_id))[2:-1].zfill(3) try: alpha = alpha.rstrip() except AttributeError: pass try: description = description.rstrip() except AttributeError: pass common = '' if(t.common_name): common = t.common_name tg_file.write("{},{},{},{},{},{}\n".format(t.dec_id,hex_val,t.mode,alpha,description,t.priority))
import sys import datetime import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils import timezone from radio.models import * class Command(BaseCommand): help = 'Import talkgroup info' def add_arguments(self, parser): parser.add_argument('file') def handle(self, *args, **options): f_name = options['file'] export_tg_file(f_name) def export_tg_file(file_name): ''' Using the talkgroup file from trunk-recorder''' talkgroups = TalkGroup.objects.all() with open(file_name, "w") as tg_file: for t in talkgroups: alpha = t.alpha_tag description = t.description hex_val = str(hex(t.dec_id))[2:-1].zfill(3) try: alpha = alpha.rstrip() except AttributeError: pass try: description = description.rstrip() except AttributeError: pass common = '' if(t.common_name): common = t.common_name tg_file.write("{},{},{},{},{},{}\n".format(t.dec_id,hex_val,t.mode,alpha,description,t.priority))
Refresh angular controllers after login
/// <reference path="../Services/AccountService.js" /> (function () { 'use strict'; angular .module('GVA.Common') .controller('AccountLoginController', AccountLoginController); AccountLoginController.$inject = ['$scope', '$rootScope', '$route', 'AccountService']; function AccountLoginController($scope, $rootScope, $route, AccountService) { $scope.loginAccount = loginAccount; $scope.forgottenPassword = forgottenPassword; function loginAccount(form) { clearError(); AccountService.login(form.email, form.password) .then(function () { closeDialog(); $route.reload(); }) .catch(displayErrorMessage); } function displayErrorMessage() { showError($rootScope.error.readableMessage); $rootScope.error = null; } function forgottenPassword(form) { clearError(); if (form.email === undefined) { showError('Please supply email address.'); } else { AccountService.forgotPassword(form.email) .then(closeDialog) .catch(function (data) { showError(data.Message || data.error_description); }); } } function closeDialog() { $scope.closeThisDialog(); } function clearError() { $scope.displayError = null; } function showError(errorMessage) { $scope.displayError = errorMessage; } } })();
/// <reference path="../Services/AccountService.js" /> (function () { 'use strict'; angular .module('GVA.Common') .controller('AccountLoginController', AccountLoginController); AccountLoginController.$inject = ['$scope', '$rootScope', 'AccountService']; function AccountLoginController($scope, $rootScope, AccountService) { $scope.loginAccount = loginAccount; $scope.forgottenPassword = forgottenPassword; function loginAccount(form) { clearError(); AccountService.login(form.email, form.password) .then(function () { closeDialog(); //setTimeout(function () { // window.location.reload(); //}, 300); }) .catch(displayErrorMessage); } function displayErrorMessage() { showError($rootScope.error.readableMessage); $rootScope.error = null; } function forgottenPassword(form) { clearError(); if (form.email === undefined) { showError('Please supply email address.'); } else { AccountService.forgotPassword(form.email) .then(closeDialog) .catch(function (data) { showError(data.Message || data.error_description); }); } } function closeDialog() { $scope.closeThisDialog(); } function clearError() { $scope.displayError = null; } function showError(errorMessage) { $scope.displayError = errorMessage; } } })();
Update test to use the type of date string we see on Prod
<?php use Northstar\Models\User; class StandardizeBirthdatesTest extends TestCase { /** @test */ public function it_should_fix_birthdates() { // We are creating some bad data on purpose, so don't try to send it to Customer.io Bus::fake(); // Create some regular and borked birthday users factory(User::class, 5)->create(); $this->createMongoDocument('users', ['birthdate' => '2018-03-15 00:00:00']); $this->createMongoDocument('users', ['birthdate' => 'I love dogs']); // Make sure we are registering 2 borked users $borkedUsersCount = User::whereRaw([ 'birthdate' => [ '$exists' => true, '$not' => [ '$type' => 9, ], ], ])->count(); $this->assertEquals($borkedUsersCount, 2); // Run the Birthdate Standardizer command. $this->artisan('northstar:bday'); // Make sure we have 0 borked users $borkedUsersCount = User::whereRaw([ 'birthdate' => [ '$exists' => true, '$not' => [ '$type' => 9, ], ], ])->count(); $this->assertEquals($borkedUsersCount, 0); } }
<?php use Northstar\Models\User; class StandardizeBirthdatesTest extends TestCase { /** @test */ public function it_should_fix_birthdates() { // We are creating some bad data on purpose, so don't try to send it to Customer.io Bus::fake(); // Create some regular and borked birthday users factory(User::class, 5)->create(); $this->createMongoDocument('users', ['birthdate' => '2018-03-15 00:00:00.000']); $this->createMongoDocument('users', ['birthdate' => 'I love dogs']); // Make sure we are registering 2 borked users $borkedUsersCount = User::whereRaw([ 'birthdate' => [ '$exists' => true, '$not' => [ '$type' => 9, ], ], ])->count(); $this->assertEquals($borkedUsersCount, 2); // Run the Birthdate Standardizer command. $this->artisan('northstar:bday'); // Make sure we have 0 borked users $borkedUsersCount = User::whereRaw([ 'birthdate' => [ '$exists' => true, '$not' => [ '$type' => 9, ], ], ])->count(); $this->assertEquals($borkedUsersCount, 0); } }
Fix Unit Test according to update on controller.parseMethodName(): * now controller.parseMethodName() receives the method name instead of the function object.
'use strict' const controller = require('./../lib/connectController') module.exports.testParseMethodNameWithoutParameters = function(test) { testParseMethodName( function get_members() {}, // actual '/members', // expected test) } module.exports.testParseMethodNameWithoutParametersNorPrefix = function(test) { testParseMethodName( function members() {}, // actual '/members', // expected test) } module.exports.testParseMethodNameWithoutGetPrefix = function(test) { testParseMethodName( function index_id_members() {}, // actual '/:id/members', // expected test) } module.exports.testParseMethodNameWithGet = function(test) { testParseMethodName( function get_index_id_members() {}, // actual '/:id/members', // expected test) } function testParseMethodName(method, expected, test) { /** * Act */ test.expect(1) const routePath = controller.parseMethodName(method.name) /** * Assert */ test.equal(routePath, expected) test.done() }
'use strict' const controller = require('./../lib/connectController') module.exports.testParseMethodNameWithoutParameters = function(test) { testParseMethodName( function get_members() {}, // actual '/members', // expected test) } module.exports.testParseMethodNameWithoutParametersNorPrefix = function(test) { testParseMethodName( function members() {}, // actual '/members', // expected test) } module.exports.testParseMethodNameWithoutGetPrefix = function(test) { testParseMethodName( function index_id_members() {}, // actual '/:id/members', // expected test) } module.exports.testParseMethodNameWithGet = function(test) { testParseMethodName( function get_index_id_members() {}, // actual '/:id/members', // expected test) } function testParseMethodName(method, expected, test) { /** * Act */ test.expect(1) const routePath = controller.parseMethodName(method) /** * Assert */ test.equal(routePath, expected) test.done() }
Make location optional in action core
import _ from 'lodash'; const {knex} = require('../util/database').connect(); function createAction(action) { const dbRow = { 'team_id': knex.raw('(SELECT team_id from users WHERE uuid = ?)', [action.user]), 'action_type_id': knex.raw('(SELECT id from action_types WHERE code = ?)', [action.type]), 'user_id': knex.raw('(SELECT id from users WHERE uuid = ?)', [action.user]), 'image_path': action.imagePath, 'text': action.text }; const location = action.location; if (location) { // Tuple is in longitude, latitude format in Postgis dbRow.location = location.longitude + ',' + location.longitude; } return knex('actions').returning('*').insert(dbRow) .then(rows => { if (_.isEmpty(rows)) { throw new Error('Action row creation failed: ' + dbRow); } return rows.length; }); } function getActionType(code) { return knex('action_types') .select('*') .limit(1) .where('code', code) .then(rows => { if (_.isEmpty(rows)) { return null; } return _actionTypeRowToObject(rows[0]); }); } function _actionTypeRowToObject(row) { return { id: row.id, code: row.code, name: row.name, value: row.value, cooldown: row.cooldown }; } export { createAction, getActionType };
import _ from 'lodash'; const {knex} = require('../util/database').connect(); function createAction(action) { const dbRow = { 'team_id': knex.raw('(SELECT team_id from users WHERE uuid = ?)', [action.user]), 'action_type_id': knex.raw('(SELECT id from action_types WHERE code = ?)', [action.type]), 'user_id': knex.raw('(SELECT id from users WHERE uuid = ?)', [action.user]), // Tuple is in longitude, latitude format in Postgis location: action.location.longitude + ',' + action.location.longitude, 'image_path': action.imagePath }; if (action.text) { dbRow.text = action.text; } return knex('actions').returning('*').insert(dbRow) .then(rows => { if (_.isEmpty(rows)) { throw new Error('Action row creation failed: ' + dbRow); } return rows.length; }); } function getActionType(code) { return knex('action_types') .select('*') .limit(1) .where('code', code) .then(rows => { if (_.isEmpty(rows)) { return null; } return _actionTypeRowToObject(rows[0]); }); } function _actionTypeRowToObject(row) { return { id: row.id, code: row.code, name: row.name, value: row.value, cooldown: row.cooldown }; } export { createAction, getActionType };
Rename to follow constant naming conventions
import re class Phage: SUPPORTED_DATABASES = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): for db, regex in Phage.SUPPORTED_DATABASES.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
import re class Phage: supported_databases = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parse_phage(raw_text, phage_finder) def _parse_phage(self, raw_text, phage_finder): for db, regex in Phage.supported_databases.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.find_by_phage(short_name, cluster) self.db = db
Change split file lines by line
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <[email protected]> # # Parse queue_log Asterisk file and add records into database. # from libs.qpanel import model import click import sys @click.command() @click.option('--file', default='/var/log/asterisk/queue_log', help='Queue Log file.') @click.option('--verbose', default=False) def parse(file, verbose): inserted, not_inserted = 0, 0 try: with open(file) as fb: print("Reading file %s ..." % file) content = fb.read().splitlines() except IOError: print('File file %s not exits or not can read.' % file) sys.exit(1) for idx, line in enumerate(content): record = line.split('|') if len(record) < 4: continue if not exist_record(record) and insert_record(record): inserted += 1 if verbose: print ("Insert record ", record) else: if verbose: print ("Not insert record ", record) not_inserted += 1 print ("Insert record: %i\nNo inserted record: %i" % (inserted, not_inserted)) def exist_record(record): return model.queuelog_exists_record(record) def insert_record(record): return model.queuelog_insert(record) if __name__ == '__main__': parse()
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Rodrigo Ramírez Norambuena <[email protected]> # # Parse queue_log Asterisk file and add records into database. # from libs.qpanel import model import click import sys @click.command() @click.option('--file', default='/var/log/asterisk/queue_log', help='Queue Log file.') @click.option('--verbose', default=False) def parse(file, verbose): inserted, not_inserted = 0, 0 try: with open(file) as fb: print("Reading file %s ..." % file) content = fb.read().split("\n") except IOError: print('File file %s not exits or not can read.' % file) sys.exit(1) for idx, line in enumerate(content): record = line.split('|') if len(record) < 4: continue if not exist_record(record) and insert_record(record): inserted += 1 if verbose: print ("Insert record ", record) else: if verbose: print ("Not insert record ", record) not_inserted += 1 print ("Insert record: %i\nNo inserted record: %i" % (inserted, not_inserted)) def exist_record(record): return model.queuelog_exists_record(record) def insert_record(record): return model.queuelog_insert(record) if __name__ == '__main__': parse()
Remove duplicated DNA Sample Change from admin
<?php return array( 'import' => array( 'application.modules.Genetics.models.*', 'application.modules.Genetics.components.*', ), 'params' => array( 'menu_bar_items' => array( 'pedigrees' => array( 'title' => 'Genetics', 'uri' => 'Genetics/default/index', 'position' => 40, 'restricted' => array('Genetics User'), ), ), 'module_partials' => array( 'patient_summary_column1' => array( 'Genetics' => array( '_patient_genetics', ), ), ), 'admin_structure' => array( 'Studies' => array( 'Genetics' => '/Genetics/studyAdmin/list', ), ), 'admin_menu' => array( 'Base Change Type' => '/Genetics/baseChangeAdmin/list', 'Amino Acid Change Type' => '/Genetics/aminoAcidChangeAdmin/list', 'Genome Versions' => '/Genetics/admin/list' ), ), );
<?php return array( 'import' => array( 'application.modules.Genetics.models.*', 'application.modules.Genetics.components.*', ), 'params' => array( 'menu_bar_items' => array( 'pedigrees' => array( 'title' => 'Genetics', 'uri' => 'Genetics/default/index', 'position' => 40, 'restricted' => array('Genetics User'), ), ), 'module_partials' => array( 'patient_summary_column1' => array( 'Genetics' => array( '_patient_genetics', ), ), ), 'admin_structure' => array( 'Studies' => array( 'Genetics' => '/Genetics/studyAdmin/list', ), ), 'admin_menu' => array( 'Base Change Type' => '/Genetics/baseChangeAdmin/list', 'Amino Acid Change Type' => '/Genetics/aminoAcidChangeAdmin/list', 'DNA Sample Change' => '/OphInDnasample/DnaSampleAdmin/list', 'Genome Versions' => '/Genetics/admin/list' ), ), );
Add access phpDocumentor tag to _output
<?php /** * RocketPHP (http://rocketphp.io) * * @package RocketPHP * @link https://github.com/rocketphp/html * @license http://opensource.org/licenses/MIT MIT */ namespace RocketPHP\HTML; /** * Declaration * * Creates a declaration node. */ class Declaration extends Node_Abstract { /** * @access protected * @var string Output */ protected $_output; /** * Constructor * * @param string $name Name * @param null|string $value Data */ public function __construct($name, $data = null) { switch ($name) { case 'doctype': $data = isset($data) ? $data : 'html'; $this->_output = "<!DOCTYPE $data>\n"; break; case 'comment': $data = isset($data) ? $data : ""; $this->_output = "<!-- $data -->\n"; break; default: throw new BadMethodCallException( "Unknown HTML declaration", 1 ); break; } } /** * Return text output * * @return string HTML */ public function output() { return $this->_output; } }
<?php /** * RocketPHP (http://rocketphp.io) * * @package RocketPHP * @link https://github.com/rocketphp/html * @license http://opensource.org/licenses/MIT MIT */ namespace RocketPHP\HTML; /** * Declaration * * Creates a declaration node. */ class Declaration extends Node_Abstract { /** * @var string Output */ protected $_output; /** * Constructor * * @param string $name Name * @param null|string $value Data */ public function __construct($name, $data = null) { switch ($name) { case 'doctype': $data = isset($data) ? $data : 'html'; $this->_output = "<!DOCTYPE $data>\n"; break; case 'comment': $data = isset($data) ? $data : ""; $this->_output = "<!-- $data -->\n"; break; default: throw new BadMethodCallException( "Unknown HTML declaration", 1 ); break; } } /** * Return text output * * @return string HTML */ public function output() { return $this->_output; } }
Clean up some of our dashboard container imports
from tg import config from tw.api import Widget from moksha.lib.helpers import eval_app_config, ConfigWrapper class AppListWidget(Widget): template = 'mako:moksha.api.widgets.containers.templates.layout_applist' properties = ['category'] def update_params(self, d): super(AppListWidget, self).update_params(d) # we want to error out if there is no category c = d['category'] if isinstance(c, basestring): for cat in d['layout']: if cat['label'] == c: d['category'] = cat break applist_widget = AppListWidget('applist'); class DashboardContainer(Widget): template = 'mako:moksha.api.widgets.containers.templates.dashboardcontainer' config_key = None layout = [] def update_params(self, d): super(DashboardContainer, self).update_params(d) layout = eval_app_config(config.get(self.config_key, "None")) if not layout: if isinstance(self.layout, basestring): layout = eval_app_config(self.layout) else: layout = self.layout # Filter out any None's in the layout which signify apps which are # not allowed to run with the current session's authorization level l = ConfigWrapper.process_wrappers(layout, d) d['layout'] = l d['applist_widget'] = applist_widget return d
from moksha.api.widgets.layout.layout import layout_js, layout_css, ui_core_js, ui_draggable_js, ui_droppable_js, ui_sortable_js from tw.api import Widget from tw.jquery import jquery_js from moksha.lib.helpers import eval_app_config, ConfigWrapper from tg import config class AppListWidget(Widget): template = 'mako:moksha.api.widgets.containers.templates.layout_applist' properties = ['category'] def update_params(self, d): super(AppListWidget, self).update_params(d) # we want to error out if there is no category c = d['category'] if isinstance(c, basestring): for cat in d['layout']: if cat['label'] == c: d['category'] = cat break applist_widget = AppListWidget('applist'); class DashboardContainer(Widget): template = 'mako:moksha.api.widgets.containers.templates.dashboardcontainer' config_key = None layout = [] def update_params(self, d): super(DashboardContainer, self).update_params(d) layout = eval_app_config(config.get(self.config_key, "None")) if not layout: if isinstance(self.layout, basestring): layout = eval_app_config(self.layout) else: layout = self.layout # Filter out any None's in the layout which signify apps which are # not allowed to run with the current session's authorization level l = ConfigWrapper.process_wrappers(layout, d) d['layout'] = l d['applist_widget'] = applist_widget return d
Drop unnecessary reference to popped elements to allow finalization through GC (XSTR-264).
package com.thoughtworks.xstream.core.util; public final class FastStack { private Object[] stack; private int pointer; public FastStack(int initialCapacity) { stack = new Object[initialCapacity]; } public Object push(Object value) { if (pointer + 1 >= stack.length) { resizeStack(stack.length * 2); } stack[pointer++] = value; return value; } public void popSilently() { stack[--pointer] = null; } public Object pop() { final Object result = stack[--pointer]; stack[pointer] = null; return result; } public Object peek() { return pointer == 0 ? null : stack[pointer - 1]; } public int size() { return pointer; } public boolean hasStuff() { return pointer > 0; } public Object get(int i) { return stack[i]; } private void resizeStack(int newCapacity) { Object[] newStack = new Object[newCapacity]; System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity)); stack = newStack; } public String toString() { StringBuffer result = new StringBuffer("["); for (int i = 0; i < pointer; i++) { if (i > 0) { result.append(", "); } result.append(stack[i]); } result.append(']'); return result.toString(); } }
package com.thoughtworks.xstream.core.util; public final class FastStack { private Object[] stack; private int pointer; public FastStack(int initialCapacity) { stack = new Object[initialCapacity]; } public Object push(Object value) { if (pointer + 1 >= stack.length) { resizeStack(stack.length * 2); } stack[pointer++] = value; return value; } public void popSilently() { pointer--; } public Object pop() { return stack[--pointer]; } public Object peek() { return pointer == 0 ? null : stack[pointer - 1]; } public int size() { return pointer; } public boolean hasStuff() { return pointer > 0; } public Object get(int i) { return stack[i]; } private void resizeStack(int newCapacity) { Object[] newStack = new Object[newCapacity]; System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity)); stack = newStack; } public String toString() { StringBuffer result = new StringBuffer("["); for (int i = 0; i < pointer; i++) { if (i > 0) { result.append(", "); } result.append(stack[i]); } result.append(']'); return result.toString(); } }
Update to where link is clickable in javadocs
package com.github.aurae.retrofit2; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import static com.bluelinelabs.logansquare.ConverterUtils.isSupported; /** * A {@linkplain Converter.Factory converter} which uses LoganSquare for JSON. * * @see <a href="https://github.com/bluelinelabs/LoganSquare">https://github.com/bluelinelabs/LoganSquare</a> */ public final class LoganSquareConverterFactory extends Converter.Factory { /** * Create an instance. Encoding to JSON and decoding from JSON will use UTF-8. * * @return A {@linkplain Converter.Factory} configured to serve LoganSquare converters */ public static LoganSquareConverterFactory create() { return new LoganSquareConverterFactory(); } private LoganSquareConverterFactory() { } @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (isSupported(type)) { return new LoganSquareResponseBodyConverter(type); } else { return null; } } @Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { if (isSupported(type)) { return new LoganSquareRequestBodyConverter(type); } else { return null; } } }
package com.github.aurae.retrofit2; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import static com.bluelinelabs.logansquare.ConverterUtils.isSupported; /** * A {@linkplain Converter.Factory converter} which uses LoganSquare for JSON. * * @see <a>https://github.com/bluelinelabs/LoganSquare</a> */ public final class LoganSquareConverterFactory extends Converter.Factory { /** * Create an instance. Encoding to JSON and decoding from JSON will use UTF-8. * * @return A {@linkplain Converter.Factory} configured to serve LoganSquare converters */ public static LoganSquareConverterFactory create() { return new LoganSquareConverterFactory(); } private LoganSquareConverterFactory() { } @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (isSupported(type)) { return new LoganSquareResponseBodyConverter(type); } else { return null; } } @Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { if (isSupported(type)) { return new LoganSquareRequestBodyConverter(type); } else { return null; } } }
Make incorrect signup error more helpful
angular.module('bolt.auth', []) .controller('AuthController', function ($scope, $window, $location, Auth) { $scope.user = {}; $scope.signin = function () { Auth.signin($scope.user) .then(function (session) { $window.localStorage.setItem('com.bolt', session.token); $window.localStorage.setItem('username', session.username); $window.localStorage.setItem('firstName', session.firstName); $window.localStorage.setItem('lastName', session.lastName); $window.localStorage.setItem('phone', session.phone); $window.localStorage.setItem('email', session.email); $window.localStorage.setItem('preferredDistance', session.preferredDistance); $window.localStorage.setItem('runs', session.runs); $window.localStorage.setItem('achievements', session.achievements); $location.path('/'); }) .catch(function (error) { $scope.errorDetected = true; $scope.signinError = "Hmm... we can't seem to find that username in our DB. Could it be another?"; }); }; $scope.signup = function () { Auth.signup($scope.user) .then(function (token) { $window.localStorage.setItem('com.bolt', token); $location.path('/createProfile'); }) .catch(function (error) { $scope.errorDetected = true; $scope.signupError = "Invalid username or password"; }); }; });
angular.module('bolt.auth', []) .controller('AuthController', function ($scope, $window, $location, Auth) { $scope.user = {}; $scope.signin = function () { Auth.signin($scope.user) .then(function (session) { $window.localStorage.setItem('com.bolt', session.token); $window.localStorage.setItem('username', session.username); $window.localStorage.setItem('firstName', session.firstName); $window.localStorage.setItem('lastName', session.lastName); $window.localStorage.setItem('phone', session.phone); $window.localStorage.setItem('email', session.email); $window.localStorage.setItem('preferredDistance', session.preferredDistance); $window.localStorage.setItem('runs', session.runs); $window.localStorage.setItem('achievements', session.achievements); $location.path('/'); }) .catch(function (error) { $scope.errorDetected = true; $scope.signinError = "Hmm... we can't seem to find that username in our DB. Could it be another?"; }); }; $scope.signup = function () { Auth.signup($scope.user) .then(function (token) { $window.localStorage.setItem('com.bolt', token); $location.path('/createProfile'); }) .catch(function (error) { $scope.errorDetected = true; $scope.signupError = "Please enter both a username and a password"; }); }; });
Make the ScopeExtractorProcessor usable for the Primary Identifier This patch adds support to use the ScopeExtractorProcessor on the Primary Identifiert which is, in contrast to the other values, a string. Closes #348
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not isinstance(values, list): values = [values] if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning from .base_processor import BaseProcessor CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute' CONFIG_DEFAULT_MAPPEDATTRIBUTE = '' class ScopeExtractorProcessor(BaseProcessor): """ Extracts the scope from a scoped attribute and maps that to another attribute Example configuration: module: satosa.micro_services.attribute_processor.AttributeProcessor name: AttributeProcessor config: process: - attribute: scoped_affiliation processors: - name: ScopeExtractorProcessor module: satosa.micro_services.processors.scope_extractor_processor mapped_attribute: domain """ def process(self, internal_data, attribute, **kwargs): mapped_attribute = kwargs.get(CONFIG_KEY_MAPPEDATTRIBUTE, CONFIG_DEFAULT_MAPPEDATTRIBUTE) if mapped_attribute is None or mapped_attribute == '': raise AttributeProcessorError("The mapped_attribute needs to be set") attributes = internal_data.attributes values = attributes.get(attribute, []) if not values: raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it has no values".format(attribute)) if not any('@' in val for val in values): raise AttributeProcessorWarning("Cannot apply scope_extractor to {}, it's values are not scoped".format(attribute)) for value in values: if '@' in value: scope = value.split('@')[1] attributes[mapped_attribute] = [scope] break
Update error message with error warning
import os.path import os import shutil from dbt.task.base import ProjectOnlyTask from dbt.logger import GLOBAL_LOGGER as logger class CleanTask(ProjectOnlyTask): def __is_project_path(self, path): proj_path = os.path.abspath('.') return not os.path.commonprefix( [proj_path, os.path.abspath(path)] ) == proj_path def __is_protected_path(self, path): """ This function identifies protected paths, so as not to clean them. """ abs_path = os.path.abspath(path) protected_paths = self.config.source_paths + \ self.config.test_paths + ['.'] protected_abs_paths = [os.path.abspath for p in protected_paths] return abs_path in set(protected_abs_paths) or \ self.__is_project_path(abs_path) def run(self): """ This function takes all the paths in the target file and cleans the project paths that are not protected. """ for path in self.config.clean_targets: logger.info("Checking {}/*".format(path)) if not self.__is_protected_path(path): shutil.rmtree(path, True) logger.info(" Cleaned {}/*".format(path)) else: logger.info("ERROR: not cleaning {}/* because it is protected".format(path)) logger.info("Finished cleaning all paths.")
import os.path import os import shutil from dbt.task.base import ProjectOnlyTask from dbt.logger import GLOBAL_LOGGER as logger class CleanTask(ProjectOnlyTask): def __is_project_path(self, path): proj_path = os.path.abspath('.') return not os.path.commonprefix( [proj_path, os.path.abspath(path)] ) == proj_path def __is_protected_path(self, path): """ This function identifies protected paths, so as not to clean them. """ abs_path = os.path.abspath(path) protected_paths = self.config.source_paths + \ self.config.test_paths + ['.'] protected_abs_paths = [os.path.abspath for p in protected_paths] return abs_path in set(protected_abs_paths) or \ self.__is_project_path(abs_path) def run(self): """ This function takes all the paths in the target file and cleans the project paths that are not protected. """ for path in self.config.clean_targets: logger.info("Checking {}/*".format(path)) if not self.__is_protected_path(path): shutil.rmtree(path, True) logger.info(" Cleaned {}/*".format(path)) else: logger.info("{}/* cannot be cleaned".format(path)) logger.info("Finished cleaning all paths.")
Fix strange wording in version check docstring.
from __future__ import absolute_import import warnings from collections import namedtuple from sentry.exceptions import InvalidConfiguration class Version(namedtuple('Version', 'major minor patch')): def __str__(self): return '.'.join(map(str, self)) def make_upgrade_message(service, modality, version, hosts): return '{service} {modality} be upgraded to {version} on {hosts}.'.format( hosts=', '.join('{0} (currently {1})'.format(*i) for i in hosts), modality=modality, service=service, version=version, ) def check_versions(service, versions, required, recommended=None): """ Check that hosts fulfill version requirements. :param service: service label, such as ``Redis`` :param versions: mapping of host to ``Version`` :param required: lowest supported ``Version``. If any host does not fulfill this requirement, an ``InvalidConfiguration`` exception is raised. :param recommended: recommended version. If any host does not fulfill this requirement, a ``PendingDeprecationWarning`` is raised. """ must_upgrade = filter(lambda (host, version): required > version, versions.items()) if must_upgrade: raise InvalidConfiguration(make_upgrade_message(service, 'must', required, must_upgrade)) if recommended: should_upgrade = filter(lambda (host, version): recommended > version, versions.items()) if should_upgrade: warnings.warn( make_upgrade_message(service, 'should', recommended, should_upgrade), PendingDeprecationWarning, )
from __future__ import absolute_import import warnings from collections import namedtuple from sentry.exceptions import InvalidConfiguration class Version(namedtuple('Version', 'major minor patch')): def __str__(self): return '.'.join(map(str, self)) def make_upgrade_message(service, modality, version, hosts): return '{service} {modality} be upgraded to {version} on {hosts}.'.format( hosts=', '.join('{0} (currently {1})'.format(*i) for i in hosts), modality=modality, service=service, version=version, ) def check_versions(service, versions, required, recommended=None): """ Check that all members of mapping hosts fulfill version requirements. :param service: service label, such as ``Redis`` :param versions: mapping of host to ``Version`` :param required: lowest supported ``Version``. If any host does not fulfill this requirement, an ``InvalidConfiguration`` exception is raised. :param recommended: recommended version. If any host does not fulfill this requirement, a ``PendingDeprecationWarning`` is raised. """ must_upgrade = filter(lambda (host, version): required > version, versions.items()) if must_upgrade: raise InvalidConfiguration(make_upgrade_message(service, 'must', required, must_upgrade)) if recommended: should_upgrade = filter(lambda (host, version): recommended > version, versions.items()) if should_upgrade: warnings.warn( make_upgrade_message(service, 'should', recommended, should_upgrade), PendingDeprecationWarning, )
Use assert.ok() instead of assert.equals()
var assert = require('assert'); describe('linter', function () { var linter = require('../../lib/linter'); describe('lint', function () { it('should return array of errors', function () { var source = '.foo{ color:red; }'; var path = 'test.less'; var actual; var config = { spaceAfterPropertyColon: { enabled: true, style: 'one_space' }, spaceBeforeBrace: { enabled: true, style: 'one_space' } }; actual = linter.lint(source, path, config); assert.ok(actual.length === 2); }); }); describe('parseAST', function () { it('should return an AST', function () { var source = '.foo { color: red; }'; var ast = linter.parseAST(source); assert.ok(ast.toCSS); // If the returned object has the 'toCSS' method, we'll consider it a success }); }); });
var assert = require('assert'); describe('linter', function () { var linter = require('../../lib/linter'); describe('lint', function () { it('should return array of errors', function () { var source = '.foo{ color:red; }'; var path = 'test.less'; var actual; var config = { spaceAfterPropertyColon: { enabled: true, style: 'one_space' }, spaceBeforeBrace: { enabled: true, style: 'one_space' } }; actual = linter.lint(source, path, config); assert.equal(2, actual.length); }); }); describe('parseAST', function () { it('should return an AST', function () { var source = '.foo { color: red; }'; var ast = linter.parseAST(source); assert.ok(ast.toCSS); // If the returned object has the 'toCSS' method, we'll consider it a success }); }); });
Return results as a generator, not in a file.
"""Get secondary structure with DSSP.""" from __future__ import print_function, absolute_import import optparse import subprocess def check_output(args, stderr=None, retcode=0, input=None, *other): p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr, stdin=subprocess.PIPE if input else None, *other) stdout, stderr = p.communicate(input) if p.returncode != retcode: raise OSError("Process %s exited with code %d" % (" ".join(args), p.returncode)) return stdout def get_ss(pdb_file): out = check_output(["dssp", pdb_file]) start = False for line in out.split("\n"): if "RESIDUE AA STRUCTURE" in line: start = True elif start and len(line) > 16 and line[11] != ' ': yield line[16] if line[16] != ' ' else '-' def parse_args(): usage = """%prog <PDB file> Get secondary structure of <PDB file> with DSSP, and print the secondary structure type for each residue, one per line. """ parser = optparse.OptionParser(usage) options, args = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") return args[0] def main(): pdb_file = parse_args() for res in get_ss(pdb_file): print(res) if __name__ == '__main__': main()
"""Get secondary structure with DSSP.""" from __future__ import print_function, absolute_import import optparse import subprocess def check_output(args, stderr=None, retcode=0, input=None, *other): p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr, stdin=subprocess.PIPE if input else None, *other) stdout, stderr = p.communicate(input) if p.returncode != retcode: raise OSError("Process %s exited with code %d" % (" ".join(args), p.returncode)) return stdout def get_ss(pdb_file): out = check_output(["dssp", pdb_file]) start = False for line in out.split("\n"): if "RESIDUE AA STRUCTURE" in line: start = True elif start and len(line) > 16 and line[11] != ' ': print(line[16] if line[16] != ' ' else '-') def parse_args(): usage = """%prog <PDB file> Get secondary structure of <PDB file> with DSSP, and print the secondary structure type for each residue, one per line. """ parser = optparse.OptionParser(usage) options, args = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") return args[0] def main(): pdb_file = parse_args() get_ss(pdb_file) if __name__ == '__main__': main()
Add bottom margin to header in account > general
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import React from "react"; import { capitalize } from "lodash"; import { connect } from "react-redux"; import { Label } from "react-bootstrap"; import { Flex, FlexItem } from "../../base"; import ChangePassword from "./Password"; import { Identicon } from "../../base"; const AccountGeneral = ({ id, groups, hash }) => { const groupLabels = groups.map(groupId => <Label key={groupId} style={{marginRight: "3px"}}> {capitalize(groupId)} </Label> ); return ( <div> <Flex alignItems="stretch" style={{marginBottom: "15px"}}> <FlexItem> <Identicon hash={hash} /> </FlexItem> <FlexItem pad={10}> <h5> <strong> {id} </strong> </h5> <div> {groupLabels} </div> </FlexItem> </Flex> <ChangePassword /> </div> ); }; const mapStateToProps = (state) => { return { id: state.account.id, hash: state.account.identicon, groups: state.account.groups }; }; const Container = connect(mapStateToProps)(AccountGeneral); export default Container;
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import React from "react"; import { capitalize } from "lodash"; import { connect } from "react-redux"; import { Label } from "react-bootstrap"; import { Flex, FlexItem } from "../../base"; import ChangePassword from "./Password"; import { Identicon } from "../../base"; class AccountGeneral extends React.Component { constructor (props) { super(props); } render () { const groupLabels = this.props.groups.map(groupId => <Label key={groupId} style={{marginRight: "3px"}}> {capitalize(groupId)} </Label> ); return ( <div> <Flex alignItems="stretch"> <FlexItem> <Identicon hash={this.props.hash} /> </FlexItem> <FlexItem pad={10}> <h5> <strong> {this.props.id} </strong> </h5> <div> {groupLabels} </div> </FlexItem> </Flex> <ChangePassword /> </div> ); } } const mapStateToProps = (state) => { return { id: state.account.id, hash: state.account.identicon, groups: state.account.groups }; }; const Container = connect(mapStateToProps)(AccountGeneral); export default Container;
Fix some command line options parsing
<?php namespace CodeTool\ArtifactDownloader\UnitConfig; use CodeTool\ArtifactDownloader\EtcdClient\EtcdClient; class UnitConfig implements UnitConfigInterface { private function getOptOrEnvOrDefault($optName, $env, $default) { $opt = getopt('', [$optName . '::']); if (false !== $opt && array_key_exists($optName, $opt)) { return $opt[$optName]; } if (false !== ($envVal = getenv(sprintf('ENV_%s', $env)))) { return $envVal; } return $default; } /** * @return string */ public function getName() { return $this->getOptOrEnvOrDefault('name', 'NAME', gethostname()); } /** * @return string */ public function getConfigPath() { return $this->getOptOrEnvOrDefault('config-path', 'CONFIG_PATH', 'artifact-downloader/config'); } /** * @return string */ public function getStatusDirectoryPath() { return $this->getOptOrEnvOrDefault('status-directory', 'STATUS_DIRECTORY', 'artifact-downloader/status'); } /** * @return string */ public function getResourceCredentialsConfigPath() { return $this->getOptOrEnvOrDefault('resource-credentials', 'RESOURCE_CREDENTIALS', null); } /** * @return string */ public function getEtcdServerUrl() { return $this->getOptOrEnvOrDefault('etcd-server-url', 'ETCD_SERVER_URL', EtcdClient::DEFAULT_SERVER); } }
<?php namespace CodeTool\ArtifactDownloader\UnitConfig; use CodeTool\ArtifactDownloader\EtcdClient\EtcdClient; class UnitConfig implements UnitConfigInterface { private function getOptOrEnvOrDefault($optName, $env, $default) { $opt = getopt('', [$optName . '::']); if (false !== $opt && array_key_exists($optName, $opt)) { return $opt[$optName]; } if (false !== ($envVal = getenv(sprintf('ENV_%s', $env)))) { return $envVal; } return $default; } /** * @return string */ public function getName() { return $this->getOptOrEnvOrDefault('name', 'NAME', gethostname()); } /** * @return string */ public function getConfigPath() { return $this->getOptOrEnvOrDefault('config-path', 'CONFIG_PATH', 'artifact-downloader/config'); } /** * @return string */ public function getStatusDirectoryPath() { return $this->getOptOrEnvOrDefault('status-directory', 'STATUS_DIRECTORY', 'artifact-downloader/status'); } /** * @return string */ public function getResourceCredentialsConfigPath() { return $this->getOptOrEnvOrDefault('--resource-credentials', 'RESOURCE_CREDENTIALS', null); } /** * @return string */ public function getEtcdServerUrl() { return $this->getOptOrEnvOrDefault('--etcd-server-url', 'ETCD_SERVER_URL', EtcdClient::DEFAULT_SERVER); } }
Fix logic in path search.
import os import sys import glob import email import itertools import contextlib class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): glob_groups = map(glob.iglob, cls._search_globs(name, path)) globs = itertools.chain.from_iterable(glob_groups) return cls(next(globs)) @staticmethod def _search_globs(name, path): """ Generate search globs for locating distribution metadata in path """ for path_item in path: yield os.path.join(path_item, f'{name}-*.*-info') # in develop install, no version is present yield os.path.join(path_item, f'{name}.*-info') @classmethod def for_module(cls, mod): return cls.for_name(cls.name_for_module(mod)) @staticmethod def name_for_module(mod): return getattr(mod, '__dist_name__', mod.__name__) @property def metadata(self): return email.message_from_string( self.load_metadata('METADATA') or self.load_metadata('PKG-INFO') ) def load_metadata(self, name): fn = os.path.join(self.path, name) with contextlib.suppress(FileNotFoundError): with open(fn, encoding='utf-8') as strm: return strm.read() @property def version(self): return self.metadata['Version']
import os import sys import glob import email import itertools import contextlib class Distribution: def __init__(self, path): """ Construct a distribution from a path to the metadata dir """ self.path = path @classmethod def for_name(cls, name, path=sys.path): for path_item in path: glob_specs = ( os.path.join(path_item, f'{name}-*.*-info'), os.path.join(path_item, f'{name}.*-info'), ) globs = itertools.chain.from_iterable(map(glob.iglob, glob_specs)) match = next(globs) return cls(os.path.join(path_item, match)) @classmethod def for_module(cls, mod): return cls.for_name(cls.name_for_module(mod)) @staticmethod def name_for_module(mod): return getattr(mod, '__dist_name__', mod.__name__) @property def metadata(self): return email.message_from_string( self.load_metadata('METADATA') or self.load_metadata('PKG-INFO') ) def load_metadata(self, name): fn = os.path.join(self.path, name) with contextlib.suppress(FileNotFoundError): with open(fn, encoding='utf-8') as strm: return strm.read() @property def version(self): return self.metadata['Version']
Remove button on mobile to show static image Static images are replaced with chart Commented out as temp measure
$(function() { // if on mobile inject overlay and button elements /* if ($("body").hasClass("viewport-xs")) { var markdownChart = $('.markdown-chart'); // remove button on mobile to show static image if (markdownChart.length) { $('<div class="markdown-chart-overlay"></div>').insertAfter($('.markdown-chart')); $('<button class="btn btn--mobile-chart-show">View chart</button>').insertAfter($('.markdown-chart')); $('<button class="btn btn--mobile-chart-hide">Close chart</button>').appendTo($('.markdown-chart-overlay')); $('.btn--mobile-chart-show').click(function () { // the variables var $this = $(this), $title = $('<span class="font-size--h4">' + $this.closest('.markdown-chart-container').find('h4').text() + '</span>'), $imgSrc = $this.closest('.markdown-chart-container').find('.js-chart-image-src').attr('href'), width = 700, $img = '<img src="' + $imgSrc + '&width=' + width + '" />', $overlay = $this.closest('.markdown-chart-container').find('.markdown-chart-overlay'); // check if image has been injected already if (!$overlay.find('img').length) { $overlay.append($title); $overlay.append($img); } // show the overlay $overlay.show(); }); $('.btn--mobile-chart-hide').click(function () { $(this).closest('.markdown-chart-overlay').css('display', ''); }); } } */ });
$(function() { // if on mobile inject overlay and button elements if ($("body").hasClass("viewport-xs")) { var markdownChart = $('.markdown-chart'); if (markdownChart.length) { $('<div class="markdown-chart-overlay"></div>').insertAfter($('.markdown-chart')); $('<button class="btn btn--mobile-chart-show">View chart</button>').insertAfter($('.markdown-chart')); $('<button class="btn btn--mobile-chart-hide">Close chart</button>').appendTo($('.markdown-chart-overlay')); $('.btn--mobile-chart-show').click(function () { // the variables var $this = $(this), $title = $('<span class="font-size--h4">' + $this.closest('.markdown-chart-container').find('h4').text() + '</span>'), $imgSrc = $this.closest('.markdown-chart-container').find('.js-chart-image-src').attr('href'), width = 700, $img = '<img src="' + $imgSrc + '&width=' + width + '" />', $overlay = $this.closest('.markdown-chart-container').find('.markdown-chart-overlay'); // check if image has been injected already if (!$overlay.find('img').length) { $overlay.append($title); $overlay.append($img); } // show the overlay $overlay.show(); }); $('.btn--mobile-chart-hide').click(function () { $(this).closest('.markdown-chart-overlay').css('display', ''); }); } } });
Fix value/name ambiguity in ThingDefinition
from thinglang.lexer.symbols import LexicalGroupEnd from thinglang.lexer.symbols.base import LexicalIdentifier from thinglang.lexer.symbols.functions import LexicalDeclarationConstructor from thinglang.parser.tokens import DefinitionPairToken, BaseToken from thinglang.parser.tokens.functions import ArgumentList class ThingDefinition(DefinitionPairToken): def __contains__(self, item): return any(child.name == item for child in self.children) def __getitem__(self, item): return [child for child in self.children if child.name == item][0] def describe(self): return self.name class MethodDefinition(BaseToken): def __init__(self, slice): super(MethodDefinition, self).__init__(slice) if isinstance(slice[0], LexicalDeclarationConstructor): self.name = LexicalIdentifier.constructor() argument_list = slice[1] else: self.name = slice[1] argument_list = slice[2] if isinstance(argument_list, ArgumentList): self.arguments = argument_list else: self.arguments = ArgumentList() def describe(self): return '{}, args={}'.format(self.name, self.arguments) class MemberDefinition(BaseToken): def __init__(self, slice): super(MemberDefinition, self).__init__(slice) _, self.type, self.name = slice def describe(self): return 'has {} {}'.format(self.type, self.name)
from thinglang.lexer.symbols import LexicalGroupEnd from thinglang.lexer.symbols.base import LexicalIdentifier from thinglang.lexer.symbols.functions import LexicalDeclarationConstructor from thinglang.parser.tokens import DefinitionPairToken, BaseToken from thinglang.parser.tokens.functions import ArgumentList class ThingDefinition(DefinitionPairToken): def __contains__(self, item): return any(child.value == item for child in self.children) def __getitem__(self, item): return [child for child in self.children if child.value == item][0] def describe(self): return self.name class MethodDefinition(BaseToken): def __init__(self, slice): super(MethodDefinition, self).__init__(slice) if isinstance(slice[0], LexicalDeclarationConstructor): self.name = LexicalIdentifier.constructor() argument_list = slice[1] else: self.name = slice[1] argument_list = slice[2] if isinstance(argument_list, ArgumentList): self.arguments = argument_list else: self.arguments = ArgumentList() def describe(self): return '{}, args={}'.format(self.name, self.arguments) class MemberDefinition(BaseToken): def __init__(self, slice): super(MemberDefinition, self).__init__(slice) _, self.type, self.name = slice def describe(self): return 'has {} {}'.format(self.type, self.name)
Revert "Make service provider deferred" This reverts commit 3918b0c987b4545c414eba988b66dba1d1de5e57. Service providers with a boot method cannot be deferred! It's a mystery to me that this worked in Laravel 5.1. This fixes #50 but intentionally regresses #18. I don't think there's any way to make this service deferred; Laravel exposes no events to hook into the loading process of the validator, so we need to eagerly load and register the validator.
<?php namespace Felixkiss\UniqueWithValidator; use Illuminate\Support\ServiceProvider; class UniqueWithValidatorServiceProvider 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->loadTranslationsFrom( __DIR__ . '/../../lang', 'uniquewith-validator' ); // Registering the validator extension with the validator factory $this->app['validator']->resolver( function($translator, $data, $rules, $messages, $customAttributes = array()) { return new ValidatorExtension( $translator, $data, $rules, $messages, $customAttributes ); } ); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
<?php namespace Felixkiss\UniqueWithValidator; use Illuminate\Support\ServiceProvider; class UniqueWithValidatorServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->loadTranslationsFrom( __DIR__ . '/../../lang', 'uniquewith-validator' ); // Registering the validator extension with the validator factory $this->app['validator']->resolver( function($translator, $data, $rules, $messages, $customAttributes = array()) { return new ValidatorExtension( $translator, $data, $rules, $messages, $customAttributes ); } ); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('validator'); } }
Fix minor spelling error in cubeupload test
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import hashlib import unittest from harvester import harvester class CubeuploadTest(unittest.TestCase): def setUp(self): self.nick = "test" self.chan = '#brotherBot' self.mask = "brotherBox!~brotherBo@unaffiliated/brotherbox" self.h = harvester.HarvesterBot def test_fetch_cubeupload_share(self): msg = "http://cubeupload.com/im/YhUxlj.jpg" test_hash = "3c1a8ef650f3c3c3c2f4dd115931c0ca" c = self.h._retrieve_content(self.h, self.mask, msg, self.chan) md5 = hashlib.md5() md5.update(c[0]['content']) self.assertEqual(md5.hexdigest(), test_hash) def test_fetch_cubeupload_raw(self): msg = "http://i.cubeupload.com/YhUxlj.jpg" test_hash = "3c1a8ef650f3c3c3c2f4dd115931c0ca" c = self.h._retrieve_content(self.h, self.mask, msg, self.chan) md5 = hashlib.md5() md5.update(c[0]['content']) self.assertEqual(md5.hexdigest(), test_hash) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 #-*- coding: utf-8 -*- import hashlib import unittest from harvester import harvester class CupeuploadTest(unittest.TestCase): def setUp(self): self.nick = "test" self.chan = '#brotherBot' self.mask = "brotherBox!~brotherBo@unaffiliated/brotherbox" self.h = harvester.HarvesterBot def test_fetch_cubeupload_share(self): msg = "http://cubeupload.com/im/YhUxlj.jpg" test_hash = "3c1a8ef650f3c3c3c2f4dd115931c0ca" c = self.h._retrieve_content(self.h, self.mask, msg, self.chan) md5 = hashlib.md5() md5.update(c[0]['content']) self.assertEqual(md5.hexdigest(), test_hash) def test_fetch_cubeupload_raw(self): msg = "http://i.cubeupload.com/YhUxlj.jpg" test_hash = "3c1a8ef650f3c3c3c2f4dd115931c0ca" c = self.h._retrieve_content(self.h, self.mask, msg, self.chan) md5 = hashlib.md5() md5.update(c[0]['content']) self.assertEqual(md5.hexdigest(), test_hash) if __name__ == '__main__': unittest.main()
Change method argument type (entity -> interface)
<?php namespace Wizin\Bundle\SimpleCmsBundle\Repository; use Doctrine\ORM\EntityRepository; use Wizin\Bundle\SimpleCmsBundle\Entity\ContentInterface; /** * ContentRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ContentRepository extends EntityRepository { /** * @param string $pathInfo * @return null|\Wizin\Bundle\SimpleCmsBundle\Entity\ContentInterface */ public function retrieveEnableContent($pathInfo) { $criteria = [ 'pathInfo' => $pathInfo, 'active' => true, ]; return $this->findOneBy($criteria); } /** * @param ContentInterface $content * @return bool */ public function isDuplicated(ContentInterface $content) { $queryBuilder = $this->getEntityManager()->createQueryBuilder(); $queryBuilder ->select('content') ->from($this->getClassName(), 'content') ->where('content.pathInfo = :pathInfo') ->setParameter('pathInfo', $content->getPathInfo()) ; if (is_null($content->getId()) === false) { $queryBuilder ->andWhere('content.id != :id') ->setParameter('id', $content->getId()) ; } $entity = $queryBuilder->getQuery()->getOneOrNullResult(); return (is_null($entity) === false); } }
<?php namespace Wizin\Bundle\SimpleCmsBundle\Repository; use Doctrine\ORM\EntityRepository; use Wizin\Bundle\SimpleCmsBundle\Entity\Content; /** * ContentRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ContentRepository extends EntityRepository { /** * @param string $pathInfo * @return null|\Wizin\Bundle\SimpleCmsBundle\Entity\Content */ public function retrieveEnableContent($pathInfo) { $criteria = [ 'pathInfo' => $pathInfo, 'active' => true, ]; return $this->findOneBy($criteria); } /** * @param Content $content * @return bool */ public function isDuplicated(Content $content) { $queryBuilder = $this->getEntityManager()->createQueryBuilder(); $queryBuilder ->select('content') ->from($this->getClassName(), 'content') ->where('content.pathInfo = :pathInfo') ->setParameter('pathInfo', $content->getPathInfo()) ; if (is_null($content->getId()) === false) { $queryBuilder ->andWhere('content.id != :id') ->setParameter('id', $content->getId()) ; } $entity = $queryBuilder->getQuery()->getOneOrNullResult(); return (is_null($entity) === false); } }
Change admin middleware to reflect 5.3 changes Generated resource route for groupController now calls the variable group, not groupId
<?php namespace JamylBot\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\Guard; use JamylBot\Group; class MustBeAdmin { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect('/home')->with('auth_message', 'Must be logged in.'); } } /** @var \JamylBot\User $user */ $user = $this->auth->user(); if ($user->admin) { return $next($request); } $groupId = $request->group ? $request->group : $request->groups; if ($groupId) { /** @var Group $group */ $group = Group::find($groupId); if ($group->isOwner($user->id)) { return $next($request); } } if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect('/home')->with('auth_message', 'Access Denied'); } } }
<?php namespace JamylBot\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\Guard; use JamylBot\Group; class MustBeAdmin { /** * The Guard implementation. * * @var Guard */ protected $auth; /** * Create a new filter instance. * * @param Guard $auth */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->auth->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect('/home')->with('auth_message', 'Must be logged in.'); } } /** @var \JamylBot\User $user */ $user = $this->auth->user(); if ($user->admin) { return $next($request); } $groupId = $request->groupId ? $request->groupId : $request->groups; if ($groupId) { /** @var Group $group */ $group = Group::find($groupId); if ($group->isOwner($user->id)) { return $next($request); } } if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect('/home')->with('auth_message', 'Access Denied'); } } }
Add support of node >=6 grunt tasks
'use strict'; var helper = require('../helper'); /** * Defines all linting task. * * @function * @memberof! GruntLint * @private * @param {Object} grunt - The grunt instance * @returns {Object} Grunt config object */ module.exports = function (grunt) { grunt.registerTask('lint', 'Linting tasks.', [ 'concurrent:lint' ]); var lintTasks = [ 'markdownlint:full', 'htmlhint:full', 'htmllint:full', 'csslint:full', 'jsonlint:full', 'jshint:full', 'jshint:test', 'jscs:full', 'jscs:test', 'filenames:full' ]; /*istanbul ignore next*/ if (global.build.options.buildConfig.es6Support) { lintTasks.push('yaml_validator:full'); if (global.build.options.buildConfig.nodeMajorVersion >= 6) { lintTasks.push('stylelint:full'); } } /*istanbul ignore next*/ if (global.build.options.buildConfig.jslintEnabled) { lintTasks = lintTasks.concat([ 'jslint:full', 'jslint:test' ]); } /*istanbul ignore else*/ if (helper.isESlintSupported(global.build.options.buildConfig)) { lintTasks = lintTasks.concat([ 'eslint:full', 'eslint:test' ]); } return { tasks: { concurrent: { lint: { target: lintTasks } } } }; };
'use strict'; var helper = require('../helper'); /** * Defines all linting task. * * @function * @memberof! GruntLint * @private * @param {Object} grunt - The grunt instance * @returns {Object} Grunt config object */ module.exports = function (grunt) { grunt.registerTask('lint', 'Linting tasks.', [ 'concurrent:lint' ]); var lintTasks = [ 'markdownlint:full', 'htmlhint:full', 'htmllint:full', 'csslint:full', 'jsonlint:full', 'jshint:full', 'jshint:test', 'jscs:full', 'jscs:test', 'filenames:full' ]; /*istanbul ignore next*/ if (global.build.options.buildConfig.es6Support) { lintTasks = lintTasks.concat([ 'stylelint:full', 'yaml_validator:full' ]); } /*istanbul ignore next*/ if (global.build.options.buildConfig.jslintEnabled) { lintTasks = lintTasks.concat([ 'jslint:full', 'jslint:test' ]); } /*istanbul ignore else*/ if (helper.isESlintSupported(global.build.options.buildConfig)) { lintTasks = lintTasks.concat([ 'eslint:full', 'eslint:test' ]); } return { tasks: { concurrent: { lint: { target: lintTasks } } } }; };
Exit /search if no area of interest Previously we would query APIs with the bounding box of the entire map in view. Now as we prepare to switch to searching for the area of interest only, we disable being able to come to this page without an area of interest drawn already.
"use strict"; var App = require('../app'), router = require('../router').router, coreUtils = require('../core/utils'), models = require('./models'), views = require('./views'); var DataCatalogController = { dataCatalogPrepare: function() { if (!App.map.get('areaOfInterest')) { router.navigate('', { trigger: true }); return false; } }, dataCatalog: function() { App.map.setDataCatalogSize(); App.state.set({ 'active_page': coreUtils.dataCatalogPageTitle, }); var form = new models.SearchForm(); var catalogs = new models.Catalogs([ new models.Catalog({ id: 'cinergi', name: 'CINERGI', active: true, results: new models.Results() }), new models.Catalog({ id: 'hydroshare', name: 'HydroShare', results: new models.Results() }), new models.Catalog({ id: 'cuahsi', name: 'WDC', description: 'Optional catalog description here...', results: new models.Results() }) ]); var view = new views.DataCatalogWindow({ model: form, collection: catalogs }); App.rootView.sidebarRegion.show(view); } }; module.exports = { DataCatalogController: DataCatalogController, };
"use strict"; var App = require('../app'), coreUtils = require('../core/utils'), models = require('./models'), views = require('./views'); var DataCatalogController = { dataCatalog: function() { App.map.setDataCatalogSize(); App.state.set({ 'active_page': coreUtils.dataCatalogPageTitle, }); var form = new models.SearchForm(); var catalogs = new models.Catalogs([ new models.Catalog({ id: 'cinergi', name: 'CINERGI', active: true, results: new models.Results() }), new models.Catalog({ id: 'hydroshare', name: 'HydroShare', results: new models.Results() }), new models.Catalog({ id: 'cuahsi', name: 'WDC', description: 'Optional catalog description here...', results: new models.Results() }) ]); var view = new views.DataCatalogWindow({ model: form, collection: catalogs }); App.rootView.sidebarRegion.show(view); } }; module.exports = { DataCatalogController: DataCatalogController, };
Set codemirror size when opening modal.
"use strict"; jsns.run([ "htmlrest.domquery", "htmlrest.storage", "htmlrest.rest", "htmlrest.controller", "htmlrest.widgets.navmenu", "edity.pageSourceSync" ], function (exports, module, domQuery, storage, rest, controller, navmenu, sourceSync) { function EditSourceController(bindings) { var editSourceDialog = bindings.getToggle('dialog'); var codemirrorElement = domQuery.first('#editSourceTextarea'); var cm = CodeMirror.fromTextArea(codemirrorElement, { lineNumbers: true, mode: "htmlmixed", theme: "edity" }); function apply(evt) { evt.preventDefault(); editSourceDialog.off(); sourceSync.setHtml(cm.getValue()); } this.apply = apply; function NavItemController() { function edit() { editSourceDialog.on(); cm.setSize(null, window.innerHeight - 250); cm.setValue(sourceSync.getHtml()); setTimeout(function () { cm.refresh(); }, 500); } this.edit = edit; } var editMenu = navmenu.getNavMenu("edit-nav-menu-items"); editMenu.add("EditSourceNavItem", NavItemController); } controller.create("editSource", EditSourceController); });
"use strict"; jsns.run([ "htmlrest.domquery", "htmlrest.storage", "htmlrest.rest", "htmlrest.controller", "htmlrest.widgets.navmenu", "edity.pageSourceSync" ], function (exports, module, domQuery, storage, rest, controller, navmenu, sourceSync) { function EditSourceController(bindings) { var editSourceDialog = bindings.getToggle('dialog'); var codemirrorElement = domQuery.first('#editSourceTextarea'); var cm = CodeMirror.fromTextArea(codemirrorElement, { lineNumbers: true, mode: "htmlmixed", theme: "edity" }); function apply(evt) { evt.preventDefault(); editSourceDialog.off(); sourceSync.setHtml(cm.getValue()); } this.apply = apply; function NavItemController() { function edit() { editSourceDialog.on(); cm.setValue(sourceSync.getHtml()); setTimeout(function () { cm.refresh(); }, 500); } this.edit = edit; } var editMenu = navmenu.getNavMenu("edit-nav-menu-items"); editMenu.add("EditSourceNavItem", NavItemController); } controller.create("editSource", EditSourceController); });
Mark apple receipt expiration time as read only.
import hashlib import logging from django.utils.translation import ugettext from rest_framework import serializers from know_me import models, subscriptions logger = logging.getLogger(__name__) class AppleSubscriptionSerializer(serializers.ModelSerializer): """ Serializer for an Apple subscription. """ class Meta: fields = ( "id", "time_created", "time_updated", "expiration_time", "receipt_data", ) model = models.SubscriptionAppleData read_only_fields = ("expiration_time",) def validate(self, data): """ Ensure the provided receipt data corresponds to a valid Apple receipt. Returns: The validated data. """ validated_data = data.copy() receipt_data = validated_data["receipt_data"] data_hash = hashlib.sha256(receipt_data.encode()).hexdigest() if models.SubscriptionAppleData.objects.filter( receipt_data_hash=data_hash ).exists(): logger.warning( "Duplicate Apple receipt submitted with hash: %s", data_hash ) raise serializers.ValidationError( { "receipt_data": ugettext( "This receipt has already been used." ) } ) try: receipt = subscriptions.validate_apple_receipt(receipt_data) except subscriptions.ReceiptException as e: raise serializers.ValidationError( code=e.code, detail={"receipt_data": e.msg} ) validated_data["expiration_time"] = receipt.expires_date return validated_data
import hashlib import logging from django.utils.translation import ugettext from rest_framework import serializers from know_me import models, subscriptions logger = logging.getLogger(__name__) class AppleSubscriptionSerializer(serializers.ModelSerializer): """ Serializer for an Apple subscription. """ class Meta: fields = ( "id", "time_created", "time_updated", "expiration_time", "receipt_data", ) model = models.SubscriptionAppleData def validate(self, data): """ Ensure the provided receipt data corresponds to a valid Apple receipt. Returns: The validated data. """ validated_data = data.copy() receipt_data = validated_data["receipt_data"] data_hash = hashlib.sha256(receipt_data.encode()).hexdigest() if models.SubscriptionAppleData.objects.filter( receipt_data_hash=data_hash ).exists(): logger.warning( "Duplicate Apple receipt submitted with hash: %s", data_hash ) raise serializers.ValidationError( { "receipt_data": ugettext( "This receipt has already been used." ) } ) try: receipt = subscriptions.validate_apple_receipt(receipt_data) except subscriptions.ReceiptException as e: raise serializers.ValidationError( code=e.code, detail={"receipt_data": e.msg} ) validated_data["expiration_time"] = receipt.expires_date return validated_data
Remove check for Java version.
package ch.ethz.scu.obit.at; import javax.swing.JOptionPane; import ch.ethz.scu.obit.at.gui.AnnotationToolWindow; import ch.ethz.scu.obit.common.settings.GlobalSettingsManager; /** * AnnotationTool is an application to drive the import of data from the * acquisition stations into openBIS. * @author Aaron Ponti */ public class AnnotationTool { /** * @param args Ignored */ public static void main(String[] args) { // Check whether the application has been set up properly and it is ready // to be used. try { GlobalSettingsManager.isConfigurationValid(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Initialization error", JOptionPane.WARNING_MESSAGE); System.exit(0); } // Open the main window and run the scan in the background javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Create the Window and scan user's data folder and // openBIS structure. final AnnotationToolWindow w = new AnnotationToolWindow(); // Scan data folder and openBIS w.scan(); } }); } }
package ch.ethz.scu.obit.at; import java.lang.management.ManagementFactory; import javax.swing.JOptionPane; import ch.ethz.scu.obit.at.gui.AnnotationToolWindow; import ch.ethz.scu.obit.common.settings.GlobalSettingsManager; /** * AnnotationTool is an application to drive the import of data from the * acquisition stations into openBIS. * @author Aaron Ponti */ public class AnnotationTool { /** * @param args Ignored */ public static void main(String[] args) { // Make sure we are running on JRE 8 or newer try { double version = Double.parseDouble( ManagementFactory.getRuntimeMXBean().getSpecVersion()); if (version < 1.8) { JOptionPane.showMessageDialog(null, "Sorry, Annotation Tool requires Java 8 or newer.", "Minimum JRE version not satisfied", JOptionPane.WARNING_MESSAGE); System.exit(0); } } catch (Exception e) { // We proceed } // Check whether the application has been set up properly and it is ready // to be used. try { GlobalSettingsManager.isConfigurationValid(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Initialization error", JOptionPane.WARNING_MESSAGE); System.exit(0); } // Open the main window and run the scan in the background javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Create the Window and scan user's data folder and // openBIS structure. final AnnotationToolWindow w = new AnnotationToolWindow(); // Scan data folder and openBIS w.scan(); } }); } }
Return promise instead of full deferred
<?php namespace React\Whois; use Promise\Deferred as Deferred; use React\Curry\Util as Curry; use React\Dns\Resolver\Resolver; class Client { private $dns; private $connFactory; public function __construct(Resolver $dns, $connFactory) { $this->dns = $dns; $this->connFactory = $connFactory; } public function query($domain, $callback) { $this ->resolveWhoisServer($domain) ->then(Curry::bind(array($this, 'queryWhoisServer'), $domain)) ->then($callback); } public function resolveWhoisServer($domain) { $deferred = new Deferred(); $tld = substr(strrchr($domain, '.'), 1); $target = $tld.'.whois-servers.net'; $this->dns->resolve($target, array($deferred, 'resolve')); return $deferred->promise(); } public function queryWhoisServer($domain, $ip) { $deferred = new Deferred(); $result = ''; $conn = call_user_func($this->connFactory, $ip); $conn->write("$domain\r\n"); $conn->on('data', function ($data) use (&$result) { $result .= $data; }); $conn->on('close', function () use (&$result, $deferred) { $result = str_replace("\r\n", "\n", $result); $deferred->resolve($result); }); return $deferred->promise(); } }
<?php namespace React\Whois; use Promise\Deferred as Deferred; use React\Curry\Util as Curry; use React\Dns\Resolver\Resolver; class Client { private $dns; private $connFactory; public function __construct(Resolver $dns, $connFactory) { $this->dns = $dns; $this->connFactory = $connFactory; } public function query($domain, $callback) { $this ->resolveWhoisServer($domain) ->then(Curry::bind(array($this, 'queryWhoisServer'), $domain)) ->then($callback); } public function resolveWhoisServer($domain) { $deferred = new Deferred(); $tld = substr(strrchr($domain, '.'), 1); $target = $tld.'.whois-servers.net'; $this->dns->resolve($target, array($deferred, 'resolve')); return $deferred; } public function queryWhoisServer($domain, $ip) { $deferred = new Deferred(); $result = ''; $conn = call_user_func($this->connFactory, $ip); $conn->write("$domain\r\n"); $conn->on('data', function ($data) use (&$result) { $result .= $data; }); $conn->on('close', function () use (&$result, $deferred) { $result = str_replace("\r\n", "\n", $result); $deferred->resolve($result); }); return $deferred; } }
Use correct db settings in populate job postings
var config = require('../../app/config') , models = require('../../app/models') , logger = require('../../app/logger'); var mongoose = require('mongoose'), fs = require('fs'); /** * Setup database */ var dbSettings = config.dbSettings; var db = mongoose.createConnection(dbSettings.host , dbSettings.database , dbSettings.port); db.on('error', function(err) { logger.error("DB error", err); }); db.on('connected', function() { logger.info("Connected to mongodb://%s/%s:%s", db.host , db.name , db.port); }); db.on('disconnected', function() { logger.warn("DB connection has been lost!") }); db.on('reconnected', function() { logger.info("DB connection has been restarted!"); }); db.on('close', function() { logger.warn("DB connection has been closed!"); }); // Register models models.register(db); var postsRaw = JSON.parse(fs.readFileSync('MOCK_JOB_POSTINGS.json', 'utf8')); var JobPosting = models.jobPosting(); var savePost = function(postRaw) { var post = new JobPosting(postRaw); post.save(); }; postsRaw.forEach(savePost); logger.info("DB successfully populated!"); db.close();
var config = require('../../app/config') , models = require('../../app/models') , logger = require('../../app/logger'); var mongoose = require('mongoose'), fs = require('fs'); /** * Setup database */ var dbSettings = config.dbSettings; var dbTestSettings = config.dbTestSettings; var db = mongoose.createConnection(dbTestSettings.host , dbTestSettings.database , dbTestSettings.port); db.on('error', function(err) { logger.error("DB error", err); }); db.on('connected', function() { logger.info("Connected to mongodb://%s/%s:%s", db.host , db.name , db.port); }); db.on('disconnected', function() { logger.warn("DB connection has been lost!") }); db.on('reconnected', function() { logger.info("DB connection has been restarted!"); }); db.on('close', function() { logger.warn("DB connection has been closed!"); }); // Register models models.register(db); var postsRaw = JSON.parse(fs.readFileSync('MOCK_JOB_POSTINGS.json', 'utf8')); var JobPosting = models.jobPosting(); var savePost = function(postRaw) { var post = new JobPosting(postRaw); post.save(); }; postsRaw.forEach(savePost); logger.info("DB successfully populated!"); db.close();
Fix to a problem with a rule detected implementing the tests
/** * Tries to detect RegExp's created from non-literal strings. * @author Jon Lamendola */ //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { "use strict"; var getSource = function(token) { return token.loc.start.line + ': ' + context.getSourceLines().slice(token.loc.start.line - 1, token.loc.end.line).join('\n\t'); } return { "NewExpression": function(node) { if (node.callee.name === 'RegExp') { var args = node.arguments; if (args && args.length > 0 && args[0].type !== 'Literal') { var token = context.getTokens(node)[0]; return context.report(node, 'Found non-literal argument to RegExp Constructor\n\t' + getSource(token)); } } } } }
/** * Tries to detect RegExp's created from non-literal strings. * @author Jon Lamendola */ //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { "use strict"; var getSource = function(token) { return token.loc.start.line + ': ' + context.getSourceLines().slice(token.loc.start.line - 1, token.loc.end.line).join('\n\t'); } return { "CallExpression": function(node) { if (node.callee.name === 'RegExp') { var args = node.arguments; if (args && args.length > 0 && args[0].type !== 'Literal') { var token = context.getTokens(node)[0]; return context.report(node, 'found non-literal argument to RegExp Constructor\n\t' + getSource(token)); } } } } }
Remove redundant property in web pack config
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'cheap-eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './example/index', './src/js/simple-list-item-selector', ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'umd', library: 'SimpleListItemSelector' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: './example/index.html' }) ], module: { loaders: [{ test: /\.html$/, loader: "raw-loader" }, { exclude: /node_modules/, test: /\.js$/, loaders: ['babel-loader'] }], }, devServer: { contentBase: path.join(__dirname, "dist"), //publicPath: path.join(__dirname, "dist") hot: true } }
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'cheap-eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './example/index', './src/js/simple-list-item-selector', ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', libraryTarget: 'umd', library: 'SimpleListItemSelector' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: './example/index.html', inject: 'body', }) ], module: { loaders: [{ test: /\.html$/, loader: "raw-loader" }, { exclude: /node_modules/, test: /\.js$/, loaders: ['babel-loader'] }], }, devServer: { contentBase: path.join(__dirname, "dist"), //publicPath: path.join(__dirname, "dist") hot: true } }
Use with handler to safely close the server socket and connection
import threading import socket NODE_RED_SERVER_PORT = 4445 NODE_RED_CLIENT_PORT = 4444 class NodeRedDoorbellServerThread(threading.Thread): """ Get doorbell triggers from NodeRed. """ def __init__(self, intercom): super(NodeRedDoorbellServerThread, self).__init__() self.intercom = intercom def run(self): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket: self.running = True self.server_socket.bind(('', NODE_RED_SERVER_PORT)) self.server_socket.listen(1) while self.running: conn, addr = self.server_socket.accept() with conn: while self.running: data = conn.recv(1024) if not data: print("no data breaking") break else: self.intercom.onBellPressed() class NodeRedDoorOpenClient(): """ Send open door commands to NodeRed. """ def __init__(self): super(NodeRedDoorOpenClient, self).__init__() self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect(("127.0.0.1", NODE_RED_CLIENT_PORT)) def sendOpenDoor(self): self.client_socket.send(b'open')
import threading import socket NODE_RED_SERVER_PORT = 4445 NODE_RED_CLIENT_PORT = 4444 class NodeRedDoorbellServerThread(threading.Thread): """ Get doorbell triggers from NodeRed. """ def __init__(self, intercom): super(NodeRedDoorbellServerThread, self).__init__() self.intercom = intercom self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.running = True def run(self): self.server_socket.bind(('', NODE_RED_SERVER_PORT)) self.server_socket.listen(1) conn, addr = self.server_socket.accept() while self.running: data = conn.recv(1024) if not data: print("no data breaking") break else: self.intercom.onBellPressed() conn.close() class NodeRedDoorOpenClient(): """ Send open door commands to NodeRed. """ def __init__(self): super(NodeRedDoorOpenClient, self).__init__() self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect(("127.0.0.1", NODE_RED_CLIENT_PORT)) def sendOpenDoor(self): self.client_socket.send(b'open')
Allow back None as identifier
from tornadowebapi.traitlets import HasTraits class Resource(HasTraits): """A model representing a resource in our system. Must be reimplemented for the specific resource in our domain, as well as specifying its properties with traitlets. The following metadata in the specified traitlets are accepted: - optional bool, default False. If True, the information can be omitted from the representation when creating. If False, the information must be present, or an error BadRepresentation will be raised. The resource is always identified via its collection name, and its identifier. Both will end up in the URL, like so /collection_name/identifier/ """ def __init__(self, identifier, *args, **kwargs): self.identifier = identifier super(Resource, self).__init__(*args, **kwargs) @classmethod def collection_name(cls): """Identifies the name of the collection. By REST convention, it is a plural form of the class name, so the default is the name of the class, lowercase, and with an "s" added at the end. Override this method to return a better pluralization. """ return cls.__name__.lower() + "s" @property def identifier(self): return self._identifier @identifier.setter def identifier(self, value): if not (value is None or isinstance(value, str)): raise ValueError("Identifier must be a string. Got {}".format( type(value) )) self._identifier = value
from tornadowebapi.traitlets import HasTraits class Resource(HasTraits): """A model representing a resource in our system. Must be reimplemented for the specific resource in our domain, as well as specifying its properties with traitlets. The following metadata in the specified traitlets are accepted: - optional bool, default False. If True, the information can be omitted from the representation when creating. If False, the information must be present, or an error BadRepresentation will be raised. The resource is always identified via its collection name, and its identifier. Both will end up in the URL, like so /collection_name/identifier/ """ def __init__(self, identifier, *args, **kwargs): self.identifier = identifier super(Resource, self).__init__(*args, **kwargs) @classmethod def collection_name(cls): """Identifies the name of the collection. By REST convention, it is a plural form of the class name, so the default is the name of the class, lowercase, and with an "s" added at the end. Override this method to return a better pluralization. """ return cls.__name__.lower() + "s" @property def identifier(self): return self._identifier @identifier.setter def identifier(self, value): if not isinstance(value, str): raise ValueError("Identifier must be a string. Got {}".format( type(value) )) self._identifier = value
Use ProfileResponse instead of Response
<?php namespace Omnipay\Beanstream\Message; abstract class AbstractProfileRequest extends AbstractRequest { protected $endpoint = 'https://www.beanstream.com/api/v1/profiles'; public function getProfileId() { return $this->getParameter('profile_id'); } public function setProfileId($value) { return $this->setParameter('profile_id', $value); } public function getCardId() { return $this->getParameter('card_id'); } public function setCardId($value) { return $this->setParameter('card_id', $value); } public function getComment() { return $this->getParameter('comment'); } public function setComment($value) { return $this->setParameter('comment', $value); } public function sendData($data) { $header = base64_encode($this->getMerchantId() . ':' . $this->getApiPasscode()); if (!empty($data)) { $httpResponse = $this->httpClient->request( $this->getHttpMethod(), $this->getEndpoint(), [ 'Content-Type' => 'application/json', 'Authorization' => 'Passcode ' . $header, ], json_encode($data) ); } else { $httpResponse = $this->httpClient->request( $this->getHttpMethod(), $this->getEndpoint(), [ 'Content-Type' => 'application/json', 'Authorization' => 'Passcode ' . $header, ] ); } return $this->response = new ProfileResponse($this, $httpResponse->getBody()->getContents()); } }
<?php namespace Omnipay\Beanstream\Message; abstract class AbstractProfileRequest extends AbstractRequest { protected $endpoint = 'https://www.beanstream.com/api/v1/profiles'; public function getProfileId() { return $this->getParameter('profile_id'); } public function setProfileId($value) { return $this->setParameter('profile_id', $value); } public function getCardId() { return $this->getParameter('card_id'); } public function setCardId($value) { return $this->setParameter('card_id', $value); } public function getComment() { return $this->getParameter('comment'); } public function setComment($value) { return $this->setParameter('comment', $value); } public function sendData($data) { $header = base64_encode($this->getMerchantId() . ':' . $this->getApiPasscode()); if (!empty($data)) { $httpResponse = $this->httpClient->request( $this->getHttpMethod(), $this->getEndpoint(), [ 'Content-Type' => 'application/json', 'Authorization' => 'Passcode ' . $header, ], json_encode($data) ); } else { $httpResponse = $this->httpClient->request( $this->getHttpMethod(), $this->getEndpoint(), [ 'Content-Type' => 'application/json', 'Authorization' => 'Passcode ' . $header, ] ); } return $this->response = new Response($this, $httpResponse->getBody()->getContents()); } }
Add processcalaccessdata to update routine
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) class Command(updatecommand): """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( "--publish", action="store_true", dest="publish", default=False, help="Publish baked content" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) call_command( 'processcalaccessdata', verbosity=self.verbosity, ) self.header('Creating latest file links') call_command('createlatestlinks') self.header('Baking downloads-website content') call_command('build') if options['publish']: self.header('Publishing baked content to S3 bucket.') call_command('publish') self.success("Done!")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) class Command(updatecommand): """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( "--publish", action="store_true", dest="publish", default=False, help="Publish baked content" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) self.header('Creating latest file links') call_command('createlatestlinks') self.header('Baking downloads-website content') call_command('build') if options['publish']: self.header('Publishing baked content to S3 bucket.') call_command('publish') self.success("Done!")
Add a "valid shipping address check" to account for VAT discrepancies If we get a phone number and a city/country combination that yield incompatible VAT results, we need to flag this to the user. The best place to do this is, ironically, the shipping address check.
from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from oscar.apps.checkout import session, exceptions from oscar_vat_moss import vat class CheckoutSessionMixin(session.CheckoutSessionMixin): def build_submission(self, **kwargs): submission = super(CheckoutSessionMixin, self).build_submission( **kwargs) assess_tax = (submission['shipping_method'] and submission['shipping_address'] and submission['shipping_address'].phone_number) if assess_tax: try: vat.apply_to(submission) except vat.VATAssessmentException as e: raise exceptions.FailedPreCondition( url=reverse('checkout:shipping-address'), message=_(str(e)) ) # Recalculate order total to ensure we have a tax-inclusive total submission['order_total'] = self.get_order_totals( submission['basket'], submission['shipping_charge']) return submission def check_a_valid_shipping_address_is_captured(self): super(CheckoutSessionMixin, self) shipping_address = self.get_shipping_address( basket=self.request.basket) try: vat.lookup_vat_for_shipping_address(shipping_address) except vat.VATAssessmentException as e: message = _("%s. Please try again." % str(e)) raise exceptions.FailedPreCondition( url=reverse('checkout:shipping-address'), message=message ) def get_context_data(self, **kwargs): ctx = super(CheckoutSessionMixin, self).get_context_data(**kwargs) # Oscar's checkout templates look for this variable which specifies to # break out the tax totals into a separate subtotal. ctx['show_tax_separately'] = True return ctx
from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from oscar.apps.checkout import session, exceptions from oscar_vat_moss import vat class CheckoutSessionMixin(session.CheckoutSessionMixin): def build_submission(self, **kwargs): submission = super(CheckoutSessionMixin, self).build_submission( **kwargs) assess_tax = (submission['shipping_method'] and submission['shipping_address'] and submission['shipping_address'].phone_number) if assess_tax: try: vat.apply_to(submission) except vat.VATAssessmentException as e: raise exceptions.FailedPreCondition( url=reverse('checkout:shipping-address'), message=_(str(e)) ) # Recalculate order total to ensure we have a tax-inclusive total submission['order_total'] = self.get_order_totals( submission['basket'], submission['shipping_charge']) return submission def get_context_data(self, **kwargs): ctx = super(CheckoutSessionMixin, self).get_context_data(**kwargs) # Oscar's checkout templates look for this variable which specifies to # break out the tax totals into a separate subtotal. ctx['show_tax_separately'] = True return ctx
Add request invalidation, receivedAt to board reducer
import initialState from './initialState'; import { BOARD_REQUESTED, BOARD_LOADED, BOARD_DESTROYED, BOARD_SCROLLED_BOTTOM, BOARD_FILTER, BOARD_INVALIDATED } from '../constants' export default function (state = initialState.board, action) { switch (action.type) { case BOARD_REQUESTED: return Object.assign({}, state, { isFetching: true, didInvalidate: false }) case BOARD_INVALIDATED: return Object.assign({}, state, { didInvalidate: true }) case BOARD_LOADED: return Object.assign({}, state, { posts: action.posts, receivedAt: action.receivedAt, isFetching: false }) case BOARD_DESTROYED: return Object.assign({}, state, { posts: [] }) case BOARD_SCROLLED_BOTTOM: return Object.assign({}, state, { limit: action.payload }) case BOARD_FILTER: return Object.assign({}, state, { filterWord: action.payload || null }) default: return state } }
import initialState from './initialState'; import { BOARD_REQUESTED, BOARD_LOADED, BOARD_DESTROYED, BOARD_SCROLLED_BOTTOM, BOARD_FILTER } from '../constants' export default function (state = initialState.board, action) { switch (action.type) { case BOARD_REQUESTED: return Object.assign({}, state, { isFetching: true, requestType: action.type // for logging error to user...? }) case BOARD_LOADED: return Object.assign({}, state, { posts: action.payload, isFetching: false }) case BOARD_DESTROYED: return Object.assign({}, state, { posts: [] }) case BOARD_SCROLLED_BOTTOM: return Object.assign({}, state, { limit: action.payload }) case BOARD_FILTER: return Object.assign({}, state, { filterWord: action.payload || null }) default: return state } }
Fix failure with Symfony 2.8
<?php declare(strict_types=1); namespace Paraunit\Process; use Paraunit\Configuration\EnvVariables; use Paraunit\Configuration\PHPUnitConfig; use Paraunit\Configuration\TempFilenameFactory; use Symfony\Component\Process\Process; /** * Class ProcessFactory * @package Paraunit\Process */ class ProcessFactory { /** @var CommandLine */ private $cliCommand; /** @var string[] */ private $baseCommandLine; /** @var string[] */ private $environmentVariables; /** * ProcessFactory constructor. * @param CommandLine $cliCommand * @param PHPUnitConfig $phpunitConfig * @param TempFilenameFactory $tempFilenameFactory */ public function __construct( CommandLine $cliCommand, PHPUnitConfig $phpunitConfig, TempFilenameFactory $tempFilenameFactory ) { $this->cliCommand = $cliCommand; $this->baseCommandLine = array_merge($this->cliCommand->getExecutable(), $this->cliCommand->getOptions($phpunitConfig)); $this->environmentVariables = [ EnvVariables::LOG_DIR => $tempFilenameFactory->getPathForLog(), ]; } public function create(string $testFilePath): AbstractParaunitProcess { $process = new Process( array_merge($this->baseCommandLine, [$testFilePath], $this->cliCommand->getSpecificOptions($testFilePath)), null, $this->environmentVariables ); if (method_exists($process, 'inheritEnvironmentVariables')) { // method added in 3.0 $process->inheritEnvironmentVariables(); } return new SymfonyProcessWrapper($process, $testFilePath); } }
<?php declare(strict_types=1); namespace Paraunit\Process; use Paraunit\Configuration\EnvVariables; use Paraunit\Configuration\PHPUnitConfig; use Paraunit\Configuration\TempFilenameFactory; use Symfony\Component\Process\Process; /** * Class ProcessFactory * @package Paraunit\Process */ class ProcessFactory { /** @var CommandLine */ private $cliCommand; /** @var string[] */ private $baseCommandLine; /** @var string[] */ private $environmentVariables; /** * ProcessFactory constructor. * @param CommandLine $cliCommand * @param PHPUnitConfig $phpunitConfig * @param TempFilenameFactory $tempFilenameFactory */ public function __construct( CommandLine $cliCommand, PHPUnitConfig $phpunitConfig, TempFilenameFactory $tempFilenameFactory ) { $this->cliCommand = $cliCommand; $this->baseCommandLine = array_merge($this->cliCommand->getExecutable(), $this->cliCommand->getOptions($phpunitConfig)); $this->environmentVariables = [ EnvVariables::LOG_DIR => $tempFilenameFactory->getPathForLog(), ]; } public function create(string $testFilePath): AbstractParaunitProcess { $process = new Process( array_merge($this->baseCommandLine, [$testFilePath], $this->cliCommand->getSpecificOptions($testFilePath)), null, $this->environmentVariables ); $process->inheritEnvironmentVariables(); return new SymfonyProcessWrapper($process, $testFilePath); } }
Add vimeo as className in FeedTypeAdmin.php
<?php namespace Protalk\AdminBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class FeedtypeAdmin extends Admin { /** * Default Datagrid values * * @var array */ protected $datagridValues = array( '_page' => 1, '_sort_order' => 'ASC', '_sort_by' => 'name' ); protected function configureFormFields(FormMapper $formMapper) { $formMapper->add('name') ->add( 'className', 'choice', array( 'choices' => array( 'feedburner' => 'feedburner', 'rss' => 'rss', 'dpc' => 'dpc', 'aws' => 'aws', 'bliptv' => 'bliptv', 'youtube' => 'youtube', 'vimeo' => 'vimeo' ) ) ); } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper->add('name'); } protected function configureListFields(ListMapper $listMapper) { $listMapper->addIdentifier('name')->add('className'); } }
<?php namespace Protalk\AdminBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; class FeedtypeAdmin extends Admin { /** * Default Datagrid values * * @var array */ protected $datagridValues = array( '_page' => 1, '_sort_order' => 'ASC', '_sort_by' => 'name' ); protected function configureFormFields(FormMapper $formMapper) { $formMapper->add('name') ->add( 'className', 'choice', array( 'choices' => array( 'feedburner' => 'feedburner', 'rss' => 'rss', 'dpc' => 'dpc', 'aws' => 'aws', 'bliptv' => 'bliptv', 'youtube' => 'youtube' ) ) ); } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper->add('name'); } protected function configureListFields(ListMapper $listMapper) { $listMapper->addIdentifier('name')->add('className'); } }
Fix the expected argument check in scoring tests
#!@PYTHON_EXECUTABLE@ #ckwg +5 # Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to # KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, # Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(path): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) result.hit_count result.miss_count result.truth_count result.percent_detection() result.precision() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
#!@PYTHON_EXECUTABLE@ #ckwg +5 # Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to # KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, # Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(path): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) result.hit_count result.miss_count result.truth_count result.percent_detection() result.precision() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 5: test_error("Expected four arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
Use the readline module to allow arrow key movement in the REPL
#!/usr/bin/env python3 import sys import readline import lexer as l import parser as p import evaluator as e import context as c import object as o def main(): if len(sys.argv) == 1: ctx = c.Context() while True: try: string = input("⧫ ") + ";" if string == "exit": break execute(string, True, ctx) except (KeyboardInterrupt, EOFError): break elif len(sys.argv) == 2: with open(sys.argv[1], "r") as f: content = f.read() execute(content, False, c.Context()) def execute(text, print_result, ctx): tokens = l.lex(text) parser = p.Parser(tokens) program = parser.parse_program() if len(parser.errors) > 0: parser.print_errors() else: result = e.eval(program, ctx) if (print_result and type(result) != o.Null) or type(result) == o.Error: print(result) if __name__ == "__main__": main()
#!/usr/bin/env python3 import sys import lexer as l import parser as p import evaluator as e import context as c import object as o def main(): if len(sys.argv) == 1: ctx = c.Context() while True: try: string = input("⧫ ") + ";" execute(string, True, ctx) except (KeyboardInterrupt, EOFError): break elif len(sys.argv) == 2: with open(sys.argv[1], "r") as f: content = f.read() execute(content, False, c.Context()) def execute(text, print_result, ctx): tokens = l.lex(text) parser = p.Parser(tokens) program = parser.parse_program() if len(parser.errors) > 0: parser.print_errors() else: result = e.eval(program, ctx) if (print_result and type(result) != o.Null) or type(result) == o.Error: print(result) if __name__ == "__main__": main()
Make the endpoint return geojson as opposed to wkt geometry
import requests from shapely.wkt import loads from shapely.geometry import mapping from girder.api import access from girder.api.describe import Description from girder.api.rest import Resource class TwoFishes(Resource): def __init__(self): self.resourceName = 'minerva_geocoder' self.route('GET', (), self.geocode) self.route('GET', ('autocomplete',), self.autocomplete) @access.public def geocode(self, params): r = requests.get(params['twofishes'], params={'query': params['location'], 'responseIncludes': 'WKT_GEOMETRY'}) wkt = r.json()['interpretations'][0]['feature']['geometry']['wktGeometry'] return mapping(loads(wkt)) geocode.description = ( Description('Get geojson for a given location name') .param('twofishes', 'Twofishes url') .param('location', 'Location name to get a geojson') ) @access.public def autocomplete(self, params): r = requests.get(params['twofishes'], params={'autocomplete': True, 'query': params['location'], 'maxInterpretations': 10, 'autocompleteBias': None}) return [i['feature']['matchedName'] for i in r.json()['interpretations']] autocomplete.description = ( Description('Autocomplete result for a given location name') .param('twofishes', 'Twofishes url') .param('location', 'Location name to autocomplete') )
import requests from girder.api import access from girder.api.describe import Description from girder.api.rest import Resource class TwoFishes(Resource): def __init__(self): self.resourceName = 'minerva_geocoder' self.route('GET', (), self.geocode) self.route('GET', ('autocomplete',), self.autocomplete) @access.public def geocode(self, params): r = requests.get(params['twofishes'], params={'query': params['location'], 'responseIncludes': 'WKT_GEOMETRY'}) return r.json() geocode.description = ( Description('Get geojson for a given location name') .param('twofishes', 'Twofishes url') .param('location', 'Location name to get a geojson') ) @access.public def autocomplete(self, params): r = requests.get(params['twofishes'], params={'autocomplete': True, 'query': params['location'], 'maxInterpretations': 10, 'autocompleteBias': None}) return [i['feature']['matchedName'] for i in r.json()['interpretations']] autocomplete.description = ( Description('Autocomplete result for a given location name') .param('twofishes', 'Twofishes url') .param('location', 'Location name to autocomplete') )
Allow empty values for select box
<?php namespace asdfstudio\admin\forms\widgets; use asdfstudio\admin\components\AdminFormatter; use Yii; use yii\base\InvalidConfigException; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use yii\helpers\Html; use asdfstudio\admin\helpers\AdminHelper; /** * Class Select * @package asdfstudio\admin\widgets * * Renders active select widget with related models */ class Select extends Base { /** * @var ActiveQuery|array */ public $query; /** * @var string */ public $labelAttribute; /** * @var array */ public $items = []; /** * @var bool */ public $multiple = false; /** * @var bool Allows empty value */ public $allowEmpty = false; /** * @inheritdoc */ public function init() { if ($this->query instanceof ActiveQuery) { if (!$this->labelAttribute) { throw new InvalidConfigException('Parameter "labelAttribute" is required'); } $this->items = $this->query->all(); foreach ($this->items as $i => $model) { $this->items[$i] = AdminHelper::resolveAttribute($this->labelAttribute, $model); } } if ($this->allowEmpty) { $this->items = ArrayHelper::merge([ null => Yii::t('yii', '(not set)') ], $this->items); } parent::init(); } /** * @inheritdoc */ public function renderWidget() { return Html::activeDropDownList($this->model, $this->attribute, $this->items, [ 'class' => 'form-control', 'multiple' => $this->multiple, ]); } }
<?php namespace asdfstudio\admin\forms\widgets; use Yii; use yii\base\InvalidConfigException; use yii\db\ActiveQuery; use yii\helpers\Html; use asdfstudio\admin\helpers\AdminHelper; /** * Class Select * @package asdfstudio\admin\widgets * * Renders active select widget with related models */ class Select extends Base { /** * @var ActiveQuery|array */ public $query; /** * @var string */ public $labelAttribute; /** * @var array */ public $items = []; /** * @var bool */ public $multiple = false; /** * @inheritdoc */ public function init() { if ($this->query instanceof ActiveQuery) { if (!$this->labelAttribute) { throw new InvalidConfigException('Parameter "labelAttribute" is required'); } $this->items = $this->query->all(); foreach ($this->items as $i => $model) { $this->items[$i] = AdminHelper::resolveAttribute($this->labelAttribute, $model); } } parent::init(); } /** * @inheritdoc */ public function renderWidget() { return Html::activeDropDownList($this->model, $this->attribute, $this->items, [ 'class' => 'form-control', 'multiple' => $this->multiple, ]); } }
Replace URL instead of pushing the new one.
define([ 'underscore', 'views/proto/paged-collection', 'views/event/box', 'text!templates/event-collection.html' ], function (_, PagedCollection, EventBox, html) { return PagedCollection.extend({ template: _.template(html), tag: 'div', listSelector: '.events-list', generateItem: function (model) { return new EventBox({ model: model }); }, events: { "click .filter": "filter" }, filter: function () { var types=[]; $('.filter:checked').each(function() { types.push($(this).val()); }); var filterString = types.join(); this.options.types = types; this.collection.setTypes(types); /* Set queryString to URL */ var url = '/feed'; if ( filterString != undefined) { url += '?types=' + filterString; } Backbone.trigger('pp:navigate', url, { replace: true }); }, serialize: function() { var types = this.options.types || []; var filterList = [ { value: 'add-comment', description: 'add-comment', }, { value: 'add-quest', description: 'add-quest', } ] /* Add status for each filter */ for( var i = 0; i < filterList.length ; i++ ){ if( types.indexOf(filterList[i].value) != -1 ){ filterList[i].status = 'checked'; }else{ filterList[i].status = ''; } } return { filterList: filterList }; } }); });
define([ 'underscore', 'views/proto/paged-collection', 'views/event/box', 'text!templates/event-collection.html' ], function (_, PagedCollection, EventBox, html) { return PagedCollection.extend({ template: _.template(html), tag: 'div', listSelector: '.events-list', generateItem: function (model) { return new EventBox({ model: model }); }, events: { "click .filter": "filter" }, filter: function () { var types=[]; $('.filter:checked').each(function() { types.push($(this).val()); }); var filterString = types.join(); this.options.types = types; this.collection.setTypes(types); /* Set queryString to URL */ var url = '/feed'; if ( filterString != undefined) { url += '?types=' + filterString; } Backbone.trigger('pp:navigate', url); }, serialize: function() { var types = this.options.types || []; var filterList = [ { value: 'add-comment', description: 'add-comment', }, { value: 'add-quest', description: 'add-quest', } ] /* Add status for each filter */ for( var i = 0; i < filterList.length ; i++ ){ if( types.indexOf(filterList[i].value) != -1 ){ filterList[i].status = 'checked'; }else{ filterList[i].status = ''; } } return { filterList: filterList }; } }); });
Update requirements to include networkx
from setuptools import setup def readme(): with open('README.rst') as readme_file: return readme_file.read() configuration = { 'name' : 'hypergraph', 'version' : '0.1', 'description' : 'Hypergraph tools and algorithms', 'long_description' : readme(), 'classifiers' : [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], 'keywords' : 'hypergraph graph network community pomset', 'url' : 'http://github.com/lmcinnes/hdbscan', 'maintainer' : 'Leland McInnes', 'maintainer_email' : '[email protected]', 'license' : 'BSD', 'packages' : ['hdbscan'], 'install_requires' : ['numpy>=1.5', 'networkx>=1.9.1'], 'ext_modules' : [], 'cmdclass' : {'build_ext' : build_ext}, 'test_suite' : 'nose.collector', 'tests_require' : ['nose'], } setup(**configuration)
from setuptools import setup def readme(): with open('README.rst') as readme_file: return readme_file.read() configuration = { 'name' : 'hypergraph', 'version' : '0.1', 'description' : 'Hypergraph tools and algorithms', 'long_description' : readme(), 'classifiers' : [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ], 'keywords' : 'hypergraph graph network community pomset', 'url' : 'http://github.com/lmcinnes/hdbscan', 'maintainer' : 'Leland McInnes', 'maintainer_email' : '[email protected]', 'license' : 'BSD', 'packages' : ['hdbscan'], 'install_requires' : ['numpy>=1.5], 'ext_modules' : [], 'cmdclass' : {'build_ext' : build_ext}, 'test_suite' : 'nose.collector', 'tests_require' : ['nose'], } setup(**configuration)
Revert "No support for update in pre" This reverts commit 20eb9908eff6fa7f2eb254d225a3e4f4bdc0c8a4.
var Schema = require('mongoose').Schema; module.exports = function (schema, options) { schema.add({ deleted: Boolean }); if (options && options.deletedAt === true) { schema.add({ deletedAt: { type: Date} }); } if (options && options.deletedBy === true) { schema.add({ deletedBy: Schema.Types.ObjectId }); } schema.pre('save', function (next) { if (!this.deleted) { this.deleted = false; } next(); }); var queries = ['find', 'findOne', 'findOneAndUpdate', 'update', 'count']; queries.forEach(function(query) { schema.pre(query, function(next) { var conditions = { deleted: { '$ne': true } }; this.where(conditions); next(); }); }); schema.methods.delete = function (first, second) { var callback = typeof first === 'function' ? first : second, deletedBy = second !== undefined ? first : null; if (typeof callback !== 'function') { throw ('Wrong arguments!'); } this.deleted = true; if (schema.path('deletedAt')) { this.deletedAt = new Date(); } if (schema.path('deletedBy')) { this.deletedBy = deletedBy; } this.save(callback); }; schema.methods.restore = function (callback) { this.deleted = false; this.deletedAt = undefined; this.deletedBy = undefined; this.save(callback); }; };
var Schema = require('mongoose').Schema; module.exports = function (schema, options) { schema.add({ deleted: Boolean }); if (options && options.deletedAt === true) { schema.add({ deletedAt: { type: Date} }); } if (options && options.deletedBy === true) { schema.add({ deletedBy: Schema.Types.ObjectId }); } schema.pre('save', function (next) { if (!this.deleted) { this.deleted = false; } next(); }); var queries = ['find', 'findOne', 'findOneAndUpdate', 'count']; queries.forEach(function(query) { schema.pre(query, function(next) { var conditions = { deleted: { '$ne': true } }; this.where(conditions); next(); }); }); schema.methods.delete = function (first, second) { var callback = typeof first === 'function' ? first : second, deletedBy = second !== undefined ? first : null; if (typeof callback !== 'function') { throw ('Wrong arguments!'); } this.deleted = true; if (schema.path('deletedAt')) { this.deletedAt = new Date(); } if (schema.path('deletedBy')) { this.deletedBy = deletedBy; } this.save(callback); }; schema.methods.restore = function (callback) { this.deleted = false; this.deletedAt = undefined; this.deletedBy = undefined; this.save(callback); }; };
Add python_requires to help pip
from setuptools import setup import sys import piexif sys.path.append('./piexif') sys.path.append('./tests') with open("README.rst", "r") as f: description = f.read() setup( name = "piexif", version = piexif.VERSION, author = "hMatoba", author_email = "[email protected]", description = "To simplify exif manipulations with python. " + "Writing, reading, and more...", long_description = description, license = "MIT", keywords = ["exif", "jpeg"], url = "https://github.com/hMatoba/Piexif", packages = ['piexif'], test_suite = 's_test.suite', python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*", classifiers = [ "Development Status :: 5 - Production/Stable", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: IronPython", "Programming Language :: Python :: Implementation :: PyPy", "License :: OSI Approved :: MIT License", "Topic :: Multimedia", "Topic :: Printing", ] )
from setuptools import setup import sys import piexif sys.path.append('./piexif') sys.path.append('./tests') with open("README.rst", "r") as f: description = f.read() setup( name = "piexif", version = piexif.VERSION, author = "hMatoba", author_email = "[email protected]", description = "To simplify exif manipulations with python. " + "Writing, reading, and more...", long_description = description, license = "MIT", keywords = ["exif", "jpeg"], url = "https://github.com/hMatoba/Piexif", packages = ['piexif'], test_suite = 's_test.suite', classifiers = [ "Development Status :: 5 - Production/Stable", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: IronPython", "Programming Language :: Python :: Implementation :: PyPy", "License :: OSI Approved :: MIT License", "Topic :: Multimedia", "Topic :: Printing", ] )