text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Allow log group to be set from env
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) log_group = os.getenv('EQ_SR_LOG_GROUP') cloud_watch_handler = watchtower.CloudWatchLogHandler(log_group=log_group) FORMAT = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s" levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING'], format=FORMAT) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server import watchtower import logging application = create_app( os.getenv('EQ_ENVIRONMENT') or 'development' ) application.debug = True manager = Manager(application) port = int(os.environ.get('PORT', 5000)) manager.add_command("runserver", Server(host='0.0.0.0', port=port)) cloud_watch_handler = watchtower.CloudWatchLogHandler() FORMAT = "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s" levels = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG } logging.basicConfig(level=levels[os.getenv('EQ_LOG_LEVEL') or 'WARNING'], format=FORMAT) application.logger.addHandler(cloud_watch_handler) logging.getLogger().addHandler(cloud_watch_handler) logging.getLogger(__name__).addHandler(cloud_watch_handler) logging.getLogger('werkzeug').addHandler(cloud_watch_handler) if __name__ == '__main__': manager.run()
Make all log messages show by default
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from werkzeug import secure_filename import os import logging import stripe APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join('static/uploads') MODELS_FOLDER = os.path.join('models') ALLOWED_EXTENSIONS = set(['stl']) stripe_keys = { 'secret_key': os.environ['SECRET_KEY'], 'publishable_key': os.environ['PUBLISHABLE_KEY'] } stripe.api_key = stripe_keys['secret_key'] shop_name = "Shop name" shop_tagline = "Best shop tagline ever" app = Flask(__name__) app.secret_key = 'thisisasecret' #You need to set up an app secret key. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MODELS_FOLDER'] = MODELS_FOLDER # Set up the SQLAlchemy Database to be a local file 'store.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/store' db = SQLAlchemy(app) if __name__ == "__main__": from views import * del session logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) app.run(debug=True)
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from werkzeug import secure_filename import os import logging import stripe APP_ROOT = os.path.dirname(os.path.abspath(__file__)) UPLOAD_FOLDER = os.path.join('static/uploads') MODELS_FOLDER = os.path.join('models') ALLOWED_EXTENSIONS = set(['stl']) stripe_keys = { 'secret_key': os.environ['SECRET_KEY'], 'publishable_key': os.environ['PUBLISHABLE_KEY'] } stripe.api_key = stripe_keys['secret_key'] shop_name = "Shop name" shop_tagline = "Best shop tagline ever" app = Flask(__name__) app.secret_key = 'thisisasecret' #You need to set up an app secret key. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MODELS_FOLDER'] = MODELS_FOLDER # Set up the SQLAlchemy Database to be a local file 'store.db' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/store' db = SQLAlchemy(app) if __name__ == "__main__": from views import * del session logging.basicConfig() app.run(debug=True)
Revert "Forcing generics on DiffElements" IDEA-CR-54193 WI-27162 This reverts commit cbf3b57c GitOrigin-RevId: 8162c394fb08d374a0054844e26aee00c58c7dd1
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.diff; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; /** * @author lene */ public interface AsyncDiffElement { @NotNull Promise<DiffElement> copyToAsync(@NotNull DiffElement container, @Nullable DiffElement target, @NotNull String relativePath); @NotNull Promise<Void> deleteAsync(); }
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.diff; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; public interface AsyncDiffElement { @NotNull Promise<DiffElement<?>> copyToAsync(@NotNull DiffElement<?> container, @Nullable DiffElement<?> target, @NotNull String relativePath); @NotNull Promise<Void> deleteAsync(); }
Implement binary representation of peers
import struct import socket import time from trackpy.vendors.redis import redis class Torrent(object): def __init__(self, info_hash): self.info = redis.hgetall(info_hash) self.info_hash = info_hash def can_announce(self, peer_id): timestamp = int(redis.get("%s_%s" % (self.info_hash, peer_id)) or 0) if not timestamp: return True now = int(time.time()) return False if now - timestamp > 5 * 60 else True def set_announce(self, peer_id): redis.set("%s_%s" % (self.info_hash, peer_id), int(time.time())) @property def peers(self): return redis.smembers('%s_peers' % self.info_hash) @peers.setter def peers(self, peer): redis.sadd('%s_peers' % self.info_hash, peer) @property def seeders(self): return self.info['seeders'] if 'seeders' in self.info else 0 @property def leechers(self): return self.info['leecher'] if 'leechers' in self.info else 0 @property def binary_peers(self): binary_peers = '' for peer in self.peers: ip = peer.split(':')[0] port = peer.split(':')[1] ip = struct.unpack("!I", socket.inet_aton(ip))[0] binary_peers += struct.pack('!ih', ip, int(port)) return binary_peers
import struct import socket import time from trackpy.vendors.redis import redis class Torrent(object): def __init__(self, info_hash): self.info = redis.hgetall(info_hash) self.info_hash = info_hash def can_announce(self, peer_id): timestamp = int(redis.get("%s_%s" % (self.info_hash, peer_id)) or 0) if not timestamp: return True now = int(time.time()) return False if now - timestamp > 5 * 60 else True def set_announce(self, peer_id): redis.set("%s_%s" % (self.info_hash, peer_id), int(time.time())) @property def peers(self): return redis.smembers('%s_peers' % self.info_hash) @peers.setter def peers(self, peer): redis.sadd('%s_peers' % self.info_hash, peer) @property def seeders(self): return self.info['seeders'] if 'seeders' in self.info else [] @property def leechers(self): return self.info['leecher'] if 'leechers' in self.info else []
Use Apache Commons Base64 library instead of sun.misc.BASE64 This will enable use on Android
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jxfdl.utils; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import org.apache.commons.codec.binary.Base64InputStream; /** * * @author unamanic */ public class Base64GZip { public static InputStream B64GzipToInputStream(InputStream is) { try { //BASE64Decoder b64 = new BASE64Decoder(); //decoded = new ByteArrayInputStream(b64.decodeBuffer(is)); InputStream decoded = new Base64InputStream(is); InputStream gzip = new GZIPInputStream(decoded); return gzip; } catch (IOException ex) { Logger.getLogger(Base64GZip.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jxfdl.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import sun.misc.BASE64Decoder; /** * * @author unamanic */ public class Base64GZip { public static InputStream B64GzipToInputStream(InputStream is) { ByteArrayInputStream decoded = null; try { BASE64Decoder b64 = new BASE64Decoder(); decoded = new ByteArrayInputStream(b64.decodeBuffer(is)); GZIPInputStream gzip = new GZIPInputStream(decoded); return gzip; } catch (IOException ex) { Logger.getLogger(Base64GZip.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
Add stil url in mock
import * as _ from 'lodash' import UUID from 'node-uuid'; const KEY = 'GIFS'; export const loadData = () => { let data = JSON.parse(localStorage.getItem(KEY)); if (_.isEmpty(data)) { return {}; } else { return data; } }; export const update = (update) => { localStorage.setItem(KEY, JSON.stringify(update)); }; export const mock = (max = 10) => { localStorage.clear(); let data = []; for(let i = 0; i < max; i++) { data.push({ id: UUID.v4(), name: 'Test ' + i, url: 'http://media2.giphy.com/media/geozuBY5Y6cXm/giphy.gif', still_url: 'https://media2.giphy.com/media/geozuBY5Y6cXm/giphy_s.gif' }); } localStorage.setItem(KEY, JSON.stringify(data)) };
import * as _ from 'lodash' import UUID from 'node-uuid'; const KEY = 'GIFS'; export const loadData = () => { let data = JSON.parse(localStorage.getItem(KEY)); if (_.isEmpty(data)) { return {}; } else { return data; } }; export const update = (update) => { localStorage.setItem(KEY, JSON.stringify(update)); }; export const mock = (max = 10) => { localStorage.clear(); let data = []; for(let i = 0; i < max; i++) { data.push({ id: UUID.v4(), name: 'Test ' + i, url: 'http://media2.giphy.com/media/geozuBY5Y6cXm/giphy.gif' }); } localStorage.setItem(KEY, JSON.stringify(data)) };
Handle ampersands with new rewrite friendly encoding
<?php /* GNU FM -- a free network service for sharing your music listening habits Copyright (C) 2009 Free Software Foundation, Inc This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Encodes an URL component in a mod_rewrite friendly way, handling plus, * ampersand and slash signs. * * @param string The text to encode * @return string A mod_rewrite compatible encoding of the given text. */ function rewrite_encode($url) { $url = urlencode($url); $url = preg_replace('/%2B/', '%252B', $url); // + $url = preg_replace('/%2F/', '%252F', $url); // / $url = preg_replace('/%26/', '%2526', $url); // & return $url; }
<?php /* GNU FM -- a free network service for sharing your music listening habits Copyright (C) 2009 Free Software Foundation, Inc This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Encodes an URL component in a mod_rewrite friendly way, handling plus and * slash signs. * * @param string The text to encode * @return string A mod_rewrite compatible encoding of the given text. */ function rewrite_encode($url) { $url = urlencode($url); $url = preg_replace('/%2B/', '%252B', $url); $url = preg_replace('/%2F/', '%252F', $url); return $url; }
Use passed options, overwriting file on each lap
/*jshint node:true */ "use strict"; var es = require('event-stream'), gutil = require('gulp-util'), path = require('path'), exec = require('child_process').exec; module.exports = function(command, opt){ if (!command) { throw new Error('command is blank'); } // defaults if (!opt) { opt = { silent: false }; } return es.map(function (file, cb){ opt.file = file; var cmd = gutil.template(command, opt); exec(cmd, function (error, stdout, stderr) { if (stderr) { gutil.log(stderr); } if (stdout) { stdout = stdout.trim(); // Trim trailing cr-lf } if (stdout) { gutil.log(stdout); } cb(error, file); }); }); };
/*jshint node:true */ "use strict"; var es = require('event-stream'), gutil = require('gulp-util'), path = require('path'), exec = require('child_process').exec; module.exports = function(command, opt){ if (!command) { throw new Error('command is blank'); } // defaults if (!opt) { opt = { silent: false }; } return es.map(function (file, cb){ var filepath = path.resolve(file.path); var cmd = gutil.template(command, {file: file}); exec(cmd, function (error, stdout, stderr) { if (stderr) { gutil.log(stderr); } if (stdout) { stdout = stdout.trim(); // Trim trailing cr-lf } if (stdout) { gutil.log(stdout); } cb(error, file); }); }); };
Increment minor version to 2.12 to prepare for a new release. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=153211686
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 12; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.cdbg.debuglets.java; /** * Defines the version of the Java Cloud Debugger agent. */ public final class GcpDebugletVersion { /** * Major version of the debugger. * All agents of the same major version are compatible with each other. In other words an * application can mix different agents with the same major version within the same debuggee. */ public static final int MAJOR_VERSION = 2; /** * Minor version of the agent. */ public static final int MINOR_VERSION = 11; /** * Debugger agent version string in the format of MAJOR.MINOR. */ public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION); /** * Main function to print the version string. */ public static void main(String[] args) { System.out.println(VERSION); } }
Add classifiers for supported Python versions.
#!/usr/bin/env python import os, sys from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup( name="statprof", version="0.1.2", author="Bryan O'Sullivan", author_email="bos@serpentine.com", description="Statistical profiling for Python", license=read('LICENSE'), keywords="profiling", url="http://packages.python.org/statprof", py_modules=['statprof'], long_description=read('README.rst'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], **extra )
#!/usr/bin/env python import os, sys from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup( name="statprof", version="0.1.2", author="Bryan O'Sullivan", author_email="bos@serpentine.com", description="Statistical profiling for Python", license=read('LICENSE'), keywords="profiling", url="http://packages.python.org/statprof", py_modules=['statprof'], long_description=read('README.rst'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", ], **extra )
Update note that the `group_id` validity is not an assumption but a requirement
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Models; /** * @property Group $group * @property int $group_id * @property int $group_leader * @property User $user * @property int $user_id * @property int $user_pending * @property array|null $playmodes */ class UserGroup extends Model { protected $table = 'phpbb_user_group'; public $timestamps = false; protected $primaryKeys = ['user_id', 'group_id']; protected $casts = [ 'playmodes' => 'array', 'user_pending' => 'boolean', ]; public function group() { return $this->belongsTo(Group::class, 'group_id'); } public function user() { return $this->belongsTo(User::class, 'user_id'); } public function getGroupAttribute(): Group { // `group_id` attribute should always be valid or otherwise this will throw error (as it tries to return null). return app('groups')->byId($this->group_id); } public function getPlaymodesAttribute(?string $value): ?array { if ($this->group->has_playmodes) { return json_decode($value) ?? []; } return null; } }
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Models; /** * @property Group $group * @property int $group_id * @property int $group_leader * @property User $user * @property int $user_id * @property int $user_pending * @property array|null $playmodes */ class UserGroup extends Model { protected $table = 'phpbb_user_group'; public $timestamps = false; protected $primaryKeys = ['user_id', 'group_id']; protected $casts = [ 'playmodes' => 'array', 'user_pending' => 'boolean', ]; public function group() { return $this->belongsTo(Group::class, 'group_id'); } public function user() { return $this->belongsTo(User::class, 'user_id'); } public function getGroupAttribute(): Group { // Assumes that `group_id` refers to an existing group that is present // in `app('groups')` cache return app('groups')->byId($this->group_id); } public function getPlaymodesAttribute(?string $value): ?array { if ($this->group->has_playmodes) { return json_decode($value) ?? []; } return null; } }
Add extra Counter component in spec to show the result with value '0'
import React, { PureComponent } from 'react'; import { Counter, Heading1, Section } from '../../components'; import style from './counter.css'; class CounterTest extends PureComponent { render () { return ( <article> <Section neutral dark> <Heading1>Counters</Heading1> </Section> <div className="component-spec"> <div className="properties"> <p> <Counter className={style.counter} count={999} /> <Counter className={style.counter} count={9} size="small" /> <Counter className={style.counter} count={0} size="small" /> <Counter className={style.counter} color="ruby" count={100} maxCount={99} /> <Counter className={style.counter} color="ruby" count={9} size="small" /> <Counter className={style.counter} color="ruby" count={0} size="small" /> <Counter className={style.counter} color="ruby" /> <Counter className={style.counter} color="ruby" size="small" /> </p> </div> </div> </article> ); } } export default CounterTest;
import React, { PureComponent } from 'react'; import { Counter, Heading1, Section } from '../../components'; import style from './counter.css'; class CounterTest extends PureComponent { render () { return ( <article> <Section neutral dark> <Heading1>Counters</Heading1> </Section> <div className="component-spec"> <div className="properties"> <p> <Counter className={style.counter} count={999} /> <Counter className={style.counter} count={9} size="small" /> <Counter className={style.counter} color="ruby" count={100} maxCount={99} /> <Counter className={style.counter} color="ruby" count={9} size="small" /> <Counter className={style.counter} color="ruby" /> <Counter className={style.counter} color="ruby" size="small" /> </p> </div> </div> </article> ); } } export default CounterTest;
Make module id's for AMD body in UMD optional as well
module.exports = UMDFormatter; var AMDFormatter = require("./amd"); var util = require("../../util"); var t = require("../../types"); var _ = require("lodash"); function UMDFormatter(file, opts) { this.file = file; this.ids = {}; this.insertModuleId = opts.amdModuleId; } util.inherits(UMDFormatter, AMDFormatter); UMDFormatter.prototype.transform = function (ast) { var program = ast.program; var body = program.body; // build an array of module names var names = []; _.each(this.ids, function (id, name) { names.push(t.literal(name)); }); // factory var ids = _.values(this.ids); var args = [t.identifier("exports")].concat(ids); var factory = t.functionExpression(null, args, t.blockStatement(body)); // runner var moduleName = this.getModuleName(); var defineArgs = [t.arrayExpression([t.literal("exports")].concat(names))]; if( this.insertModuleId ) defineArgs.unshift(t.literal(moduleName)); var runner = util.template("umd-runner-body", { AMD_ARGUMENTS: defineArgs, COMMON_ARGUMENTS: names.map(function (name) { return t.callExpression(t.identifier("require"), [name]); }) }); // var call = t.callExpression(runner, [factory]); program.body = [t.expressionStatement(call)]; };
module.exports = UMDFormatter; var AMDFormatter = require("./amd"); var util = require("../../util"); var t = require("../../types"); var _ = require("lodash"); function UMDFormatter(file) { this.file = file; this.ids = {}; } util.inherits(UMDFormatter, AMDFormatter); UMDFormatter.prototype.transform = function (ast) { var program = ast.program; var body = program.body; // build an array of module names var names = []; _.each(this.ids, function (id, name) { names.push(t.literal(name)); }); // factory var ids = _.values(this.ids); var args = [t.identifier("exports")].concat(ids); var factory = t.functionExpression(null, args, t.blockStatement(body)); // runner var moduleName = this.getModuleName(); var runner = util.template("umd-runner-body", { AMD_ARGUMENTS: [t.literal(moduleName), t.arrayExpression([t.literal("exports")].concat(names))], COMMON_ARGUMENTS: names.map(function (name) { return t.callExpression(t.identifier("require"), [name]); }) }); // var call = t.callExpression(runner, [factory]); program.body = [t.expressionStatement(call)]; };
Add API call to return service dialogs https://trello.com/c/qfdnTNlk
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'marketplace.details': { url: '/:serviceTemplateId', templateUrl: 'app/states/marketplace/details/details.html', controller: StateController, controllerAs: 'vm', title: 'Service Template Details', resolve: { dialogs: resolveDialogs, serviceTemplate: resolveServiceTemplate } } }; } /** @ngInject */ function resolveServiceTemplate($stateParams, CollectionsApi) { return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId); } /** @ngInject */ function resolveDialogs($stateParams, CollectionsApi) { var options = {expand: true, attributes: 'content'}; return CollectionsApi.query('service_templates/' + $stateParams.serviceTemplateId + '/service_dialogs', options); } /** @ngInject */ function StateController(dialogs, serviceTemplate) { var vm = this; vm.title = 'Service Template Details'; vm.dialogs = dialogs.resources[0].content; vm.serviceTemplate = serviceTemplate; } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return { 'marketplace.details': { url: '/:serviceTemplateId', templateUrl: 'app/states/marketplace/details/details.html', controller: StateController, controllerAs: 'vm', title: 'Service Template Details', resolve: { serviceTemplate: resolveServiceTemplate } } }; } /** @ngInject */ function resolveServiceTemplate($stateParams, CollectionsApi) { return CollectionsApi.get('service_templates', $stateParams.serviceTemplateId); } /** @ngInject */ function StateController(serviceTemplate) { var vm = this; vm.title = 'Service Template Details'; vm.serviceTemplate = serviceTemplate; } })();
Remove default buflen value in UniqueBuffer.__init__()
import collections import http.cookies import logging class UniqueBuffer: """A simple deduplicating buffer. To add new items, manipulate self.items. The actual buffer is not limited in length, the `buflen` argument is used to specify the amount of items guaranteed to be unique.""" def __init__(self, buflen): self.items = [] self.old = collections.deque(maxlen=buflen) def pop_all(self): """Return all items and remove them from the buffer.""" ret = [] for i in self.items: if i not in self.old: ret.append(i) self.old.append(i) self.items = [] return ret def atoi(string): s = [] for i in string: try: int(i) s.append(i) except ValueError: break return int(''.join(s)) def dict_from_cookie_str(cookie_str): c = http.cookies.SimpleCookie() d = dict() c.load(cookie_str) for k, m in c.items(): d[k] = m.value return d
import collections import http.cookies import logging class UniqueBuffer: """A simple deduplicating buffer. To add new items, manipulate self.items. The actual buffer is not limited in length, the `buflen` argument is used to specify the amount of items guaranteed to be unique.""" def __init__(self, buflen=21): self.items = [] self.old = collections.deque(maxlen=buflen) def pop_all(self): """Return all items and remove them from the buffer.""" ret = [] for i in self.items: if i not in self.old: ret.append(i) self.old.append(i) self.items = [] return ret def atoi(string): s = [] for i in string: try: int(i) s.append(i) except ValueError: break return int(''.join(s)) def dict_from_cookie_str(cookie_str): c = http.cookies.SimpleCookie() d = dict() c.load(cookie_str) for k, m in c.items(): d[k] = m.value return d
Remove ember-beta from npm testing Reference issue #62
/*jshint node:true*/ module.exports = { scenarios: [ { name: 'default', bower: { dependencies: { } } }, { name: 'ember-1-13', bower: { dependencies: { 'ember': '~1.13.0' }, resolutions: { 'ember': '~1.13.0' } } }, { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } } } ] };
/*jshint node:true*/ module.exports = { scenarios: [ { name: 'default', bower: { dependencies: { } } }, { name: 'ember-1-13', bower: { dependencies: { 'ember': '~1.13.0' }, resolutions: { 'ember': '~1.13.0' } } }, { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } } }, { name: 'ember-beta', bower: { dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } } } ] };
Improve JSON parsing error message
var fs = require('fs'); var parallelStream = require('pelias-parallel-stream'); var maxInFlight = 10; module.exports.create = function create_json_parse_stream(dataDirectory) { return parallelStream(maxInFlight, function(record, enc, next) { fs.readFile(dataDirectory + record.path, function(err, data) { if (err) { console.error('exception reading file ' + record.path); next(err); } else { try { var object = JSON.parse(data); next(null, object); } catch (parse_err) { console.error('exception parsing JSON in file %s:', record.path, parse_err); console.error('Inability to parse JSON usually means that WOF has been cloned ' + 'without using git-lfs, please see instructions here: ' + 'https://github.com/whosonfirst/whosonfirst-data#git-and-large-files'); next(parse_err); } } }); }); };
var fs = require('fs'); var parallelStream = require('pelias-parallel-stream'); var maxInFlight = 10; module.exports.create = function create_json_parse_stream(dataDirectory) { return parallelStream(maxInFlight, function(record, enc, next) { fs.readFile(dataDirectory + record.path, function(err, data) { if (err) { console.error('exception reading file ' + record.path); next(err); } else { try { var object = JSON.parse(data); next(null, object); } catch (parse_err) { console.error('exception on %s:', record.path, parse_err); console.error('Inability to parse JSON usually means that WOF has been cloned ' + 'without using git-lfs, please see instructions here: ' + 'https://github.com/whosonfirst/whosonfirst-data#git-and-large-files'); next(parse_err); } } }); }); };
Add support for Meteor 1.2
// package metadata file for Meteor.js /* jshint strict:false */ /* global Package:true */ Package.describe({ name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.', version: '3.3.5', git: 'https://github.com/twbs/bootstrap.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); api.addFiles([ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2' ], 'client', { isAsset: true }); api.addFiles([ 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client'); });
// package metadata file for Meteor.js /* jshint strict:false */ /* global Package:true */ Package.describe({ name: 'twbs:bootstrap', // http://atmospherejs.com/twbs/bootstrap summary: 'The most popular front-end framework for developing responsive, mobile first projects on the web.', version: '3.3.5', git: 'https://github.com/twbs/bootstrap.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); api.addFiles([ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2', 'dist/css/bootstrap.css', 'dist/js/bootstrap.js' ], 'client'); });
Add config object to JSON schema.
export default { "defs": { "spec": { "title": "Vega visualization specification", "type": "object", "allOf": [ {"$ref": "#/defs/scope"}, { "properties": { "$schema": {"type": "string", "format": "uri"}, "config": {"type": "object"}, "description": {"type": "string"}, "width": {"type": "number"}, "height": {"type": "number"}, "padding": {"$ref": "#/defs/padding"}, "autosize": {"$ref": "#/defs/autosize"}, "background": {"$ref": "#/defs/background"} } } ] } } };
export default { "defs": { "spec": { "title": "Vega visualization specification", "type": "object", "allOf": [ {"$ref": "#/defs/scope"}, { "properties": { "$schema": {"type": "string", "format": "uri"}, "description": {"type": "string"}, "width": {"type": "number"}, "height": {"type": "number"}, "padding": {"$ref": "#/defs/padding"}, "autosize": {"$ref": "#/defs/autosize"}, "background": {"$ref": "#/defs/background"} } } ] } } };
Remove Node.js from global environment
'use strict'; /* eslint-env node */ module.exports = { env: { es6: true, browser: true, }, extends: 'eslint:recommended', parserOptions: { sourceType: 'module', ecmaVersion: 8, }, rules: { indent: [ 'error', 2 , {SwitchCase: 1}], 'linebreak-style': [ 'error', 'unix' ], quotes: [ 'error', 'single', { avoidEscape: true, allowTemplateLiterals: true } ], semi: [ 'error', 'always' ], 'no-console': 'off', 'no-unused-vars': 'warn', } };
'use strict'; module.exports = { env: { es6: true, node: true, browser: true, }, extends: 'eslint:recommended', parserOptions: { sourceType: 'module', ecmaVersion: 8, }, rules: { indent: [ 'error', 2 , {SwitchCase: 1}], 'linebreak-style': [ 'error', 'unix' ], quotes: [ 'error', 'single', { avoidEscape: true, allowTemplateLiterals: true } ], semi: [ 'error', 'always' ], 'no-console': 'off', 'no-unused-vars': 'warn', } };
Remove logic from component, it's done in the data class.
import React from 'react'; import KataGroupsComponent from './katagroups'; import KatasComponent from './katas.js'; import KataComponent from './kata.js'; import KataGroups from '../katagroups.js'; export default class PageComponent extends React.Component { static propTypes = { kataGroups: React.PropTypes.instanceOf(KataGroups).isRequired }; render() { const {kataGroups, appUrl} = this.props; return ( <div id="layout" className="content pure-g"> <KataGroupsComponent kataGroups={kataGroups} appUrl={appUrl}/> <KatasComponent kataGroup={kataGroups.selectedGroup} appUrl={appUrl} /> <KataComponent kata={kataGroups.selectedKata} /> </div> ); } }
import React from 'react'; import KataGroupsComponent from './katagroups'; import KatasComponent from './katas.js'; import KataComponent from './kata.js'; import KataGroups from '../katagroups.js'; export default class PageComponent extends React.Component { static propTypes = { kataGroups: React.PropTypes.instanceOf(KataGroups).isRequired }; render() { const {kataGroups, appUrl} = this.props; const { selectedGroup = kataGroups.firstGroup, selectedKata } = kataGroups; return ( <div id="layout" className="content pure-g"> <KataGroupsComponent kataGroups={kataGroups} appUrl={appUrl}/> <KatasComponent kataGroup={selectedGroup} appUrl={appUrl} /> <KataComponent kata={selectedKata} /> </div> ); } }
Store K so it can be returned again later
<?php namespace Bitcoin\Signature\K; use Bitcoin\Util\Buffer; use Bitcoin\Crypto\DRBG\HMACDRBG; use Bitcoin\Key\PrivateKeyInterface; use Mdanter\Ecc\GeneratorPoint; /** * Class DeterministicK * @package Bitcoin\Signature\K * @author Thomas Kerin * Todo: refactor so this class accepts an initialized DRBGInterface */ class DeterministicK implements KInterface { /** * @var HMACDRBG */ protected $drbg; /** * @var Buffer */ protected $k; /** * @param PrivateKeyInterface $privateKey * @param Buffer $messageHash * @param string $algo * @param GeneratorPoint $generator */ public function __construct(PrivateKeyInterface $privateKey, Buffer $messageHash, $algo = 'sha256') { $entropy = new Buffer($privateKey->serialize() . $messageHash->serialize()); $this->drbg = new HMACDRBG($algo, $entropy); } /** * Return a K value deterministically derived from the private key * and data */ public function getK() { if (is_null($this->k)) { $this->k = $this->drbg->bytes(32); } return $this->k; } }
<?php namespace Bitcoin\Signature\K; use Bitcoin\Util\Buffer; use Bitcoin\Crypto\Hash; use Bitcoin\Crypto\DRBG\HMACDRBG; use Bitcoin\Crypto\DRBG\RFC6979; use Bitcoin\Key\PrivateKeyInterface; use Mdanter\Ecc\GeneratorPoint; /** * Class DeterministicK * @package Bitcoin\Signature\K * @author Thomas Kerin */ class DeterministicK implements KInterface { /** * @var HMACDRBG */ protected $drbg; /** * @param PrivateKeyInterface $privateKey * @param Buffer $messageHash * @param string $algo * @param GeneratorPoint $generator */ public function __construct(PrivateKeyInterface $privateKey, Buffer $messageHash, $algo = 'sha256') { $entropy = new Buffer($privateKey->serialize() . $messageHash->serialize()); $this->drbg = new HMACDRBG($algo, $entropy); } /** * Return a K value deterministically derived from the private key * and data */ public function getK() { $deterministicK = $this->drbg->bytes(32); return $deterministicK; } }
Fix csp test on node
var parseTests = require( './samples/parse' ); QUnit.module( 'Ractive.parse()' ); parseTests.forEach( function ( test ) { // disable for tests unless explicitly specified // we can just test the signatures, so set csp false test.options = test.options || { csp: false }; if ( !test.options.hasOwnProperty( 'csp' ) ) { test.options.csp = false; } QUnit.test( test.name, function ( assert ) { if (test.error) { assert.throws( function () { Ractive.parse( test.template, test.options ); }, function ( error ) { if (error.name !== 'ParseError') { throw error; } assert.equal( error.message, test.error ); return true; }, 'Expected ParseError'); } else { var parsed = Ractive.parse( test.template, test.options ); if (parsed.e && test.parsed.e) { var expectedKeys = Object.keys(test.parsed.e); var parsedKeys = Object.keys(parsed.e); assert.deepEqual(parsedKeys, expectedKeys); expectedKeys.forEach(key => { // normalize function whitepace for browser vs phantomjs var actual = parsed.e[key].toString().replace(') \{', ')\{'); assert.equal(actual, test.parsed.e[key]); }); delete parsed.e; delete test.parsed.e; } assert.deepEqual( parsed, test.parsed ); } }); });
var parseTests = require( './samples/parse' ); QUnit.module( 'Ractive.parse()' ); parseTests.forEach( function ( test ) { // disable for tests unless explicitly specified // we can just test the signatures, so set csp false test.options = test.options || { csp: false }; if ( !test.options.hasOwnProperty( 'csp' ) ) { test.options.csp = false; } QUnit.test( test.name, function ( assert ) { if (test.error) { assert.throws( function () { Ractive.parse( test.template, test.options ); }, function ( error ) { if (error.name !== 'ParseError') { throw error; } assert.equal( error.message, test.error ); return true; }, 'Expected ParseError'); } else { var parsed = Ractive.parse( test.template, test.options ); assert.deepEqual( parsed, test.parsed ); } }); });
Add remove buttons to selectize tags
var People = new Mongo.Collection("people"); if (Meteor.isClient) { Template.body.helpers({ people: function () { return People.find({}); } }); Template.body.events({ "submit .new-person": function (event) { var commaSeparator = /\s*,\s*/; var name = event.target.name.value; var learning = event.target.learning.value.split(commaSeparator); var teaching = event.target.teaching.value.split(commaSeparator); People.insert({ name: name, learning: learning, teaching: teaching }); event.target.name.value = ""; $(event.target.learning).clearOptions(); $(event.target.teaching).clearOptions(); return false; } }); $(document).ready(function () { $('.input-list').selectize({ create: function (input) { return { value: input, text: input }; }, plugins: [ 'remove_button' ] }); }); }
var People = new Mongo.Collection("people"); if (Meteor.isClient) { Template.body.helpers({ people: function () { return People.find({}); } }); Template.body.events({ "submit .new-person": function (event) { var commaSeparator = /\s*,\s*/; var name = event.target.name.value; var learning = event.target.learning.value.split(commaSeparator); var teaching = event.target.teaching.value.split(commaSeparator); People.insert({ name: name, learning: learning, teaching: teaching }); event.target.name.value = ""; $(event.target.learning).clearOptions(); $(event.target.teaching).clearOptions(); return false; } }); $(document).ready(function () { $('.input-list').selectize({ create: function (input) { return { value: input, text: input }; } }); }); }
Use "The StackStorm Authors" in copyright Co-authored-by: Eugen C. <67cac084fbaf94f499d5252e3cb50165dbf6e026@armab.io>
#!/usr/bin/env python # Copyright 2020 The StackStorm Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from st2tests.base import BaseActionTestCase from dig import DigAction class DigActionTestCase(BaseActionTestCase): action_cls = DigAction def test_run(self): action = self.get_action_instance() # Use the defaults from dig.yaml result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short') self.assertIsInstance(result, list) self.assertEqual(len(result), 0) result = action.run(rand=False, count=0, nameserver=None, hostname='google.com', queryopts='') self.assertIsInstance(result, list) self.assertGreater(len(result), 0)
#!/usr/bin/env python # Copyright 2020 The StackStorm Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from st2tests.base import BaseActionTestCase from dig import DigAction class DigActionTestCase(BaseActionTestCase): action_cls = DigAction def test_run(self): action = self.get_action_instance() # Use the defaults from dig.yaml result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short') self.assertIsInstance(result, list) self.assertEqual(len(result), 0) result = action.run(rand=False, count=0, nameserver=None, hostname='google.com', queryopts='') self.assertIsInstance(result, list) self.assertGreater(len(result), 0)
Set production databse to test database
# -*- coding: utf-8 -*- import os HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000') class ProdConfig(Config): ENV = 'prod' DEBUG = False class DevConfig(Config): ENV = 'dev' DEBUG = True LOAD_FAKE_DATA = True class TestConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'postgresql://localhost/') TESTING = True DEBUG = True # For: `nose.proxy.AssertionError: Popped wrong request context.` # http://stackoverflow.com/a/28139033/399726 # https://github.com/jarus/flask-testing/issues/21 PRESERVE_CONTEXT_ON_EXCEPTION = False
# -*- coding: utf-8 -*- import os HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000') class ProdConfig(Config): ENV = 'prod' DEBUG = False class DevConfig(Config): ENV = 'dev' DEBUG = True LOAD_FAKE_DATA = True class TestConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'postgresql://localhost/') TESTING = True DEBUG = True # For: `nose.proxy.AssertionError: Popped wrong request context.` # http://stackoverflow.com/a/28139033/399726 # https://github.com/jarus/flask-testing/issues/21 PRESERVE_CONTEXT_ON_EXCEPTION = False
Set a default INSPIRE_API_URL value for tests
// Remove the PUBLIC_URL, if defined process.env.PUBLIC_URL = ''; process.env.INSPIRE_API_URL = 'inspire-api-url' require('babel-register')(); const { jsdom } = require('jsdom') const moduleAlias = require('module-alias') const path = require('path') moduleAlias.addAlias('common', path.join(__dirname, '../../src')) const exposedProperties = ['window', 'navigator', 'document']; global.document = jsdom('<!doctype html><html><body></body></html>'); global.window = document.defaultView; Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property); global[property] = document.defaultView[property]; } }); global.navigator = window.navigator = { userAgent: 'node.js', platform: 'node.js', }; const chai = require('chai') const chaiEnzyme = require('chai-enzyme') global.expect = chai.expect chai.use(chaiEnzyme())
// Remove the PUBLIC_URL, if defined process.env.PUBLIC_URL = ''; require('babel-register')(); const { jsdom } = require('jsdom') const moduleAlias = require('module-alias') const path = require('path') moduleAlias.addAlias('common', path.join(__dirname, '../../src')) const exposedProperties = ['window', 'navigator', 'document']; global.document = jsdom('<!doctype html><html><body></body></html>'); global.window = document.defaultView; Object.keys(document.defaultView).forEach((property) => { if (typeof global[property] === 'undefined') { exposedProperties.push(property); global[property] = document.defaultView[property]; } }); global.navigator = window.navigator = { userAgent: 'node.js', platform: 'node.js', }; const chai = require('chai') const chaiEnzyme = require('chai-enzyme') global.expect = chai.expect chai.use(chaiEnzyme())
Correct namespace of Input Class
<?php /* * This file is part of phpBB. * * (c) phpBB Ltd. * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Bundle\phpBB\PyrusBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Bundle\phpBB\PyrusBundle\Input\ArbitraryInputDefinition; use Bundle\phpBB\PyrusBundle\Pyrus; /** * Pyrus command */ class PyrusCommand extends Command { protected $inputDefinition; /** * Configures this command to accept arbitrary options and arguments. */ protected function configure() { $this->inputDefinition = new ArbitraryInputDefinition; $this ->setName('pyrus') ->setDefinition($this->inputDefinition); } /** * Passes the given options and arguments to Pyrus for execution * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $tokens = $this->inputDefinition->getTokens($input); array_shift($tokens); // remove pyrus $pyrus = new Pyrus($this->application->getKernel()); $pyrus->run($tokens); } }
<?php /* * This file is part of phpBB. * * (c) phpBB Ltd. * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Bundle\phpBB\PyrusBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Bundle\Phpbb\PyrusBundle\Input\ArbitraryInputDefinition; use Bundle\Phpbb\PyrusBundle\Pyrus; /** * Pyrus command */ class PyrusCommand extends Command { protected $inputDefinition; /** * Configures this command to accept arbitrary options and arguments. */ protected function configure() { $this->inputDefinition = new ArbitraryInputDefinition; $this ->setName('pyrus') ->setDefinition($this->inputDefinition); } /** * Passes the given options and arguments to Pyrus for execution * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $tokens = $this->inputDefinition->getTokens($input); array_shift($tokens); // remove pyrus $pyrus = new Pyrus($this->application->getKernel()); $pyrus->run($tokens); } }
FIx scenario: Step editMeetingSteps change the attendee value in create meeting with api
package org.fundacionjala.automation.scenario.steps.tablet.editMeeting; import org.fundacionjala.automation.framework.utils.api.managers.MeetingAPIManager; import org.fundacionjala.automation.framework.utils.api.objects.admin.Meeting; import org.fundacionjala.automation.framework.utils.common.PropertiesReader; import org.fundacionjala.automation.framework.utils.common.RMGenerator; import cucumber.api.java.en.Given; public class EditMeetingGivenSteps { @Given("^I had a created meeting with \"([^\"]*)\" organizer, with \"([^\"]*)\" subject in the \"([^\"]*)\" room$") public void IHadAMeetingCreated(String organizer, String subject, String room) throws Throwable { String startDate = RMGenerator.getIsoTime(0); String endDate = RMGenerator.getIsoTime(1); String roomEmail = room + "@" + PropertiesReader.getExchangeDomain(); Meeting meeting = new Meeting(organizer, subject, startDate, endDate, room, roomEmail, roomEmail, PropertiesReader.getExchangeInviteMail()); MeetingAPIManager.postRequest(room, meeting); } }
package org.fundacionjala.automation.scenario.steps.tablet.editMeeting; import org.fundacionjala.automation.framework.utils.api.managers.MeetingAPIManager; import org.fundacionjala.automation.framework.utils.api.objects.admin.Meeting; import org.fundacionjala.automation.framework.utils.common.PropertiesReader; import org.fundacionjala.automation.framework.utils.common.RMGenerator; import cucumber.api.java.en.Given; public class EditMeetingGivenSteps { @Given("^I had a created meeting with \"([^\"]*)\" organizer, with \"([^\"]*)\" subject in the \"([^\"]*)\" room$") public void IHadAMeetingCreated(String organizer, String subject, String room) throws Throwable { String startDate = RMGenerator.getIsoTime(0); String endDate = RMGenerator.getIsoTime(1); String roomEmail = room + "@" + PropertiesReader.getExchangeDomain(); Meeting meeting = new Meeting(organizer, subject, startDate, endDate, room, roomEmail, roomEmail, PropertiesReader.getExchangeInviteUser()); MeetingAPIManager.postRequest(room, meeting); } }
Remove dupe vars and bad syntax; tidy string
var request = require( 'request' ); module.exports = { commands: { isup: { aliases: [ 'get', 'web' ], privileged: true, help: 'Performs a HTTP(S) request to an arbitrary host.', usage: [ 'host' ], command: function ( bot, msg ) { request( msg.args.host, function ( err, res, body ) { if ( err ) { bot.say( msg.to, msg.nick + ': ' + err.message ); } else { var str = 'HTTP/' + res.httpVersion; str += ' ' + res.req.method + ' ' + res.request.href; str += ' → ' + res.statusCode; var flag = ''; try { var headers = [ res.headers['content-type'], res.headers.server, body.length ]; str += ' ' + headers.join( ' · ' ); } catch ( e ) { flag = '!'; } bot.say( msg.to, msg.nick + ': ' + str + flag ); } } ); } } } };
var request = require( 'request' ); module.exports = { commands: { isup: { aliases: [ 'get', 'web' ], privileged: true, help: 'Performs a HTTP(S) request to an arbitrary host.', usage: [ 'host' ], command: function ( bot, msg ) { request( msg.args.host, function ( err, res, body ) { if ( err ) { bot.say( msg.to, msg.nick + ': ' + err.message ); } else { var str = 'HTTP/' + res.httpVersion + ' ' + res.req.method; str += ' ' + res.req.method + ' ' + res.request.href; str += + ' → ' + res.statusCode; var flag = ''; try { var headers = [ res.headers['content-type'], res.headers.server, body.length ]; str += headers.join( ' · ' ); } catch ( e ) { flag = '!'; } bot.say( msg.to, msg.nick + ': ' + str + flag ); } } ); } } } };
Check the type of the IndexInput rather than the Directory to detect native implementation. This is a simpler and more correct test. It also permits the Directory to return a mixture of native and non-native IndexInput implementations. git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150604 13f79535-47bb-0310-9956-ffa450edef68
package org.apache.lucene.index; /** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.store.GCJIndexInput; class GCJSegmentReader extends SegmentReader { /** Try to use an optimized native implementation of TermDocs. The optimized * implementation can only be used when the segment's directory is a * GCJDirectory and it is not in compound format. */ public final TermDocs termDocs() throws IOException { if (freqStream instanceof GCJIndexInput) { // it's a GCJIndexInput return new GCJTermDocs(this); // so can use GCJTermDocs } else { return super.termDocs(); } } }
package org.apache.lucene.index; /** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.store.GCJDirectory; class GCJSegmentReader extends SegmentReader { /** Try to use an optimized native implementation of TermDocs. The optimized * implementation can only be used when the segment's directory is a * GCJDirectory and it is not in compound format. */ public final TermDocs termDocs() throws IOException { if (directory() instanceof GCJDirectory // it's a GCJ directory && this.cfsReader == null) { // & not in compound format return new GCJTermDocs(this); // so can use GCJTermDocs } else { return super.termDocs(); } } }
Make use of the version module
from ._library import * from . import version from .version import module as __version__ from .version import api as __api_version__ def get_include(): """Returns the directory containing the C/C++ API include directives""" return __import__('pkg_resources').resource_filename(__name__, 'include') def get_config(): """Returns a string containing the configuration information. """ import pkg_resources from .version import externals packages = pkg_resources.require(__name__) this = packages[0] deps = packages[1:] retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version, version.api, this.location) retval += " - c/c++ dependencies:\n" for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k]) retval += " - python dependencies:\n" for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location) return retval.strip() # gets sphinx autodoc done right - don't remove it __all__ = [_ for _ in dir() if not _.startswith('_')]
from ._library import * from ._library import __version__, __api_version__ def get_include(): """Returns the directory containing the C/C++ API include directives""" return __import__('pkg_resources').resource_filename(__name__, 'include') def get_config(): """Returns a string containing the configuration information. """ import pkg_resources from .version import externals packages = pkg_resources.require(__name__) this = packages[0] deps = packages[1:] retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version, version.api, this.location) retval += " - c/c++ dependencies:\n" for k in sorted(externals): retval += " - %s: %s\n" % (k, externals[k]) retval += " - python dependencies:\n" for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location) return retval.strip() # gets sphinx autodoc done right - don't remove it __all__ = [_ for _ in dir() if not _.startswith('_')]
Add a high range, precision histogram for tests
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.network.api; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.network.api.session.SessionDetailsProvider; /** * Created by peter.lawrey on 22/01/15. */ @FunctionalInterface public interface TcpHandler { void process(Bytes in, Bytes out, SessionDetailsProvider sessionDetails); default void sendHeartBeat(Bytes out, SessionDetailsProvider sessionDetails) { } default void onEndOfConnection(boolean heartbeatTimeOut) { } }
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.network.api; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.network.api.session.SessionDetailsProvider; /** * Created by peter.lawrey on 22/01/15. */ @FunctionalInterface public interface TcpHandler { void process(Bytes in, Bytes out, SessionDetailsProvider sessionDetails); default void sendHeartBeat(Bytes outBBB, SessionDetailsProvider sessionDetails) { } default void onEndOfConnection(boolean heartbeatTimeOut) { } }
Increase version number to 0.1.2b
from setuptools import setup, find_packages with open('description.txt') as f: long_description = ''.join(f.readlines()) def get_requirements(): with open("requirements.txt") as f: return f.readlines() setup( author="Martin Chovanec", author_email="chovamar@fit.cvut.cz", classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", ], description="SacredBoard", long_description=long_description, license="MIT License", url="https://github.com/chovanecm/sacredboard", name="sacredboard", keywords="sacred", packages=find_packages(), include_package_data=True, entry_points={ "console_scripts": [ "sacredboard = sacredboard.webapp:run" ] }, install_requires=get_requirements(), setup_requires=["pytest-runner"], tests_require=["pytest"], version="0.1.2b" )
from setuptools import setup, find_packages with open('description.txt') as f: long_description = ''.join(f.readlines()) def get_requirements(): with open("requirements.txt") as f: return f.readlines() setup( author="Martin Chovanec", author_email="chovamar@fit.cvut.cz", classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", ], description="SacredBoard", long_description=long_description, license="MIT License", url="https://github.com/chovanecm/sacredboard", name="sacredboard", keywords="sacred", packages=find_packages(), include_package_data=True, entry_points={ "console_scripts": [ "sacredboard = sacredboard.webapp:run" ] }, install_requires=get_requirements(), setup_requires=["pytest-runner"], tests_require=["pytest"], version="0.1.1" )
Fix scroll to top when using the menu
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; const EXCEPTIONS = [ 'table', 'mitigation', 'adaptation', 'sectoral-information', 'ndcs', 'models', 'scenarios', 'indicators' ]; class ScrollToTop extends PureComponent { componentDidUpdate(prevProps) { const currentPath = this.props.location.pathname; const paths = currentPath.split('/'); const lastPath = paths.slice(paths.length - 1)[0]; if ( currentPath !== prevProps.location.pathname && EXCEPTIONS.indexOf(lastPath) === -1 ) { window.scrollTo(0, 0); } } render() { return this.props.children; } } ScrollToTop.propTypes = { location: PropTypes.object.isRequired, children: PropTypes.node }; export default withRouter(ScrollToTop);
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router'; const EXCEPTIONS = [ 'table', 'mitigation', 'adaptation', 'sectoral-information', 'ndcs' ]; class ScrollToTop extends PureComponent { componentDidUpdate(prevProps) { const currentPath = this.props.location.pathname; const paths = currentPath.split('/'); const lastPath = paths.slice(paths.length - 1)[0]; if ( currentPath !== prevProps.location.pathname && EXCEPTIONS.indexOf(lastPath) === -1 ) { window.scrollTo(0, 0); } } render() { return this.props.children; } } ScrollToTop.propTypes = { location: PropTypes.object.isRequired, children: PropTypes.node }; export default withRouter(ScrollToTop);
Add ability to set specific nodes as focused nodes
/** * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import FocusedNodeView from '../focused/focusedNodeView'; import Node from '../base/node'; import NodeViewStandard from '../base/nodeViewStandard'; class RegionNode extends Node { constructor (node) { node.size = node.size || 60; super(node, 'region'); this.loaded = true; } isDraggable () { return true; } isInteractive () { return true; } render () { // Set the default view renderer if (this.nodeView === 'focused') { this.view = new FocusedNodeView(this); } else { this.view = new NodeViewStandard(this); } } } export default RegionNode;
/** * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import Node from '../base/node'; import NodeViewStandard from '../base/nodeViewStandard'; class RegionNode extends Node { constructor (node) { node.size = node.size || 60; super(node, 'region'); this.loaded = true; } isDraggable () { return true; } isInteractive () { return true; } render () { // Set the default view renderer this.view = new NodeViewStandard(this); } } export default RegionNode;
Write stimuli schedule to csv file.
#!/usr/bin/python import csv import pprint p = 0 # read schedule (from SCRT) schedule_f = 'schedule_' + str(p) inf = open(schedule_f,'r') for line in inf.readlines(): line = line.rstrip() schedule = line.split(' ') inf.close() # allocate stimuli and write csv a = 0 b = [] phase = '' csvfile = open('stimuli_' + str(p) + '.csv', 'wb') writer = csv.writer(csvfile, delimiter=',') for session in range(1,36): writer.writerow([session]) blocks = '' previous = phase phase = schedule[session - 1] if phase == 'B': if phase != previous: transition = session % 10 b = [transition] repeat = 0 if repeat == 3: b.append((b[-1] + 1) % 10) repeat = 0 a = (b[-1] + 1) % 10 repeat += 1 else: a = session % 10 writer.writerow(b) writer.writerow([a])
#!/usr/bin/python import csv import pprint p = 0 # read schedule (from SCRT) schedule_f = 'schedule_' + str(p) inf = open(schedule_f,'r') for line in inf.readlines(): line = line.rstrip() schedule = line.split(' ') inf.close() # allocate stimuli a = 0 b = [] phase = '' for session in range(1,36): print "%s" % session blocks = '' previous = phase phase = schedule[session - 1] if phase == 'B': if phase != previous: transition = session % 10 b = [transition] repeat = 0 if repeat == 3: b.append((b[-1] + 1) % 10) repeat = 0 a = (b[-1] + 1) % 10 repeat += 1 else: a = session % 10 print ',' . join(map(str,b)) print str(a)
Revert "remove the dest tree and recreate it" This reverts commit becc4657acea505594836e62c49de2b4cb0160a9.
#!/usr/bin/env python import os import sys import shutil from version import full_version from optparse import OptionParser import pkgutils def main(): usage = "usage: %prog [destination path]" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: parser.print_usage() sys.exit(1) dest = args[0] build_dir = pkgutils.package_builder_dir() binary_name = pkgutils.package_binary() binary = os.path.join(build_dir, binary_name) dest = os.path.join(dest, '%s-monitoring-agent-%s' % (pkgutils.pkg_dir(), full_version)) if pkgutils.pkg_type() == 'windows': dest += '.msi' print("Moving %s to %s" % (binary, dest)) shutil.move(binary, dest) if pkgutils.pkg_type() != 'windows': shutil.move(binary + ".sig", dest + ".sig") if __name__ == "__main__": main()
#!/usr/bin/env python import os import sys import shutil from version import full_version from optparse import OptionParser import pkgutils def main(): usage = "usage: %prog [destination path]" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: parser.print_usage() sys.exit(1) dest = args[0] shutil.rmtree(dest, True) os.mkdir(dest) build_dir = pkgutils.package_builder_dir() binary_name = pkgutils.package_binary() binary = os.path.join(build_dir, binary_name) dest = os.path.join(dest, '%s-monitoring-agent-%s' % (pkgutils.pkg_dir(), full_version)) if pkgutils.pkg_type() == 'windows': dest += '.msi' print("Moving %s to %s" % (binary, dest)) shutil.move(binary, dest) if pkgutils.pkg_type() != 'windows': shutil.move(binary + ".sig", dest + ".sig") if __name__ == "__main__": main()
Replace `execfile()` with `exec(open().read())` for python3
from setuptools import setup, find_packages import sys exec(open('yas3fs/_version.py').read()) requires = ['setuptools>=2.2', 'boto>=2.25.0'] # Versions of Python pre-2.7 require argparse separately. 2.7+ and 3+ all # include this as the replacement for optparse. if sys.version_info[:2] < (2, 7): requires.append("argparse") setup( name='yas3fs', version=__version__, description='YAS3FS (Yet Another S3-backed File System) is a Filesystem in Userspace (FUSE) interface to Amazon S3.', packages=find_packages(), author='Danilo Poccia', author_email='dpoccia@gmail.com', url='https://github.com/danilop/yas3fs', install_requires=requires, entry_points = { 'console_scripts': ['yas3fs = yas3fs:main'] }, )
from setuptools import setup, find_packages import sys execfile('yas3fs/_version.py') requires = ['setuptools>=2.2', 'boto>=2.25.0'] # Versions of Python pre-2.7 require argparse separately. 2.7+ and 3+ all # include this as the replacement for optparse. if sys.version_info[:2] < (2, 7): requires.append("argparse") setup( name='yas3fs', version=__version__, description='YAS3FS (Yet Another S3-backed File System) is a Filesystem in Userspace (FUSE) interface to Amazon S3.', packages=find_packages(), author='Danilo Poccia', author_email='dpoccia@gmail.com', url='https://github.com/danilop/yas3fs', install_requires=requires, entry_points = { 'console_scripts': ['yas3fs = yas3fs:main'] }, )
Add collections package to required list.
#!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup from glob import glob classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Topic :: Scientific/Engineering :: Bio-Informatics', ] exec(open("goatools/version.py").read()) setup( name="goatools", version=__version__, author='Haibao Tang', author_email='tanghaibao@gmail.com', packages=['goatools'], scripts=glob('scripts/*.py'), license='BSD', classifiers=classifiers, url='http://github.com/tanghaibao/goatools', description="Python scripts to find enrichment of GO terms", long_description=open("README.rst").read(), install_requires=['fisher', 'wget', 'collections', 'xlsxwriter', 'statsmodels'] )
#!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup from glob import glob classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Topic :: Scientific/Engineering :: Bio-Informatics', ] exec(open("goatools/version.py").read()) setup( name="goatools", version=__version__, author='Haibao Tang', author_email='tanghaibao@gmail.com', packages=['goatools'], scripts=glob('scripts/*.py'), license='BSD', classifiers=classifiers, url='http://github.com/tanghaibao/goatools', description="Python scripts to find enrichment of GO terms", long_description=open("README.rst").read(), install_requires=['fisher', 'wget', 'xlsxwriter', 'statsmodels'] )
Add already the UNMINIFIED out-commented block.
<?php /////////////////////////////////////////////////////// // ---------------------------------------------------------- // SNIPPET // ---------------------------------------------------------- // No-CTM fallback scripts (e.g. plain resrc) // ---------------------------------------------------------- // Check for CTM, and if absent load ReSRC aynchonously // (http://www.resrc.it/docs/javascript) // ---------------------------------------------------------- ///////////////////////////////////////////////////////////// ?> <script> function cutsTheMustard() { if('querySelector' in document && 'localStorage' in window && 'addEventListener' in window) { return true; } else { return false; } } if(cutsTheMustard() === false) { var lazyloads = document.querySelectorAll('img.lazyload'); for(i = 0; i < lazyloads.length; i++) { // Set data-src as src var datasrc = lazyloads[i].getAttribute('data-src'); lazyloads[i].setAttribute('src', datasrc); // Set/undo some no-js styles to show images nicely lazyloads[i].style.display = 'block'; lazyloads[i].parentNode.style.display = 'block'; lazyloads[i].parentNode.style.paddingBottom = '0px'; } } </script> <?php /* ///////////////////// UNMINIFIED! ///////////////////// <script> unminified here! </script> ////////////////////////////////////////////////////////// */ ?>
<?php /////////////////////////////////////////////////////// // ---------------------------------------------------------- // SNIPPET // ---------------------------------------------------------- // No-CTM fallback scripts (e.g. plain resrc) // ---------------------------------------------------------- // Check for CTM, and if absent load ReSRC aynchonously // (http://www.resrc.it/docs/javascript) // ---------------------------------------------------------- ///////////////////////////////////////////////////////////// ?> <script> function cutsTheMustard() { if('querySelector' in document && 'localStorage' in window && 'addEventListener' in window) { return true; } else { return false; } } if(cutsTheMustard() === false) { var lazyloads = document.querySelectorAll('img.lazyload'); for(i = 0; i < lazyloads.length; i++) { // Set data-src as src var datasrc = lazyloads[i].getAttribute('data-src'); lazyloads[i].setAttribute('src', datasrc); // Set/undo some no-js styles to show images nicely lazyloads[i].style.display = 'block'; lazyloads[i].parentNode.style.display = 'block'; lazyloads[i].parentNode.style.paddingBottom = '0px'; } } </script>
Return OriginKindUnknown with parsing errors.
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package resource import ( "github.com/juju/errors" ) // These are the valid kinds of resource origin. const ( OriginKindUnknown OriginKind = "" OriginKindUpload OriginKind = "upload" OriginKindStore OriginKind = "store" ) var knownOriginKinds = map[OriginKind]bool{ OriginKindUpload: true, OriginKindStore: true, } // OriginKind identifies the kind of a resource origin. type OriginKind string // ParseOriginKind converts the provided string into an OriginKind. // If it is not a known origin kind then an error is returned. func ParseOriginKind(value string) (OriginKind, error) { o := OriginKind(value) if !knownOriginKinds[o] { return OriginKindUnknown, errors.Errorf("unknown origin %q", value) } return o, nil } // String returns the printable representation of the origin kind. func (o OriginKind) String() string { return string(o) } // Validate ensures that the origin is correct. func (o OriginKind) Validate() error { if !knownOriginKinds[o] { return errors.NewNotValid(nil, "unknown origin") } return nil }
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package resource import ( "github.com/juju/errors" ) // These are the valid kinds of resource origin. const ( OriginKindUnknown OriginKind = "" OriginKindUpload OriginKind = "upload" OriginKindStore OriginKind = "store" ) var knownOriginKinds = map[OriginKind]bool{ OriginKindUpload: true, OriginKindStore: true, } // OriginKind identifies the kind of a resource origin. type OriginKind string // ParseOriginKind converts the provided string into an OriginKind. // If it is not a known origin kind then an error is returned. func ParseOriginKind(value string) (OriginKind, error) { o := OriginKind(value) if !knownOriginKinds[o] { return o, errors.Errorf("unknown origin %q", value) } return o, nil } // String returns the printable representation of the origin kind. func (o OriginKind) String() string { return string(o) } // Validate ensures that the origin is correct. func (o OriginKind) Validate() error { if !knownOriginKinds[o] { return errors.NewNotValid(nil, "unknown origin") } return nil }
Set settings for e2e tests correctly
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1: if sys.argv[1] == 'test': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" elif sys.argv[1] == 'pipeline_e2e_tests': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.e2etest" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1 and sys.argv[1] in ['test', 'pipeline_e2e_tests']: os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Use pkg_resources to read README.rst
#!/usr/bin/env python # Copyright (c) 2013 Soren Hansen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages import pkg_resources setup( name='basicdb', version='0.1', description='Basic database service', long_description=pkg_resources.resource_string(__name__, "README.rst"), author='Soren Hansen', author_email='soren@linux2go.dk', url='http://github.com/sorenh/basicdb', packages=find_packages(), include_package_data=True, license='Apache 2.0', keywords='basicdb simpledb')
#!/usr/bin/env python # Copyright (c) 2013 Soren Hansen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages setup( name='basicdb', version='0.1', description='Basic database service', long_description=open('README.rst', 'r').read(), author='Soren Hansen', author_email='soren@linux2go.dk', url='http://github.com/sorenh/basicdb', packages=find_packages(), include_package_data=True, license='Apache 2.0', keywords='basicdb simpledb')
Add include directory and c library file.
from distutils.core import setup, Extension module1 = Extension('foolib', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0')], include_dirs = ['../../cxx/include'], sources = ['foolibmodule.c', '../../cxx/src/foolib_c.cxx']) setup (name = 'foolib', version = '1.0', description = 'This is a demo package', author = 'Tom Kraljevic', author_email = 'tomk@tomk.net', url = 'http://example-of-where-to-put-url.org', long_description = ''' This is really just a demo package. ''', ext_modules = [module1])
from distutils.core import setup, Extension module1 = Extension('foolib', define_macros = [('MAJOR_VERSION', '1'), ('MINOR_VERSION', '0')], sources = ['foolibmodule.c']) setup (name = 'foolib', version = '1.0', description = 'This is a demo package', author = 'Tom Kraljevic', author_email = 'tomk@tomk.net', url = 'http://example-of-where-to-put-url.org', long_description = ''' This is really just a demo package. ''', ext_modules = [module1])
Make sure to load the S3 cache file when available
import json import os from tempfile import gettempdir import boto3 from botocore.exceptions import ClientError import requests def fetch_json(uri): """ Perform an HTTP GET on the given uri, return the results as json. Args: uri: the string URI to fetch. Returns: A JSON object with the response or None if the status code of the response is an error code. """ r = requests.get(uri) if r.status_code != requests.codes.ok: return None return r.json() def get_s3_json_content(s3_bucket, s3_key): """Download and parse a json file stored on AWS S3. The file is downloaded and then cached for future use. """ local_filename = '_'.join([s3_bucket, s3_key]).replace('/', '_') local_path = os.path.join(gettempdir(), local_filename) if not os.path.exists(local_path): with open(local_path, 'wb') as data: try: s3 = boto3.client('s3') s3.download_fileobj(s3_bucket, s3_key, data) except ClientError: return None with open(local_path, 'r') as data: return json.loads(data.read())
import json import os from tempfile import gettempdir import boto3 from botocore.exceptions import ClientError import requests def fetch_json(uri): """ Perform an HTTP GET on the given uri, return the results as json. Args: uri: the string URI to fetch. Returns: A JSON object with the response or None if the status code of the response is an error code. """ r = requests.get(uri) if r.status_code != requests.codes.ok: return None return r.json() def get_s3_json_content(s3_bucket, s3_key): """Download and parse a json file stored on AWS S3. The file is downloaded and then cached for future use. """ local_filename = '_'.join([s3_bucket, s3_key]).replace('/', '_') local_path = os.path.join(gettempdir(), local_filename) if not os.path.exists(local_path): with open(local_path, 'wb') as data: try: s3 = boto3.client('s3') s3.download_fileobj(s3_bucket, s3_key, data) except ClientError: return None with open(local_path, 'r') as data: return json.loads(data.read())
Move TODO tag to correct class
from flask.ext.wtf import Form from wtforms import SelectField, BooleanField, IntegerField, TextField, \ validators class TeamForm(Form): number = IntegerField("Number", [validators.Required(), validators.NumberRange(min=1, max=99999)]) name = TextField("Name", [validators.Required(), validators.Length(min=1, max=50)]) affiliation = TextField("Affiliation", [validators.Length(min=1, max=200)]) city = TextField("City", [validators.Length(min=1, max=50)]) state = TextField("State", [validators.Length(min=2, max=2)]) # TODO add validation class ScoreForm(Form): team_id = SelectField(u'Team', coerce=int) tree_branch_is_closer = BooleanField(default=False) tree_branch_is_intact = BooleanField(default=False) cargo_plane_location = SelectField(choices=[('0', 'None'), ('1', 'Yellow only'), ('2', 'Light blue')])
from flask.ext.wtf import Form from wtforms import SelectField, BooleanField, IntegerField, TextField, \ validators # TODO add vailidation class TeamForm(Form): number = IntegerField("Number", [validators.Required(), validators.NumberRange(min=1, max=99999)]) name = TextField("Name", [validators.Required(), validators.Length(min=1, max=50)]) affiliation = TextField("Affiliation", [validators.Length(min=1, max=200)]) city = TextField("City", [validators.Length(min=1, max=50)]) state = TextField("State", [validators.Length(min=2, max=2)]) class ScoreForm(Form): team_id = SelectField(u'Team', coerce=int) tree_branch_is_closer = BooleanField(default=False) tree_branch_is_intact = BooleanField(default=False) cargo_plane_location = SelectField(choices=[('0', 'None'), ('1', 'Yellow only'), ('2', 'Light blue')])
Update key usage when the usage_left counter is still greater than zero.
from datetime import datetime from django.db import models from django.contrib.auth.models import User class Key(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) usage_left = models.IntegerField(null=True, default=1) expires = models.DateTimeField(null=True) next = models.CharField(null=True, max_length=200) def __unicode__(self): return '%s (%s)' % (self.key, self.user.username) def is_valid(self): if self.usage_left is not None and self.usage_left <= 0: return False if self.expires is not None and self.expires < datetime.now(): return False return True def update_usage(self): if self.usage_left is not None and self.usage_left > 0: self.usage_left -= 1 self.save()
from datetime import datetime from django.db import models from django.contrib.auth.models import User class Key(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=40) created = models.DateTimeField(auto_now_add=True) usage_left = models.IntegerField(null=True, default=1) expires = models.DateTimeField(null=True) next = models.CharField(null=True, max_length=200) def __unicode__(self): return '%s (%s)' % (self.key, self.user.username) def is_valid(self): if self.usage_left is not None and self.usage_left <= 0: return False if self.expires is not None and self.expires < datetime.now(): return False return True def update_usage(self): if self.usage_left is not None: self.usage_left -= 1 self.save()
Add planning and template getKeywords function
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.logging.Level; import java.util.logging.Logger; @WebServlet("/search") public class SearchServlet extends HttpServlet { private static final Logger LOGGER = Logger.getLogger(SearchServlet.class.getName()); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { //get location //filter by location and cutoff outside it //get tags //drop all without first tag //those with most tags in common with search go to top //those closest to the user go to the top } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { } /** * Returns keywords from an event (currently using just the title * and description) based off an algorithm */ public List<String> getKeywords(String title, String desc) { } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.logging.Level; import java.util.logging.Logger; @WebServlet("/search") public class SearchServlet extends HttpServlet { private static final Logger LOGGER = Logger.getLogger(SearchServlet.class.getName()); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { } }
Add Python 3.6 as a supported version.
import re from setuptools import setup with open('nexmo/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) setup(name='nexmo', version=version, description='Nexmo Client Library for Python', long_description='This is the Python client library for Nexmo\'s API. To use it you\'ll need a Nexmo account. Sign up `for free at nexmo.com <http://nexmo.com?src=python-client-library>`_.', url='http://github.com/Nexmo/nexmo-python', author='Tim Craft', author_email='mail@timcraft.com', license='MIT', packages=['nexmo'], platforms=['any'], install_requires=['requests', 'PyJWT', 'cryptography'], classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ])
import re from setuptools import setup with open('nexmo/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) setup(name='nexmo', version=version, description='Nexmo Client Library for Python', long_description='This is the Python client library for Nexmo\'s API. To use it you\'ll need a Nexmo account. Sign up `for free at nexmo.com <http://nexmo.com?src=python-client-library>`_.', url='http://github.com/Nexmo/nexmo-python', author='Tim Craft', author_email='mail@timcraft.com', license='MIT', packages=['nexmo'], platforms=['any'], install_requires=['requests', 'PyJWT', 'cryptography'], classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ])
Set test to ignore failed MBean registration
package org.axonframework.boot.autoconfig; import org.axonframework.axonserver.connector.query.AxonServerQueryBus; import org.axonframework.queryhandling.QueryBus; import org.axonframework.queryhandling.QueryUpdateEmitter; import org.junit.*; import org.junit.runner.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @ContextConfiguration @EnableAutoConfiguration @RunWith(SpringRunner.class) @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class AxonServerAutoConfigurationTest { @Autowired private QueryBus queryBus; @Autowired private QueryUpdateEmitter updateEmitter; @Test public void testAxonServerQueryBusConfiguration() { assertTrue(queryBus instanceof AxonServerQueryBus); assertSame(updateEmitter, queryBus.queryUpdateEmitter()); } }
package org.axonframework.boot.autoconfig; import org.axonframework.axonserver.connector.query.AxonServerQueryBus; import org.axonframework.queryhandling.QueryBus; import org.axonframework.queryhandling.QueryUpdateEmitter; import org.junit.*; import org.junit.runner.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @ContextConfiguration @EnableAutoConfiguration @RunWith(SpringRunner.class) public class AxonServerAutoConfigurationTest { @Autowired private QueryBus queryBus; @Autowired private QueryUpdateEmitter updateEmitter; @Test public void testAxonServerQueryBusConfiguration() { assertTrue(queryBus instanceof AxonServerQueryBus); assertSame(updateEmitter, queryBus.queryUpdateEmitter()); } }
Add commit hash to errbit
package main import ( "github.com/deshboard/boilerplate-service/app" "github.com/kelseyhightower/envconfig" "gopkg.in/airbrake/gobrake.v2" logrus_airbrake "gopkg.in/gemnasium/logrus-airbrake-hook.v2" ) func init() { err := envconfig.Process("app", config) if err != nil { logger.Fatal(err) } // Initialize Airbrake if config.AirbrakeEnabled { airbrakeHook := logrus_airbrake.NewHook(config.AirbrakeProjectID, config.AirbrakeAPIKey, config.Environment) airbrake := airbrakeHook.Airbrake airbrake.SetHost(config.AirbrakeHost) airbrake.AddFilter(func(notice *gobrake.Notice) *gobrake.Notice { notice.Context["version"] = app.Version notice.Context["commit"] = app.CommitHash return notice }) logger.Hooks.Add(airbrakeHook) closers = append(closers, airbrake) } }
package main import ( "github.com/deshboard/boilerplate-service/app" "github.com/kelseyhightower/envconfig" "gopkg.in/airbrake/gobrake.v2" logrus_airbrake "gopkg.in/gemnasium/logrus-airbrake-hook.v2" ) func init() { err := envconfig.Process("app", config) if err != nil { logger.Fatal(err) } // Initialize Airbrake if config.AirbrakeEnabled { airbrakeHook := logrus_airbrake.NewHook(config.AirbrakeProjectID, config.AirbrakeAPIKey, config.Environment) airbrake := airbrakeHook.Airbrake airbrake.SetHost(config.AirbrakeHost) airbrake.AddFilter(func(notice *gobrake.Notice) *gobrake.Notice { notice.Context["version"] = app.Version return notice }) logger.Hooks.Add(airbrakeHook) closers = append(closers, airbrake) } }
Remove middleware function. Returns current instance.
'use strict'; var mongodb = require('mongodb'); var nodefn = require('when/node'); var util = require('util'); // ### Errors ### function MongoConnectionError(error) { this.name = 'MongoConnectionError'; this.message = error; } util.inherits(MongoConnectionError, Error); function MongoAdapter() { this._connectURI = 'mongodb://0.0.0.0:27017/'; this._databaseName = 'testowa'; this.collections = { 'users': undefined }; } MongoAdapter.prototype.connect = function () { var self = this; var MongoClient = mongodb.MongoClient; var promisedConnect = nodefn.call(MongoClient.connect, this._connectURI + this._databaseName); return promisedConnect.then(function (db) { Object.keys(self.collections).forEach(function (collectionName) { self.collections[collectionName] = db.collection(collectionName); }); return self; }).catch(function (error) { throw new MongoConnectionError(error); }); }; module.exports.MongoAdapter = MongoAdapter;
'use strict'; var mongodb = require('mongodb'); var nodefn = require('when/node'); var util = require('util'); // ### Errors ### function MongoConnectionError(error) { this.name = 'MongoConnectionError'; this.message = error; } util.inherits(MongoConnectionError, Error); function MongoAdapter() { this._connectURI = 'mongodb://0.0.0.0:27017/'; this._databaseName = 'testowa'; this.collections = { 'users': undefined }; } MongoAdapter.prototype.connect = function () { var self = this; return function (req, res, next) { var MongoClient = mongodb.MongoClient; var promisedConnect = nodefn.call(MongoClient.connect, self._connectURI + self._databaseName); return promisedConnect.then(function (db) { Object.keys(self.collections).forEach(function (collectionName) { self.collections[collectionName] = db.collection(collectionName); }); next(); }).catch(function (error) { throw new MongoConnectionError(error); }); }; }; module.exports.MongoAdapter = MongoAdapter;
Fix bug about not displaying injected prestations In previous implem, if a prestation was injected in one test, it would never be displayed in other tests
var _ = require('lodash'); var periods = require('./periods'); var PRESTATIONS = require('../prestations'); module.exports = function reverseMap(openFiscaFamille, date, injectedRessources) { var period = periods.map(date); var prestationsToDisplay = _.cloneDeep(PRESTATIONS); // Don't show prestations that have been injected by the user, and not calculated by the simulator _.forEach(injectedRessources, function(resource) { delete prestationsToDisplay[resource]; }); return _.mapValues(prestationsToDisplay, function(format, prestationName) { var type = format.type, computedPrestation = openFiscaFamille[prestationName], result = computedPrestation[period]; var uncomputabilityReason = openFiscaFamille[prestationName + '_non_calculable'] && openFiscaFamille[prestationName + '_non_calculable'][period]; if (uncomputabilityReason) { return uncomputabilityReason; } if (format.montantAnnuel) { result *= 12; } if (type == Number) { result = Number(result.toFixed(2)); } return result; }); };
var _ = require('lodash'); var periods = require('./periods'); var PRESTATIONS = require('../prestations'); module.exports = function reverseMap(openFiscaFamille, date, injectedRessources) { var period = periods.map(date); // Don't show prestations that have been injected by the user, and not calculated by the simulator _.forEach(injectedRessources, function(resource) { delete PRESTATIONS[resource]; }); return _.mapValues(PRESTATIONS, function(format, prestationName) { var type = format.type, computedPrestation = openFiscaFamille[prestationName], result = computedPrestation[period]; var uncomputabilityReason = openFiscaFamille[prestationName + '_non_calculable'] && openFiscaFamille[prestationName + '_non_calculable'][period]; if (uncomputabilityReason) { return uncomputabilityReason; } if (format.montantAnnuel) { result *= 12; } if (type == Number) { result = Number(result.toFixed(2)); } return result; }); };
Fix up some raw types git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@804686 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: a63ffb7f588237f535fcfc739967ddd91ac6bfe2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.testelement; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.apache.jmeter.threads.JMeterVariables; /** * @version $Revision$ */ public class VariablesCollection implements Serializable { private static final long serialVersionUID = 240L; private Map<String, JMeterVariables> varMap = new HashMap<String, JMeterVariables>(); public void addJMeterVariables(JMeterVariables jmVars) { varMap.put(Thread.currentThread().getName(), jmVars); } public JMeterVariables getVariables() { return varMap.get(Thread.currentThread().getName()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.testelement; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.apache.jmeter.threads.JMeterVariables; /** * @version $Revision$ */ public class VariablesCollection implements Serializable { private Map varMap = new HashMap(); public void addJMeterVariables(JMeterVariables jmVars) { varMap.put(Thread.currentThread().getName(), jmVars); } public JMeterVariables getVariables() { return (JMeterVariables) varMap.get(Thread.currentThread().getName()); } }
Fix text align rigth on the monster list table.
<table class="table table-bordered tablesorter"> <thead> <tr> <th></th> <th>Name</th> <th>HP</th> <th>Dmg</th> <th>MaxDmg</th> <th>AvgDmg</th> <th>Melee sk</th> <th>Dodge sk</th> </tr> </thead> @foreach ($data as $monster) <tr> <td>{{ $monster->symbol }}</td> <td><a href="{{ route('monster.view', array($monster->id)) }}">{{ $monster->niceName }}</a></td> <td class="text-right">{{{ $monster->hp }}}</td> <td class="text-right">{{{ $monster->damage }}}</td> <td class="text-right">{{{ $monster->maxDamage }}}</td> <td class="text-right">{{{ $monster->avgDamage }}}</td> <td class="text-right">{{{ $monster->melee_skill }}}</td> <td class="text-right">{{{ $monster->dodge }}}</td> </tr> @endforeach </table> <script> $(function() { $(".tablesorter").tablesorter({ sortList: [[1,0]] }); }); </script>
<table class="table table-bordered tablesorter"> <thead> <tr> <th></th> <th>Name</th> <th>HP</th> <th>Dmg</th> <th>MaxDmg</th> <th>AvgDmg</th> <th>Melee sk</th> <th>Dodge sk</th> </tr> </thead> @foreach ($data as $monster) <tr> <td>{{ $monster->symbol }}</td> <td><a href="{{ route('monster.view', array($monster->id)) }}">{{ $monster->niceName }}</a></td> <td>{{{ $monster->hp }}}</td> <td>{{{ $monster->damage }}}</td> <td>{{{ $monster->maxDamage }}}</td> <td>{{{ $monster->avgDamage }}}</td> <td>{{{ $monster->melee_skill }}}</td> <td>{{{ $monster->dodge }}}</td> </tr> @endforeach </table> <script> $(function() { $(".tablesorter").tablesorter({ sortList: [[1,0]] }); }); </script>
Update dsub version to 0.3.2 PiperOrigin-RevId: 252927917
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.2'
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Single source of truth for dsub's version. This must remain small and dependency-free so that any dsub module may import it without creating circular dependencies. Note that this module is parsed as a text file by setup.py and changes to the format of this file could break setup.py. The version should follow formatting requirements specified in PEP-440. - https://www.python.org/dev/peps/pep-0440 A typical release sequence will be versioned as: 0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ... """ DSUB_VERSION = '0.3.2.dev0'
Use camel case for names of mojos and avoid hypens
package io.takari.maven.plugins.resources; import java.io.File; import java.util.List; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @Mojo(name = "processResources", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, configurator = "takari-mojo") public class ProcessResources extends AbstractProcessResourcesMojo { @Parameter(defaultValue = "${project.build.outputDirectory}", property = "resources.outputDirectory") private File outputDirectory; @Parameter private List<Resource> resources; @Override protected void executeMojo() throws MojoExecutionException { process(resources != null ? resources : project.getBuild().getResources(), outputDirectory); } }
package io.takari.maven.plugins.resources; import java.io.File; import java.util.List; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @Mojo(name = "process-resources", defaultPhase = LifecyclePhase.PROCESS_RESOURCES, configurator = "takari-mojo") public class ProcessResources extends AbstractProcessResourcesMojo { @Parameter(defaultValue = "${project.build.outputDirectory}", property = "resources.outputDirectory") private File outputDirectory; @Parameter private List<Resource> resources; @Override protected void executeMojo() throws MojoExecutionException { process(resources != null ? resources : project.getBuild().getResources(), outputDirectory); } }
Fix BrowserSync to cooperate with Tracy debug bar
module.exports = function(gulp, config) { return function(done) { var c = require('better-console') c.info('watch reload') var browsersync = require('browser-sync') var fs = require('fs') var watch = require('gulp-watch') var filter = require('gulp-filter') var options = {} if(config.proxy) { options.proxy = config.proxy } else { options.server = { baseDir: config.dist_folder } } options.snippetOptions = { rule: { match: /<body[^>]*>/i, fn: function (snippet, match) { if(match === '<body id=\\"tracy-debug\\">') { return match } return match + snippet; } } } browsersync(options) var glob = [config.dist_folder + '/**/*.*'] if(config.watch) { glob = glob.concat(config.watch) } var handleReloadFile = function(file) { // files only if(!fs.existsSync(file.path) || !fs.lstatSync(file.path).isFile()) { return false } c.log('- handling reload', file.path) browsersync.reload(file.path) } return watch(glob, { base: config.dir, read: false }).pipe(filter(handleReloadFile)) } }
module.exports = function(gulp, config) { return function(done) { var c = require('better-console') c.info('watch reload') var browsersync = require('browser-sync') var fs = require('fs') var watch = require('gulp-watch') var filter = require('gulp-filter') var options = {} if(config.proxy) { options.proxy = config.proxy } else { options.server = { baseDir: config.dist_folder } } browsersync(options) var glob = [config.dist_folder + '/**/*.*'] if(config.watch) { glob = glob.concat(config.watch) } var handleReloadFile = function(file) { // files only if(!fs.existsSync(file.path) || !fs.lstatSync(file.path).isFile()) { return false } c.log('- handling reload', file.path) browsersync.reload(file.path) } return watch(glob, { base: config.dir, read: false }).pipe(filter(handleReloadFile)) } }
Fix accuracy when topk > num_classes
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [ correct[:k].reshape(-1).float().sum(0) * 100. / batch_size if k <= maxk else torch.tensor(100.) for k in topk ]
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
Fix loading bug with last merge
var baseHref = 'http://localhost:' + process.env.npm_package_config_port var appEntry = baseHref + '/gen/app.entry.js' var baseNode = document.createElement('base') baseNode.href = baseHref document.getElementsByTagName('head')[0].appendChild(baseNode) const createScript = function (scriptPath) { return new Promise(function (resolve, reject) { var script = document.createElement('script') script.type = 'text/javascript' script.src = scriptPath script.async = true script.onload = resolve script.onerror = reject document.body.appendChild(script) }) } document.querySelector('#webpackLoading').style.display = 'block' createScript(appEntry).catch(function () { document.querySelector('#webpackLoading').style.display = 'none' document.querySelector('#setupError').style.display = 'block' })
var baseHref = `http://localhost: ${process.env.npm_package_config_port}` var appEntry = `${baseHref} /gen/app.entry.js` var baseNode = document.createElement('base') baseNode.href = baseHref document.getElementsByTagName('head')[0].appendChild(baseNode) const createScript = function (scriptPath) { return new Promise((resolve, reject) => { var script = document.createElement('script') script.type = 'text/javascript' script.src = scriptPath script.async = true script.onload = resolve script.onerror = reject document.body.appendChild(script) }) } document.querySelector('#webpackLoading').style.display = 'block' createScript(appEntry).catch(() => { document.querySelector('#webpackLoading').style.display = 'none' document.querySelector('#setupError').style.display = 'block' })
[ReactNative] Fix reloading in debug mode sometimes crashes packager
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var WebSocketServer = require('ws').Server; function attachToServer(server, path) { var wss = new WebSocketServer({ server: server, path: path }); var clients = []; wss.on('connection', function(ws) { clients.push(ws); var allClientsExcept = function(ws) { return clients.filter(function(cn) { return cn !== ws; }); }; ws.onerror = function() { clients = allClientsExcept(ws); }; ws.onclose = function() { clients = allClientsExcept(ws); }; ws.on('message', function(message) { allClientsExcept(ws).forEach(function(cn) { try { // Sometimes this call throws 'not opened' cn.send(message); } catch(e) { console.warn('WARN: ' + e.message); } }); }); }); } module.exports = { attachToServer: attachToServer };
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var WebSocketServer = require('ws').Server; function attachToServer(server, path) { var wss = new WebSocketServer({ server: server, path: path }); var clients = []; wss.on('connection', function(ws) { clients.push(ws); var allClientsExcept = function(ws) { return clients.filter(function(cn) { return cn !== ws; }); }; ws.onerror = function() { clients = allClientsExcept(ws); }; ws.onclose = function() { clients = allClientsExcept(ws); }; ws.on('message', function(message) { allClientsExcept(ws).forEach(function(cn) { cn.send(message); }); }); }); } module.exports = { attachToServer: attachToServer };
Remove spurious print statement in busbus.util.Lazy
from abc import ABCMeta, abstractmethod import six import busbus @six.add_metaclass(ABCMeta) class Iterable(object): def __iter__(self): return self @abstractmethod def __next__(self): return NotImplemented # Python 2 compatibility def next(self): return self.__next__() class Lazy(object): def __init__(self, f, *args): self.f = f self.args = args self.called = False def __get__(self, instance, owner): if not self.called: self.value = self.f(*self.args) self.called = True return self.value def entity_type(obj): try: if not isinstance(obj, type): obj = type(obj) return next(x for x in obj.mro() if x in busbus.ENTITIES) except StopIteration: raise TypeError def clsname(obj): return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
from abc import ABCMeta, abstractmethod import six import busbus @six.add_metaclass(ABCMeta) class Iterable(object): def __iter__(self): return self @abstractmethod def __next__(self): return NotImplemented # Python 2 compatibility def next(self): return self.__next__() class Lazy(object): def __init__(self, f, *args): self.f = f self.args = args self.called = False def __get__(self, instance, owner): if not self.called: self.value = self.f(*self.args) self.called = True print('Lazy.__get__ --> {0}'.format(self.value)) return self.value def entity_type(obj): try: if not isinstance(obj, type): obj = type(obj) return next(x for x in obj.mro() if x in busbus.ENTITIES) except StopIteration: raise TypeError def clsname(obj): return '{0}.{1}'.format(type(obj).__module__, type(obj).__name__)
Add breakline to better reading
#!/bin/python """ reversebinary puzzle for Spotify.com v1 Jose Antonio Navarrete You can find me at janavarretecristino@gmail.com Follow me on twitter @joseanavarrete """ import unittest MAX_VALUE = 1000000000 def reverse_binary(n): """ Receives an integer (n), converts it to its reverse binary """ if not 1 <= n <= MAX_VALUE: raise ValueError binary_str = bin(n) # '0bXXXX' where XXXX is n in binary return int(binary_str[::-1][:-2], 2) class ReverseBinaryTest(unittest.TestCase): def test_reverse_binary(self): self.assertEqual(reverse_binary(1), 1) self.assertEqual(reverse_binary(13), 11) self.assertEqual(reverse_binary(47), 61) def test_wrong_input(self): with self.assertRaises(ValueError): reverse_binary(0) reverse_binary(MAX_VALUE) def main(): unittest.main() if __name__ == '__main__': main()
#!/bin/python """ reversebinary puzzle for Spotify.com v1 Jose Antonio Navarrete You can find me at janavarretecristino@gmail.com Follow me on twitter @joseanavarrete """ import unittest MAX_VALUE = 1000000000 def reverse_binary(n): """ Receives an integer (n), converts it to its reverse binary """ if not 1 <= n <= MAX_VALUE: raise ValueError binary_str = bin(n) # '0bXXXX' where XXXX is n in binary return int(binary_str[::-1][:-2], 2) class ReverseBinaryTest(unittest.TestCase): def test_reverse_binary(self): self.assertEqual(reverse_binary(1), 1) self.assertEqual(reverse_binary(13), 11) self.assertEqual(reverse_binary(47), 61) def test_wrong_input(self): with self.assertRaises(ValueError): reverse_binary(0) reverse_binary(MAX_VALUE) def main(): unittest.main() if __name__ == '__main__': main()
Create new advanced watcher doc if id does not exists.
import { uiModules } from 'ui/modules'; import { Notifier } from 'ui/notify/notifier'; import routes from 'ui/routes'; import template from './watcher_raw_edit.html'; import controller from './watcher_raw_edit'; routes .when('/watcher/raw/:id/edit') .when('/watcher/raw/:type/new') .defaults(/watcher\/raw\/(:id\/edit|:type\/new)/, { template, controller, controllerAs: 'watcherRawEdit', bindToController: true, resolve: { watcher: function ($injector) { const $route = $injector.get('$route'); const kbnUrl = $injector.get('kbnUrl'); const watcherService = $injector.get('Watcher'); const notifier = new Notifier({ location: 'Watcher' }); const watcherId = $route.current.params.id; if (!watcherId) { return watcherService.new('watcher').catch(function (err) { notifier.error(err); kbnUrl.redirect('/'); }); } return watcherService.get(watcherId).catch(function (err) { notifier.error(err); kbnUrl.redirect('/'); }); }, }, });
import { uiModules } from 'ui/modules'; import { Notifier } from 'ui/notify/notifier'; import routes from 'ui/routes'; import template from './watcher_raw_edit.html'; import controller from './watcher_raw_edit'; routes .when('/watcher/raw/:id/edit') .when('/watcher/raw/:type/new') .defaults(/watcher\/raw\/(:id\/edit|:type\/new)/, { template, controller, controllerAs: 'watcherRawEdit', bindToController: true, resolve: { watcher: function ($injector) { const $route = $injector.get('$route'); const kbnUrl = $injector.get('kbnUrl'); const watcherService = $injector.get('Watcher'); const notifier = new Notifier({ location: 'Watcher' }); const watcherId = $route.current.params.id; return watcherService.get(watcherId).catch(function (err) { notifier.error(err); kbnUrl.redirect('/'); }); }, }, });
Disable random pathfinding for workers
import { fastMap, fastObjects } from '../../../world'; import { clone, nextCoord } from '../../../utils'; import { collidableObjects } from '../../../collisions'; import config from '../../../config'; import workerPool from '../../../worker-pool'; export default function findWork() { if (this.working || this.waitingOnPath) return; const collidables = collidableObjects.concat(['chopper', 'collector', 'planter']); const workerArgs = [ fastMap, fastObjects, collidables, config.mapWidth, config.mapHeight, this.tile, this.targetObjects, // use this.targetObjects false, ]; this.waitingOnPath = true; workerPool.addTask(workerArgs, (pathToTree) => { if (pathToTree) { this.path = pathToTree.path; this.noPath = false; this.working = true; } else { // no available path to any trees this.cancelWork(true); } this.waitingOnPath = false; }); // if a path to a tree can't be found, worker will try again next time update calls it }
import { fastMap, fastObjects } from '../../../world'; import { clone, nextCoord } from '../../../utils'; import { collidableObjects } from '../../../collisions'; import config from '../../../config'; import workerPool from '../../../worker-pool'; export default function findWork() { if (this.working || this.waitingOnPath) return; const collidables = collidableObjects.concat(['chopper', 'collector', 'planter']); const workerArgs = [ fastMap, fastObjects, collidables, config.mapWidth, config.mapHeight, this.tile, this.targetObjects, // use this.targetObjects true, ]; this.waitingOnPath = true; workerPool.addTask(workerArgs, (pathToTree) => { if (pathToTree) { this.path = pathToTree.path; this.noPath = false; this.working = true; } else { // no available path to any trees this.cancelWork(true); } this.waitingOnPath = false; }); // if a path to a tree can't be found, worker will try again next time update calls it }
Use `sort`, not `text`, for search index table Summary: Ref T1191. The index's case sensitivity depends on the column type. Using `text` makes the search case-sensitive, which is not desirable. Test Plan: After adjustment, searched for "PROJECTS" and found hits against "projects". Reviewers: btrahan Reviewed By: btrahan Subscribers: epriestley Maniphest Tasks: T1191 Differential Revision: https://secure.phabricator.com/D10619
<?php final class PhabricatorSearchDocumentField extends PhabricatorSearchDAO { protected $phidType; protected $field; protected $auxPHID; protected $corpus; public function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_IDS => self::IDS_MANUAL, self::CONFIG_COLUMN_SCHEMA => array( 'phidType' => 'text4', 'field' => 'text4', 'auxPHID' => 'phid?', 'corpus' => 'sort?', ), self::CONFIG_KEY_SCHEMA => array( 'key_phid' => null, 'phid' => array( 'columns' => array('phid'), ), 'corpus' => array( 'columns' => array('corpus'), 'type' => 'FULLTEXT', ), ), ) + parent::getConfiguration(); } public function getIDKey() { return 'phid'; } }
<?php final class PhabricatorSearchDocumentField extends PhabricatorSearchDAO { protected $phidType; protected $field; protected $auxPHID; protected $corpus; public function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_IDS => self::IDS_MANUAL, self::CONFIG_COLUMN_SCHEMA => array( 'phidType' => 'text4', 'field' => 'text4', 'auxPHID' => 'phid?', 'corpus' => 'text?', ), self::CONFIG_KEY_SCHEMA => array( 'key_phid' => null, 'phid' => array( 'columns' => array('phid'), ), 'corpus' => array( 'columns' => array('corpus'), 'type' => 'FULLTEXT', ), ), ) + parent::getConfiguration(); } public function getIDKey() { return 'phid'; } }
Test what happens in dockerhub when a node test fails Signed-off-by: Tobias Sjöndin <04a8cd48feee91827ce7c6d1356384bcca091996@op5.com>
"use strict"; let chai = require('chai'); let expect = chai.expect; let Stream = require('../src/stream'); describe('Stream', () => { describe('#constructor', () => { it('returns an instanceof stream', () => { let stream = new Stream.default("123"); expect(stream).to.be.an.instanceof(Stream.default); }); it('can get the current value', () => { let stream = new Stream.default("123"); expect(stream.current()).to.eql("1"); }); it('can move the position forward', () => { let stream = new Stream.default("123"); stream.forward(); expect(stream.current()).to.eql('2'); }); it('can stream until condition is met', () => { let stream = new Stream.default("A stream of things"); let segment = stream.until(character => (character === 'o')); expect(segment).to.eql('A stream '); }); it('can move backwards in the stream', () => { let stream = new Stream.default("123"); let segment = stream.until(character => (character === '3')); expect(segment).to.eql('12'); stream.backward(); expect(stream.current()).to.eql('2'); }); it('will fail', () => { let stream = new Stream.default("123"); let segment = stream.until(character => (character === '3')); expect(segment).to.eql('12'); stream.backward(); expect(stream.current()).to.eql('1'); }); }); });
"use strict"; let chai = require('chai'); let expect = chai.expect; let Stream = require('../src/stream'); describe('Stream', () => { describe('#constructor', () => { it('returns an instanceof stream', () => { let stream = new Stream.default("123"); expect(stream).to.be.an.instanceof(Stream.default); }); it('can get the current value', () => { let stream = new Stream.default("123"); expect(stream.current()).to.eql("1"); }); it('can move the position forward', () => { let stream = new Stream.default("123"); stream.forward(); expect(stream.current()).to.eql('2'); }); it('can stream until condition is met', () => { let stream = new Stream.default("A stream of things"); let segment = stream.until(character => (character === 'o')); expect(segment).to.eql('A stream '); }); it('can move backwards in the stream', () => { let stream = new Stream.default("123"); let segment = stream.until(character => (character === '3')); expect(segment).to.eql('12'); stream.backward(); expect(stream.current()).to.eql('2'); }); }); });
Add very brief comments about the event types
from collections import defaultdict import traceback LINT_START = 'LINT_START' # (buffer_id) LINT_RESULT = 'LINT_RESULT' # (buffer_id, linter_name, errors) LINT_END = 'LINT_END' # (buffer_id) listeners = defaultdict(set) def subscribe(topic, fn): listeners[topic].add(fn) def unsubscribe(topic, fn): try: listeners[topic].remove(fn) except KeyError: pass def broadcast(topic, message=None): payload = message.copy() or {} for fn in listeners.get(topic, []): try: fn(**payload) except Exception: traceback.print_exc() map_fn_to_topic = {} def on(topic): def inner(fn): subscribe(topic, fn) map_fn_to_topic[fn] = topic return fn return inner def off(fn): topic = map_fn_to_topic.get(fn, None) if topic: unsubscribe(topic, fn)
from collections import defaultdict import traceback LINT_START = 'LINT_START' LINT_RESULT = 'LINT_RESULT' LINT_END = 'LINT_END' listeners = defaultdict(set) def subscribe(topic, fn): listeners[topic].add(fn) def unsubscribe(topic, fn): try: listeners[topic].remove(fn) except KeyError: pass def broadcast(topic, message=None): payload = message.copy() or {} for fn in listeners.get(topic, []): try: fn(**payload) except Exception: traceback.print_exc() map_fn_to_topic = {} def on(topic): def inner(fn): subscribe(topic, fn) map_fn_to_topic[fn] = topic return fn return inner def off(fn): topic = map_fn_to_topic.get(fn, None) if topic: unsubscribe(topic, fn)
Use NODE_ENV (with --production) to run production import(...) tests.
var selftest = require('../tool-testing/selftest.js'); var Sandbox = selftest.Sandbox; selftest.define("dynamic import(...) in development", function () { const s = new Sandbox(); s.createApp("dynamic-import-test-app-devel", "dynamic-import"); s.cd("dynamic-import-test-app-devel", run.bind(s, false)); }); selftest.define("dynamic import(...) in production", function () { const s = new Sandbox(); s.createApp("dynamic-import-test-app-prod", "dynamic-import"); s.cd("dynamic-import-test-app-prod", run.bind(s, true)); }); function run(isProduction) { const sandbox = this; const args = [ "test", "--once", "--full-app", "--driver-package", "dispatch:mocha-phantomjs" ]; if (isProduction) { sandbox.set("NODE_ENV", "production"); args.push("--production"); } else { sandbox.set("NODE_ENV", "development"); } const run = sandbox.run(...args); run.waitSecs(60); run.match("App running at"); run.match("SERVER FAILURES: 0"); run.match("CLIENT FAILURES: 0"); run.expectExit(0); }
var selftest = require('../tool-testing/selftest.js'); var Sandbox = selftest.Sandbox; selftest.define("dynamic import(...) in development", function () { const s = new Sandbox(); s.createApp("dynamic-import-test-app-devel", "dynamic-import"); s.cd("dynamic-import-test-app-devel", run.bind(s, false)); }); selftest.define("dynamic import(...) in production", function () { const s = new Sandbox(); s.createApp("dynamic-import-test-app-prod", "dynamic-import"); s.cd("dynamic-import-test-app-prod", run.bind(s, true)); }); function run(prod) { const sandbox = this; const args = [ "test", "--once", "--full-app", "--driver-package", "dispatch:mocha-phantomjs" ]; if (prod) { args.push("--production"); } const run = sandbox.run(...args); run.waitSecs(60); run.match("App running at"); run.match("SERVER FAILURES: 0"); run.match("CLIENT FAILURES: 0"); run.expectExit(0); }
:lipstick: Add more verbosity on test running
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATABASES'] = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':MEMORY:', } } if django.VERSION[:2] >= (1, 10): opts['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', }, ] settings.configure(**opts) if django.VERSION[:2] >= (1, 7): django.setup() if __name__ == "__main__": call_command('test', 'widget_tweaks', verbosity=2)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATABASES'] = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':MEMORY:', } } if django.VERSION[:2] >= (1, 10): opts['TEMPLATES'] = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', }, ] settings.configure(**opts) if django.VERSION[:2] >= (1, 7): django.setup() if __name__ == "__main__": call_command('test', 'widget_tweaks')
Fix for broken unit test in Linux
/* * Copyright 2017 anand. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sshd.shell.springboot.console; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * * @author anand */ public class ConsoleIOTest { @Test public void testConsoleIOAsJsonException() { assertTrue(ConsoleIO.asJson(new X("x")).startsWith("Error processing json output")); } @lombok.AllArgsConstructor private static class X { final String x; } }
/* * Copyright 2017 anand. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sshd.shell.springboot.console; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * * @author anand */ public class ConsoleIOTest { @Test public void testConsoleIOAsJsonException() { assertTrue(ConsoleIO.asJson(new X("x")).startsWith("Error processing json output")); } @lombok.AllArgsConstructor private static class X { private final String x; } }
Fix join channel ui moving when sorting channels Fixes #2218
"use strict"; const $ = require("jquery"); const socket = require("../socket"); const options = require("../options"); socket.on("sync_sort", function(data) { // Syncs the order of channels or networks when they are reordered if (options.ignoreSortSync) { options.ignoreSortSync = false; return; // Ignore syncing because we 'caused' it } const type = data.type; const order = data.order; const container = $(".networks"); const network = container.find(`.network[data-uuid="${data.target}"]`); if (type === "networks") { $.each(order, function(index, value) { const position = $(container.children(".network")[index]); if (position.data("id") === value) { // Network in correct place return true; // No point in continuing } network.insertBefore(position); }); } else if (type === "channels") { $.each(order, function(index, value) { if (index === 0) { // Shouldn't attempt to move lobby return true; // same as `continue` -> skip to next item } const position = $(network.children(".chan")[index]); // Target channel at position if (position.data("id") === value) { // Channel in correct place return true; // No point in continuing } const channel = network.find(".chan[data-id=" + value + "]"); // Channel at position channel.insertBefore(position); }); } });
"use strict"; const $ = require("jquery"); const socket = require("../socket"); const options = require("../options"); socket.on("sync_sort", function(data) { // Syncs the order of channels or networks when they are reordered if (options.ignoreSortSync) { options.ignoreSortSync = false; return; // Ignore syncing because we 'caused' it } const type = data.type; const order = data.order; const container = $(".networks"); const network = container.find(`.network[data-uuid="${data.target}"]`); if (type === "networks") { $.each(order, function(index, value) { const position = $(container.children()[index]); if (position.data("id") === value) { // Network in correct place return true; // No point in continuing } network.insertBefore(position); }); } else if (type === "channels") { $.each(order, function(index, value) { if (index === 0) { // Shouldn't attempt to move lobby return true; // same as `continue` -> skip to next item } const position = $(network.children()[index]); // Target channel at position if (position.data("id") === value) { // Channel in correct place return true; // No point in continuing } const channel = network.find(".chan[data-id=" + value + "]"); // Channel at position channel.insertBefore(position); }); } });
Make a BCEDate for the dates before CE day 1.
from datetime import date as vanilla_date, timedelta from .base import Calendar from ..dates.bce import BCEDate class JulianDayNumber(Calendar): first_ce_day = vanilla_date(1, 1, 1) first_ce_day_number = 1721423 display_name = "Julian Day Number" @staticmethod def date_display_string(d): n = JulianDayNumber._day_number(d) return "Day %d" % n @staticmethod def representation(d): return {'day_number': JulianDayNumber._day_number(d)} @staticmethod def _day_number(d): return (d - JulianDayNumber.first_ce_day).days + JulianDayNumber.first_ce_day_number def date(self, n): offset = n - self.first_ce_day_number if offset >= 0: vd = self.first_ce_day + timedelta(days=offset) return JulianDayNumber().from_date(vd) else: d = BCEDate(1, 1, 1) self.bless(d) return d
from datetime import date as vanilla_date, timedelta from .base import Calendar class JulianDayNumber(Calendar): first_ce_day = vanilla_date(1, 1, 1) first_ce_day_number = 1721423 display_name = "Julian Day Number" @staticmethod def date_display_string(d): n = JulianDayNumber._day_number(d) return "Day %d" % n @staticmethod def representation(d): return {'day_number': JulianDayNumber._day_number(d)} @staticmethod def _day_number(d): return (d - JulianDayNumber.first_ce_day).days + JulianDayNumber.first_ce_day_number def date(self, n): vd = self.first_ce_day + timedelta(days=n - self.first_ce_day_number) return self.bless(vd)
Replace default with filter on default_option. This is necessary for backwards compatibility with the current tests.
<?php /** * Class Google\Site_Kit\Modules\Search_Console\Settings * * @package Google\Site_Kit\Modules\Search_Console * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Modules\Search_Console; use Google\Site_Kit\Core\Modules\Module_Settings; /** * Class for Search Console settings. * * @since n.e.x.t * @access private * @ignore */ class Settings extends Module_Settings { const OPTION = 'googlesitekit_search-console_settings'; /** * Registers the setting in WordPress. * * @since n.e.x.t */ public function register() { parent::register(); // Backwards compatibility with previous dedicated option. add_filter( 'default_option_' . self::OPTION, function ( $default ) { $default['propertyID'] = $this->options->get( 'googlesitekit_search_console_property' ) ?: ''; return $default; } ); } /** * Gets the default value. * * @since n.e.x.t * * @return array */ protected function get_default() { return array( 'propertyID' => '', ); } }
<?php /** * Class Google\Site_Kit\Modules\Search_Console\Settings * * @package Google\Site_Kit\Modules\Search_Console * @copyright 2020 Google LLC * @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link https://sitekit.withgoogle.com */ namespace Google\Site_Kit\Modules\Search_Console; use Google\Site_Kit\Core\Modules\Module_Settings; /** * Class for Search Console settings. * * @since n.e.x.t * @access private * @ignore */ class Settings extends Module_Settings { const OPTION = 'googlesitekit_search-console_settings'; /** * Gets the default value. * * @since n.e.x.t * * @return array */ protected function get_default() { return array( // Backwards compatibility with previous dedicated option. 'propertyID' => $this->options->get( 'googlesitekit_search_console_property' ) ?: '', ); } }
Use Django's memoize over a custom one. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
from django.utils.functional import memoize from . import app_settings def get_render_method(): return from_dotted_path(app_settings.EMAIL_RENDER_METHOD) get_render_method = memoize(get_render_method, {}, 0) def get_context_processors(): return [from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESSORS] get_context_processors = memoize(get_context_processors, {}, 0) def from_dotted_path(fullpath): """ Returns the specified attribute of a module, specified by a string. ``from_dotted_path('a.b.c.d')`` is roughly equivalent to:: from a.b.c import d except that ``d`` is returned and not entered into the current namespace. """ module, attr = fullpath.rsplit('.', 1) return getattr(__import__(module, {}, {}, (attr,)), attr)
from . import app_settings _render_method = None def get_render_method(): global _render_method if _render_method is None: _render_method = from_dotted_path(app_settings.EMAIL_RENDER_METHOD) return _render_method _context_processors = None def get_context_processors(): global _context_processors if _context_processors is None: _context_processors = [ from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESSORS ] return _context_processors def from_dotted_path(fullpath): """ Returns the specified attribute of a module, specified by a string. ``from_dotted_path('a.b.c.d')`` is roughly equivalent to:: from a.b.c import d except that ``d`` is returned and not entered into the current namespace. """ module, attr = fullpath.rsplit('.', 1) return getattr(__import__(module, {}, {}, (attr,)), attr)
Make sure jQuery is always included
<?php class FrontEndGridField extends GridField { /** * Returns the whole gridfield rendered with all the attached components * @return string */ public function FieldHolder($properties=array()) { Requirements::block(FRAMEWORK_DIR.'/css/GridField.css'); Requirements::css(FRONTEND_GRIDFIELD_BASE.'/css/FrontEndGridField.css'); Requirements::add_i18n_javascript(FRAMEWORK_DIR.'/javascript/lang'); Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-ui/jquery-ui.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/ssui.core.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(FRONTEND_GRIDFIELD_BASE.'/javascript/FrontEndGridField.js'); return parent::FieldHolder(); } } ?>
<?php class FrontEndGridField extends GridField { /** * Returns the whole gridfield rendered with all the attached components * @return string */ public function FieldHolder($properties=array()) { Requirements::block(FRAMEWORK_DIR.'/css/GridField.css'); Requirements::css(FRONTEND_GRIDFIELD_BASE.'/css/FrontEndGridField.css'); Requirements::add_i18n_javascript(FRAMEWORK_DIR.'/javascript/lang'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-ui/jquery-ui.js'); Requirements::javascript(FRAMEWORK_ADMIN_DIR.'/javascript/ssui.core.js'); Requirements::javascript(THIRDPARTY_DIR.'/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(FRONTEND_GRIDFIELD_BASE.'/javascript/FrontEndGridField.js'); return parent::FieldHolder(); } } ?>
Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots. BUG=424027 TBR=dtu@chromium.org Review URL: https://codereview.chromium.org/643763005 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833}
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import unittest from telemetry import decorators from telemetry.core.platform import win_platform_backend from telemetry.core.platform.power_monitor import ippet_power_monitor class IppetPowerMonitorTest(unittest.TestCase): @decorators.Disabled def testFindOrInstallIppet(self): self.assertTrue(ippet_power_monitor.IppetPath()) @decorators.Enabled('win') def testIppetRunsWithoutErrors(self): # Very basic test, doesn't validate any output data. platform_backend = win_platform_backend.WinPlatformBackend() power_monitor = ippet_power_monitor.IppetPowerMonitor(platform_backend) if not power_monitor.CanMonitorPower(): logging.warning('Test not supported on this platform.') return power_monitor.StartMonitoringPower(None) statistics = power_monitor.StopMonitoringPower() self.assertEqual(statistics['identifier'], 'ippet')
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import unittest from telemetry import decorators from telemetry.core.platform import win_platform_backend from telemetry.core.platform.power_monitor import ippet_power_monitor class IppetPowerMonitorTest(unittest.TestCase): @decorators.Enabled('win') def testFindOrInstallIppet(self): self.assertTrue(ippet_power_monitor.IppetPath()) @decorators.Enabled('win') def testIppetRunsWithoutErrors(self): # Very basic test, doesn't validate any output data. platform_backend = win_platform_backend.WinPlatformBackend() power_monitor = ippet_power_monitor.IppetPowerMonitor(platform_backend) if not power_monitor.CanMonitorPower(): logging.warning('Test not supported on this platform.') return power_monitor.StartMonitoringPower(None) statistics = power_monitor.StopMonitoringPower() self.assertEqual(statistics['identifier'], 'ippet')
Add route to a single post
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import 'current-input'; import App from './components/App'; import Home from './components/Home'; import PageNotFound from './components/PageNotFound'; import ExampleComponent from './components/ExampleComponent'; import ExampleTwoDeepComponent from './components/ExampleTwoDeepComponent'; import Post from './components/Post'; const routes = ( <Route path="/" mapMenuTitle="Home" component={App}> <IndexRoute component={Home} /> <Route path="example" mapMenuTitle="Example" component={ExampleComponent}> <Route path="two-deep" mapMenuTitle="Two Deep" component={ExampleTwoDeepComponent} /> </Route> <Route path="posts/:category/:slug" component={Post} /> <Route path="*" mapMenuTitle="Page Not Found" component={PageNotFound} /> </Route> ); render( <Router history={browserHistory} routes={routes} />, document.getElementById('root') );
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import 'current-input'; import App from './components/App'; import Home from './components/Home'; import PageNotFound from './components/PageNotFound'; import ExampleComponent from './components/ExampleComponent'; import ExampleTwoDeepComponent from './components/ExampleTwoDeepComponent'; import Post from './components/Post'; const routes = ( <Route path="/" mapMenuTitle="Home" component={App}> <IndexRoute component={Home} /> <Route path="example" mapMenuTitle="Example" component={ExampleComponent}> <Route path="two-deep" mapMenuTitle="Two Deep" component={ExampleTwoDeepComponent} /> </Route> <Route path="sample-post" mapMenuTitle="Sample post" component={Post} /> <Route path="post/:category/:" mapMenuTitle="Post" component={PageNotFound} /> <Route path="*" mapMenuTitle="Page Not Found" component={PageNotFound} /> </Route> ); render( <Router history={browserHistory} routes={routes} />, document.getElementById('root') );
Support ES module exported class names
var loaderUtils = require("loader-utils"); module.exports = function(source, map) { this.callback(null, source, map); }; module.exports.pitch = function(remainingRequest) { this.cacheable(); return ` // classnames-loader: automatically bind css-modules to classnames function interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var classNames = require(${loaderUtils.stringifyRequest(this, '!' + require.resolve('classnames/bind'))}); var locals = interopRequireDefault(require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)})).default; var css = classNames.bind(locals); for (var style in locals) { if (!locals.hasOwnProperty(style)) { continue; } if (typeof Object.defineProperty === 'function') { Object.defineProperty(css, style, {value: locals[style]}); } else { css[style] = locals[style]; } } module.exports = css; `; };
var loaderUtils = require("loader-utils"); module.exports = function(source, map) { this.callback(null, source, map); }; module.exports.pitch = function(remainingRequest) { this.cacheable(); return ` // classnames-loader: automatically bind css-modules to classnames var classNames = require(${loaderUtils.stringifyRequest(this, '!' + require.resolve('classnames/bind'))}); var locals = require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)}); var css = classNames.bind(locals); for (var style in locals) { if (!locals.hasOwnProperty(style)) { continue; } if (typeof Object.defineProperty === 'function') { Object.defineProperty(css, style, {value: locals[style]}); } else { css[style] = locals[style]; } } module.exports = css; `; }
Update order to include rule for "is" property.
module.exports.sortMemberRules = { "sort-class-members/sort-class-members": [2, { "order": [ "[static-property-is]", "[static-property-properties]", "[static-property-styles]", "[static-properties]", "[static-methods]", "[properties]", "constructor", "[accessor-pairs]", "[methods]", "[conventional-private-properties]", "[conventional-private-methods]", ], "groups": { "accessor-pairs": [{ "accessorPair": true, "sort": "alphabetical" }], "methods": [{ "type": "method", "sort": "alphabetical"}], "conventional-private-methods": [{ "type": "method", "sort": "alphabetical"}], "conventional-private-properties": [{ "type": "property", "sort": "alphabetical"}], "properties": [{ "type": "property", "sort": "alphabetical"}], "static-methods": [{ "type": "method", "sort": "alphabetical", "static": true }], "static-properties": [{ "type": "property", "sort": "alphabetical", "static": true }], "static-property-is": [{ "name": "is", "static": true }], "static-property-properties": [{ "name": "properties", "static": true }], "static-property-styles": [{ "name": "styles", "static": true }] }, "accessorPairPositioning": "getThenSet", }] }
module.exports.sortMemberRules = { "sort-class-members/sort-class-members": [2, { "order": [ "[static-properties-getter]", "[static-styles-getter]", "[static-properties]", "[static-methods]", "[properties]", "constructor", "[accessor-pairs]", "[methods]", "[conventional-private-properties]", "[conventional-private-methods]", ], "groups": { "accessor-pairs": [{ "accessorPair": true, "sort": "alphabetical" }], "methods": [{ "type": "method", "sort": "alphabetical"}], "conventional-private-methods": [{ "type": "method", "sort": "alphabetical"}], "conventional-private-properties": [{ "type": "property", "sort": "alphabetical"}], "properties": [{ "type": "property", "sort": "alphabetical"}], "static-methods": [{ "type": "method", "sort": "alphabetical", "static": true }], "static-properties": [{ "type": "property", "sort": "alphabetical", "static": true }], "static-properties-getter": [{ "name": "properties", "static": true }], "static-styles-getter": [{ "name": "styles", "static": true }] }, "accessorPairPositioning": "getThenSet", }] }
Add clean command and remove download tarball
import os from setuptools import setup, find_packages, Command __version__ = None exec(open('tadtool/version.py').read()) class CleanCommand(Command): """ Custom clean command to tidy up the project root. """ user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): os.system('rm -vrf ./build ./dist ./*.pyc ./*.tgz ./*.egg-info ./htmlcov') setup( name='tadtool', version=__version__, description='Assistant to find cutoffs in TAD calling algorithms.', packages=find_packages(exclude=["test"]), install_requires=[ 'numpy>=1.9.0', 'matplotlib>=3.6.0', 'progressbar2', 'future', ], author='Vaquerizas lab', author_email='kai.kruse@mpi-muenster.mpg.de', url='https://github.com/vaquerizaslab/tadtool', keywords=['bioinformatics', 'hi-c', 'genomics', 'tad'], classifiers=[], scripts=['bin/tadtool'], cmdclass={ 'clean': CleanCommand }, )
from setuptools import setup, find_packages __version__ = None exec(open('tadtool/version.py').read()) setup( name='tadtool', version=__version__, description='Assistant to find cutoffs in TAD calling algorithms.', packages=find_packages(exclude=["test"]), install_requires=[ 'numpy>=1.9.0', 'matplotlib>=3.6.0', 'progressbar2', 'future', ], author='Vaquerizas lab', author_email='kai.kruse@mpi-muenster.mpg.de', url='https://github.com/vaquerizaslab/tadtool', download_url='https://github.com/vaquerizaslab/tadtool/tarball/0.81', keywords=['bioinformatics', 'hi-c', 'genomics', 'tad'], classifiers=[], scripts=['bin/tadtool'] )
Fix namespace issue in search controller.
<?php /** * FluxBB - fast, light, user-friendly PHP forum software * Copyright (C) 2008-2012 FluxBB.org * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public license for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category FluxBB * @package Core * @copyright Copyright (c) 2008-2012 FluxBB (http://fluxbb.org) * @license http://www.gnu.org/licenses/gpl.html GNU General Public License */ namespace FluxBB\Controllers; use FluxBB\Models\Category; class Search extends Base { public function get_index() { $categories = Category::all(); return \View::make('fluxbb::search.index') ->with('categories', $categories); } }
<?php /** * FluxBB - fast, light, user-friendly PHP forum software * Copyright (C) 2008-2012 FluxBB.org * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public license for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category FluxBB * @package Core * @copyright Copyright (c) 2008-2012 FluxBB (http://fluxbb.org) * @license http://www.gnu.org/licenses/gpl.html GNU General Public License */ namespace FluxBB\Controllers; use FluxBB\Models\Category; class Search extends Base { public function get_index() { $categories = Category::all(); return View::make('fluxbb::search.index') ->with('categories', $categories); } }
Sort results so they group properly
(function() { 'use strict'; var app = angular.module('radar.patients.results'); app.factory('groupResults', ['_', function(_) { function getKey(result) { return result.sourceGroup.id + '.' + result.sourceType + '.' + result.date; } return function groupResults(results) { var groups = []; var currentKey = null; var currentGroup = null; // Sort the results so they group properly results = _.sortBy(results, getKey); _.forEach(results, function(result) { var observationId = result.observation.id; var key = getKey(result); if ( key !== currentKey || currentGroup === null || currentGroup.results[observationId] !== undefined ) { currentKey = key; currentGroup = { date: result.date, source: result.getSource(), results: {} }; groups.push(currentGroup); } currentGroup.results[observationId] = result; }); return groups; }; }]); })();
(function() { 'use strict'; var app = angular.module('radar.patients.results'); app.factory('groupResults', ['_', function(_) { return function groupResults(results) { var groups = []; var currentKey = null; var currentGroup = null; _.forEach(results, function(result) { var observationId = result.observation.id; var key = result.sourceGroup.id + '.' + result.sourceType + '.' + result.date; if ( key !== currentKey || currentGroup === null || currentGroup.results[observationId] !== undefined ) { currentKey = key; currentGroup = { date: result.date, source: result.getSource(), results: {} }; groups.push(currentGroup); } currentGroup.results[observationId] = result; }); return groups; }; }]); })();
Fix renaming of table columns for other database drivers
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AlterTableIncidentsRenameComponentColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('incidents', function (Blueprint $table) { $table->rename('component', 'component_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('incidents', function (Blueprint $table) { $table->rename('component_id', 'component'); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AlterTableIncidentsRenameComponentColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('incidents', function (Blueprint $table) { DB::statement("ALTER TABLE `incidents` CHANGE `component` `component_id` TINYINT(4) NOT NULL DEFAULT '1'"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('incidents', function (Blueprint $table) { DB::statement("ALTER TABLE `incidents` CHANGE `component_id` `component` TINYINT(4) NOT NULL DEFAULT '1'"); }); } }
Add /schema path that serves schema as plain text
import express from 'express'; import { apolloExpress, graphiqlExpress } from 'apollo-server'; import bodyParser from 'body-parser'; import cors from 'cors'; import { createServer } from 'http'; import { SubscriptionServer } from 'subscriptions-transport-ws'; import { printSchema } from 'graphql/utilities/schemaPrinter' import { subscriptionManager } from './data/subscriptions'; import schema from './data/schema'; const GRAPHQL_PORT = 8080; const WS_PORT = 8090; const graphQLServer = express().use('*', cors()); graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({ schema, context: {}, })); graphQLServer.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql', })); graphQLServer.use('/schema', function(req, res, _next) { res.set('Content-Type', 'text/plain'); res.send(printSchema(schema)); }); graphQLServer.listen(GRAPHQL_PORT, () => console.log( `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql` )); // WebSocket server for subscriptions const websocketServer = createServer((request, response) => { response.writeHead(404); response.end(); }); websocketServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console `Websocket Server is now running on http://localhost:${WS_PORT}` )); // eslint-disable-next-line new SubscriptionServer( { subscriptionManager }, websocketServer );
import express from 'express'; import { apolloExpress, graphiqlExpress } from 'apollo-server'; import bodyParser from 'body-parser'; import cors from 'cors'; import { createServer } from 'http'; import { SubscriptionServer } from 'subscriptions-transport-ws'; import { subscriptionManager } from './data/subscriptions'; import schema from './data/schema'; const GRAPHQL_PORT = 8080; const WS_PORT = 8090; const graphQLServer = express().use('*', cors()); graphQLServer.use('/graphql', bodyParser.json(), apolloExpress({ schema, context: {}, })); graphQLServer.use('/graphiql', graphiqlExpress({ endpointURL: '/graphql', })); graphQLServer.listen(GRAPHQL_PORT, () => console.log( `GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql` )); // WebSocket server for subscriptions const websocketServer = createServer((request, response) => { response.writeHead(404); response.end(); }); websocketServer.listen(WS_PORT, () => console.log( // eslint-disable-line no-console `Websocket Server is now running on http://localhost:${WS_PORT}` )); // eslint-disable-next-line new SubscriptionServer( { subscriptionManager }, websocketServer );
Fix single user model and blog example.
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Core\Units; use Jivoo\Core\UnitBase; use Jivoo\Core\App; use Jivoo\Core\Store\Document; use Jivoo\Core\Cache\Cache; use Jivoo\Models\Enum; use Jivoo\Core\ModuleLoader; use Jivoo\Core\LoadableModule; use Jivoo\Helpers\Helpers; use Jivoo\Models\Models; /** * Initializes old modules. */ class LegacyModulesUnit extends UnitBase { /** * {@inheritdoc} */ protected $requires = array('Routing', 'AppLogic'); /** * {@inheritdoc} */ public function run(App $app, Document $config) { $modules = $this->app->manifest['modules']; $modules = array_intersect(array( 'Extensions', 'AccessControl', 'Console', 'Content', 'Jtk', 'Themes' ), $modules); foreach ($modules as $module) { $class = 'Jivoo\\' . $module . '\\' . $module; $this->m->$module = new $class($app); $this->m->$module->runInit(); } } }
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Core\Units; use Jivoo\Core\UnitBase; use Jivoo\Core\App; use Jivoo\Core\Store\Document; use Jivoo\Core\Cache\Cache; use Jivoo\Models\Enum; use Jivoo\Core\ModuleLoader; use Jivoo\Core\LoadableModule; use Jivoo\Helpers\Helpers; use Jivoo\Models\Models; /** * Initializes old modules. */ class LegacyModulesUnit extends UnitBase { /** * {@inheritdoc} */ protected $requires = array('Request', 'AppLogic'); /** * {@inheritdoc} */ public function run(App $app, Document $config) { $modules = $this->app->manifest['modules']; $modules = array_intersect($modules, array( 'AccessControl', 'Console', 'Content', 'Extensions', 'Jtk', 'Themes' )); foreach ($modules as $module) { $class = 'Jivoo\\' . $module . '\\' . $module; $this->m->$module = new $class($app); $this->m->$module->runInit(); } } }
Set post state to published upon save
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend(AuthenticatedRouteMixin, { session: Ember.inject.service(), model() { let userId = this.get('session.session.authenticated.user_id'); return Ember.RSVP.hash({ user: Ember.isPresent('userId') ? this.store.findRecord('user', userId) : null, project: this.modelFor('project') }); }, setupController(controller, models) { let newPost = this.store.createRecord('post', { project: models.project, user: models.user }); controller.set('post', newPost); }, actions: { savePost(post) { post.set('state', 'published'); post.save().then((post) => { this.transitionTo('project.posts.post', post.get('number')); }).catch((error) => { if (error.errors.length === 1) { this.controllerFor('project.posts.new').set('error', error); } }); } } });
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend(AuthenticatedRouteMixin, { session: Ember.inject.service(), model() { let userId = this.get('session.session.authenticated.user_id'); return Ember.RSVP.hash({ user: Ember.isPresent('userId') ? this.store.findRecord('user', userId) : null, project: this.modelFor('project') }); }, setupController(controller, models) { let newPost = this.store.createRecord('post', { project: models.project, user: models.user }); controller.set('post', newPost); }, actions: { savePost(post) { post.save().then((post) => { this.transitionTo('project.posts.post', post.get('number')); }).catch((error) => { if (error.errors.length === 1) { this.controllerFor('project.posts.new').set('error', error); } }); } } });
Add test for shortened clear command
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ClearCommandTest extends EzDoGuiTest { @Test public void clear() { //verify a non-empty list can be cleared assertTrue(taskListPanel.isListMatching(td.getTypicalTasks())); assertClearCommandSuccess(false); //verify a non-empty list can be cleared using the short clear command commandBox.runCommand(td.jack.getAddCommand(true)); assertListSize(1); assertClearCommandSuccess(true); //verify other commands can work after a clear command commandBox.runCommand(td.hoon.getAddCommand(false)); assertTrue(taskListPanel.isListMatching(td.hoon)); commandBox.runCommand("kill 1"); assertListSize(0); //verify clear command works when the list is empty assertClearCommandSuccess(false); } private void assertClearCommandSuccess(boolean usesShortCommand) { if (usesShortCommand) { commandBox.runCommand("c"); } else { commandBox.runCommand("clear"); } assertListSize(0); assertResultMessage("EzDo has been cleared!"); } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ClearCommandTest extends EzDoGuiTest { @Test public void clear() { //verify a non-empty list can be cleared assertTrue(taskListPanel.isListMatching(td.getTypicalTasks())); assertClearCommandSuccess(); //verify other commands can work after a clear command commandBox.runCommand(td.hoon.getAddCommand(false)); assertTrue(taskListPanel.isListMatching(td.hoon)); commandBox.runCommand("kill 1"); assertListSize(0); //verify clear command works when the list is empty assertClearCommandSuccess(); } private void assertClearCommandSuccess() { commandBox.runCommand("clear"); assertListSize(0); assertResultMessage("EzDo has been cleared!"); } }
Support event timezone aware datetime
import dayjsCommon from 'dayjs'; dayjsCommon.extend(require('dayjs/plugin/advancedFormat')) dayjsCommon.extend(require('dayjs/plugin/calendar')) dayjsCommon.extend(require('dayjs/plugin/relativeTime')) dayjsCommon.extend(require('dayjs/plugin/timezone')) dayjsCommon.extend(require('dayjs/plugin/utc')) dayjsCommon.extend(require('dayjs/plugin/customParseFormat')) export const dayjs = dayjsCommon; export const getNow = (rootState = null) => { if (rootState && rootState.cardDisplayDates && rootState.cardDisplayDates.comparison_date) { return dayjs(rootState.cardDisplayDates.comparison_date); } // dayjs.tz.setDefault("America/Los_Angeles"); // default value using client device local timezone return dayjs(); }; export const strToDate = (dateStr) => { if (dateStr.includes("T")) { // timezone aware UTC format return dayjs.utc(dateStr); } return dayjs.tz(dateStr, "America/Los_Angeles"); };
import dayjsCommon from 'dayjs'; dayjsCommon.extend(require('dayjs/plugin/advancedFormat')) dayjsCommon.extend(require('dayjs/plugin/calendar')) dayjsCommon.extend(require('dayjs/plugin/relativeTime')) dayjsCommon.extend(require('dayjs/plugin/timezone')) dayjsCommon.extend(require('dayjs/plugin/utc')) dayjsCommon.extend(require('dayjs/plugin/customParseFormat')) export const dayjs = dayjsCommon; export const getNow = (rootState = null) => { if (rootState && rootState.cardDisplayDates && rootState.cardDisplayDates.comparison_date) { return dayjs(rootState.cardDisplayDates.comparison_date); } // dayjs.tz.setDefault("America/Los_Angeles"); // default value using client device local timezone return dayjs(); }; export const strToDate = (dateStr) => { return dayjs.tz(dateStr, "America/Los_Angeles"); };
Set the ManagedObject to empty
package org.pentaho.ui.xul.swing.tags; import java.awt.GridBagLayout; import javax.swing.JPanel; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulTab; import org.pentaho.ui.xul.swing.SwingElement; import org.pentaho.ui.xul.util.Orient; public class SwingTab extends SwingElement implements XulTab{ private String label; private boolean disabled = false; private String onclick; public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) { super("tab"); managedObject = "empty"; } public boolean isDisabled() { return disabled; } public String getLabel() { return label; } public String getOnclick() { return onclick; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public void setLabel(String label) { this.label = label; } public void setOnclick(String onClick) { this.onclick = onClick; } @Override public void layout() { } }
package org.pentaho.ui.xul.swing.tags; import java.awt.GridBagLayout; import javax.swing.JPanel; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulTab; import org.pentaho.ui.xul.swing.SwingElement; import org.pentaho.ui.xul.util.Orient; public class SwingTab extends SwingElement implements XulTab{ private String label; private boolean disabled = false; private String onclick; public SwingTab(XulComponent parent, XulDomContainer domContainer, String tagName) { super("tab"); } public boolean isDisabled() { return disabled; } public String getLabel() { return label; } public String getOnclick() { return onclick; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public void setLabel(String label) { this.label = label; } public void setOnclick(String onClick) { this.onclick = onClick; } @Override public void layout() { } }
Use fragment JSX syntax instead
// @flow strict-local import React from 'react' import vt323 from './vt323/VT323-Regular.ttf' import { Global, css } from '@emotion/core' function GlobalStyles() { return ( <> <Global styles={css` @font-face { font-family: 'VT323-Webfont'; src: url('${vt323}'); } `} /> <Global styles={css` html, body { font-family: 'VT323', 'VT323-Webfont', monospace; font-size: 100%; margin: 0; padding: 0; } `} /> <Global styles={css` * { box-sizing: border-box; } `} /> </> ) } export default GlobalStyles
// @flow strict-local import React, { Fragment } from 'react' import vt323 from './vt323/VT323-Regular.ttf' import { Global, css } from '@emotion/core' function GlobalStyles() { return ( <Fragment> <Global styles={css` @font-face { font-family: 'VT323-Webfont'; src: url('${vt323}'); } `} /> <Global styles={css` html, body { font-family: 'VT323', 'VT323-Webfont', monospace; font-size: 100%; margin: 0; padding: 0; } `} /> <Global styles={css` * { box-sizing: border-box; } `} /> </Fragment> ) } export default GlobalStyles
Add filtering and ordering to PostListView
from django.core.urlresolvers import reverse from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView from board.forms import PostCreateForm from board.mixins import BoardMixin, UserLoggingMixin from board.models import Board, Post class PostCreateView(BoardMixin, UserLoggingMixin, CreateView): model = Post form_class = PostCreateForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['board'] = self.board return kwargs class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): kwargs['board'] = self.object.board return super().get_context_data(**kwargs) class PostListView(BoardMixin, ListView): pagenate_by = 20 def get_queryset(self): return Post.objects.filter(board=self.board).order_by('-created_time')
from django.core.urlresolvers import reverse from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView from board.forms import PostCreateForm from board.mixins import BoardMixin, UserLoggingMixin from board.models import Board, Post class PostCreateView(BoardMixin, UserLoggingMixin, CreateView): model = Post form_class = PostCreateForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['board'] = self.board return kwargs class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): kwargs['board'] = self.object.board return super().get_context_data(**kwargs) class PostListView(BoardMixin, ListView): model = Post pass
Add Config weather - (DARKSKY API KEY, HOME, WORK_PLACE
# -*- coding: utf-8 -*- from utils.data_handler import DataHandler class Config(object): class __Config: def __init__(self): self.data_handler = DataHandler() self.fname = "config.json" config = self.__read_config() self.kino = config["kino"] self.github = config["github"] self.weather = config["weather"] def __read_config(self): return self.data_handler.read_file(self.fname) instance = None def __init__(self): if not Config.instance: Config.instance = Config.__Config() def __getattr__(self, name): return getattr(self.instance, name)
from utils.data_handler import DataHandler class Config(object): class __Config: def __init__(self): self.data_handler = DataHandler() self.fname = "config.json" config = self.__read_config() self.kino = config["kino"] self.github = config["github"] def __read_config(self): return self.data_handler.read_file(self.fname) instance = None def __init__(self): if not Config.instance: Config.instance = Config.__Config() def __getattr__(self, name): return getattr(self.instance, name)
Adjust media rewrite so that it will work in all circumstances
<?php /* ------------------------------------------------------------------------ *\ * Functions: Rewrites \* ------------------------------------------------------------------------ */ /** * Add various rewrite rules * * @return void */ function __gulp_init_namespace___pwa_rewrite_rules(): void { /** * Point to manifest generator at /manifest.json */ add_rewrite_endpoint("manifest", EP_NONE); add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top"); /** * Load offline template at /offline/ */ add_rewrite_endpoint("offline", EP_NONE); add_rewrite_rule("offline/?$", "index.php?offline=true", "top"); /** * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/ * to ensure no 404s occur when critical CSS is included */ add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . "/assets/media/$1", "top"); } add_action("init", "__gulp_init_namespace___pwa_rewrite_rules");
<?php /* ------------------------------------------------------------------------ *\ * Functions: Rewrites \* ------------------------------------------------------------------------ */ /** * Add various rewrite rules * * @return void */ function __gulp_init_namespace___pwa_rewrite_rules(): void { /** * Point to manifest generator at /manifest.json */ add_rewrite_endpoint("manifest", EP_NONE); add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top"); /** * Load offline template at /offline/ */ add_rewrite_endpoint("offline", EP_NONE); add_rewrite_rule("offline/?$", "index.php?offline=true", "top"); /** * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/ * to ensure no 404s occur when critical CSS is included */ add_rewrite_rule("media/(.*)$", parse_url(get_stylesheet_directory_uri(), PHP_URL_PATH) . "/assets/media/$1", "top"); } add_action("init", "__gulp_init_namespace___pwa_rewrite_rules");
Add persistent fix test name
<?php /* * This file is part of the Itkg\Core package. * * (c) Interakting - Business & Decision * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * @author Pascal DENIS <pascal.denis@businessdecision.com> */ class PersistentTest extends \PHPUnit_Framework_TestCase { public function testGetSetRemoveAndRemoveAll() { $data = new \Itkg\Core\Cache\CacheableData('my_key', null, array('values')); $adapter = $this->getMock('Itkg\Core\Cache\Adapter\Memory', array(), array(array())); $adapter->expects($this->exactly(2))->method('get')->with($data)->will($this->returnValue(false)); $adapter->expects($this->once())->method('set')->with($data); $adapter->expects($this->once())->method('remove')->with($data); $adapter->expects($this->once())->method('removeAll'); $persistent = new \Itkg\Core\Cache\Adapter\Persistent($adapter); $persistent->get($data); $persistent->set($data); $persistent->get($data); $persistent->remove($data); $this->assertFalse($persistent->get($data)); $persistent->removeAll(); } }
<?php /* * This file is part of the Itkg\Core package. * * (c) Interakting - Business & Decision * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * @author Pascal DENIS <pascal.denis@businessdecision.com> */ class MemoryTest extends \PHPUnit_Framework_TestCase { public function testGetSetRemoveAndRemoveAll() { $data = new \Itkg\Core\Cache\CacheableData('my_key', null, array('values')); $adapter = $this->getMock('Itkg\Core\Cache\Adapter\Memory', array(), array(array())); $adapter->expects($this->exactly(2))->method('get')->with($data)->will($this->returnValue(false)); $adapter->expects($this->once())->method('set')->with($data); $adapter->expects($this->once())->method('remove')->with($data); $adapter->expects($this->once())->method('removeAll'); $persistent = new \Itkg\Core\Cache\Adapter\Persistent($adapter); $persistent->get($data); $persistent->set($data); $persistent->get($data); $persistent->remove($data); $this->assertFalse($persistent->get($data)); $persistent->removeAll(); } }
Docs: Update createInstance documentation to be more clear
<?php namespace Concrete\Core\Foundation\Service; use \Concrete\Core\Application\Application; class ProviderList { public function __construct(Application $app) { $this->app = $app; } /** * Loads and registers a class ServiceProvider class. * @param string $class * @return void */ public function registerProvider($class) { $this->createInstance($class)->register(); } /** * Creates an instance of the passed class string, override this to change how providers are instantiated * * @param string $class The class name * @return \Concrete\Core\Foundation\Service\Provider */ protected function createInstance($class) { return new $class($this->app); } /** * Registers an array of service group classes. * @param array $groups * @return void */ public function registerProviders($groups) { foreach($groups as $group) { $this->registerProvider($group); } } /** * We are not allowed to serialize $this->app */ public function __sleep() { unset($this->app); } }
<?php namespace Concrete\Core\Foundation\Service; use \Concrete\Core\Application\Application; class ProviderList { public function __construct(Application $app) { $this->app = $app; } /** * Loads and registers a class ServiceProvider class. * @param string $class * @return void */ public function registerProvider($class) { $this->createInstance($class)->register(); } /** * Class for creating an instance of a passed class string, override this to add extra functionality * * @param string $class The class name * @return \Concrete\Core\Foundation\Service\Provider */ protected function createInstance($class) { return new $class($this->app); } /** * Registers an array of service group classes. * @param array $groups * @return void */ public function registerProviders($groups) { foreach($groups as $group) { $this->registerProvider($group); } } /** * We are not allowed to serialize $this->app */ public function __sleep() { unset($this->app); } }
Remove gdata dependency from install reqs
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'lxml', 'cssselect', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.3.1', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: setup_params['install_requires'].append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'cssselect', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.3.1', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: setup_params['install_requires'].append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
Fix import resources command line wrapper
"""Import/create resources into the system. This is registered as console script 'import_resources' in setup.py. """ # pragma: no cover import argparse import inspect import logging import sys import transaction from pyramid.paster import bootstrap from . import import_resources as main_import_resources def import_resources(): """Import resources from a JSON file. usage:: bin/import_resources etc/development.ini <filename> """ epilog = """The input JSON file contains the interface name of the resource type to create and a serialization of the sheets data. Strings having the form 'user_by_login: <username>' are resolved to the user's path. """ docstring = inspect.getdoc(import_resources) parser = argparse.ArgumentParser(description=docstring, epilog=epilog) parser.add_argument('ini_file', help='path to the adhocracy backend ini file') parser.add_argument('filename', type=str, help='file containing the resources descriptions') args = parser.parse_args() env = bootstrap(args.ini_file) logging.basicConfig(stream=sys.stdout, level=logging.INFO) main_import_resources(env['root'], env['registry'], args.filename) transaction.commit() env['closer']()
"""Import/create resources into the system. This is registered as console script 'import_resources' in setup.py. """ # pragma: no cover import argparse import inspect import logging import sys import transaction from pyramid.paster import bootstrap from adhocracy_core import scripts def import_resources(): """Import resources from a JSON file. usage:: bin/import_resources etc/development.ini <filename> """ epilog = """The input JSON file contains the interface name of the resource type to create and a serialization of the sheets data. Strings having the form 'user_by_login: <username>' are resolved to the user's path. """ docstring = inspect.getdoc(import_resources) parser = argparse.ArgumentParser(description=docstring, epilog=epilog) parser.add_argument('ini_file', help='path to the adhocracy backend ini file') parser.add_argument('filename', type=str, help='file containing the resources descriptions') args = parser.parse_args() env = bootstrap(args.ini_file) logging.basicConfig(stream=sys.stdout, level=logging.INFO) scripts.import_resources(env['root'], env['registry'], args.filename) transaction.commit() env['closer']()
Update ASDF-related docs to reflect presence of schemas [docs only]
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ The **asdf** subpackage contains code that is used to serialize astropy types so that they can be represented and stored using the Advanced Scientific Data Format (ASDF). This subpackage defines classes, referred to as **tags**, that implement the logic for serialization and deserialization. ASDF makes use of abstract data type definitons called **schemas**. The tag classes provided here are specific implementations of particular schemas. Some of the tags in Astropy (e.g., those related to transforms) implement schemas that are defined by the ASDF Standard. In other cases, both the tags and schemas are defined within Astropy (e.g., those related to many of the coordinate frames). Astropy currently has no ability to read or write ASDF files itself. In order to process ASDF files it is necessary to make use of the standalone **asdf** package. Users should never need to refer to tag implementations directly. Their presence should be entirely transparent when processing ASDF files. If both **asdf** and **astropy** are installed, no futher configuration is required in order to process ASDF files. The **asdf** package has been designed to automatically detect the presence of the tags defined by **astropy**. Documentation on the ASDF Standard can be found `here <https://asdf-standard.readthedocs.io>`__. Documentation on the ASDF Python module can be found `here <https://asdf.readthedocs.io>`__. """
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ The **asdf** subpackage contains code that is used to serialize astropy types so that they can be represented and stored using the Advanced Scientific Data Format (ASDF). This subpackage defines classes, referred to as **tags**, that implement the logic for serialization and deserialization. ASDF makes use of abstract data type definitons called **schemas**. The tags provided here are simply specific implementations of particular schemas. Currently astropy only implements tags for a subset of schemas that are defined externally by the ASDF Standard. However, it is likely that astropy will eventually define schemas of its own. Astropy currently has no ability to read or write ASDF files itself. In order to process ASDF files it is necessary to make use of the standalone **asdf** package. Users should never need to refer to tag implementations directly. Their presence should be entirely transparent when processing ASDF files. If both **asdf** and **astropy** are installed, no futher configuration is required in order to process ASDF files. The **asdf** package has been designed to automatically detect the presence of the tags defined by **astropy**. Documentation on the ASDF Standard can be found `here <https://asdf-standard.readthedocs.io>`__. Documentation on the ASDF Python module can be found `here <https://asdf.readthedocs.io>`__. """