text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
feat: Update regex. Add file write-out. Regex is bugged, however. Need to fix regex pattern.
""" Copyright 2016 Dee Reddy """ import sys import re args = sys.argv[1:] def minify(input_path, output_path, comments=False): """ Minifies/uglifies file args: input_path: input file path output_path: write-out file path comments: Boolean. If False, deletes comments during output. returns: Minified string. example: `$ python minify.py ./src/styles.css ./src/output.css` """ pattern = re.compile(r""" \s | # matches all whitespace characters OR ( # /\* # /* AND [ # 0 or more of any character \w\s # (?=\*) # (positive lookahead: doesn't make * part of the match) :@!"'~,#%&-=;<>` # \.\^\$\+\{\[\]\\\| # ]* # \*/ # AND */ ) # | //.*\n # OR any character from // until end-line (inclusive) """, re.VERBOSE) # read file and apply regex: with open(input_path, "r") as file_in: temp = [] for line in file_in: temp.append(line) output = ''.join(temp) output = pattern.sub('', output) # write to file: # (`w+` mode: writing/reading; overwrites existing files; creates file if doesn't exit) with open(output_path, "w+") as file_out: file_out.write(output) ############################# # Main # ############################# if __name__ == "__main__": # specify input and output paths in args: minify(args[0], args[1])
""" Copyright 2016 Dee Reddy """ import sys import re args = sys.argv[1:] def minify(filepath, comments=False): """ Minifies/uglifies file :param file_: comments: Boolean. If False, deletes comments during output. :return: Minified string. """ pattern = re.compile(r""" \s | # matches all whitespace characters OR ( # /\* # /* [ \w\s (?=\*) :@!"'~\.\^\$\+\?\{\}\[\]\\\|\(\) ]* # AND \*/ # */ ) # | //.*\n # OR any character from // until end-line (inclusive) """, re.VERBOSE) with open(filepath, "r") as file_: temp = [] for line in file_: temp.append(line) output = ''.join(temp) return pattern.sub('', output) if __name__ == "__main__": print(minify('./test/stylesheet.css'))
Change debug flag to match module name
var Busboy = require('busboy'), bytes = require('bytes'), concat = require('concat-stream'), debug = require('debug')('busboy-body-parser'); module.exports = function (settings) { settings = settings || {}; settings.limit = settings.limit || Math.Infinity; if (typeof settings.limit === 'string') { settings.limit = bytes(settings.limit); } return function multipartBodyParser(req, res, next) { if (req.is('multipart/form-data')) { var busboy = new Busboy({ headers: req.headers, limits: { fileSize: settings.limit } }); busboy.on('field', function (key, value) { debug('Received field %s: %s', key, value); req.body[key] = value; }); busboy.on('file', function (key, file, name, enc, mimetype) { file.pipe(concat(function (d) { debug('Received file %s', file); req.files[key] = { data: file.truncated ? null : d, name: name, encoding: enc, mimetype: mimetype, truncated: file.truncated, size: Buffer.byteLength(d.toString('binary'), 'binary') }; })); }); busboy.on('finish', function () { debug('Finished form parsing'); debug(req.body); next(); }); req.files = req.files || {}; req.body = req.body || {}; req.pipe(busboy); } else { next(); } }; };
var Busboy = require('busboy'), bytes = require('bytes'), concat = require('concat-stream'), debug = require('debug')('busboy-bodyparser'); module.exports = function (settings) { settings = settings || {}; settings.limit = settings.limit || Math.Infinity; if (typeof settings.limit === 'string') { settings.limit = bytes(settings.limit); } return function multipartBodyParser(req, res, next) { if (req.is('multipart/form-data')) { var busboy = new Busboy({ headers: req.headers, limits: { fileSize: settings.limit } }); busboy.on('field', function (key, value) { debug('Received field %s: %s', key, value); req.body[key] = value; }); busboy.on('file', function (key, file, name, enc, mimetype) { file.pipe(concat(function (d) { debug('Received file %s', file); req.files[key] = { data: file.truncated ? null : d, name: name, encoding: enc, mimetype: mimetype, truncated: file.truncated, size: Buffer.byteLength(d.toString('binary'), 'binary') }; })); }); busboy.on('finish', function () { debug('Finished form parsing'); debug(req.body); next(); }); req.files = req.files || {}; req.body = req.body || {}; req.pipe(busboy); } else { next(); } }; };
Add the explanation for the autoloading of doctrine entities
<?php namespace Backend\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class BackendExtension extends Extension implements PrependExtensionInterface { /** * @inheritDoc */ public function load(array $configs, ContainerBuilder $container) { // Nothing needs to be loaded here } /** * @inheritDoc */ public function prepend(ContainerBuilder $container) { $filesystem = new Filesystem(); foreach ((array) $container->getParameter('installed_modules') as $module) { $dir = $container->getParameter('kernel.root_dir') . '/../src/Backend/Modules/' . $module . '/Entity'; if (!$filesystem->exists($dir)) { continue; } /* * Find and load entities in the backend folder. * We do this by looping all installed modules and looking for an Entity directory. * If the Entity map is found, a configuration will be prepended to the configuration. * So it's basically like if you would add every single module by hand, but automagically. * * @TODO Check for YAML/XML files and set the type accordingly */ $container->prependExtensionConfig( 'doctrine', array( 'orm' => array( 'mappings' => array( $module => array( 'type' => 'annotation', 'is_bundle' => false, 'dir' => $dir, 'prefix' => 'Backend\\Modules\\' . $module . '\\Entity', 'alias' => $module, ), ), ), ) ); } } }
<?php namespace Backend\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class BackendExtension extends Extension implements PrependExtensionInterface { /** * @inheritDoc */ public function load(array $configs, ContainerBuilder $container) { // Nothing needs to be loaded here } /** * @inheritDoc */ public function prepend(ContainerBuilder $container) { $filesystem = new Filesystem(); foreach ((array) $container->getParameter('installed_modules') as $module) { $dir = $container->getParameter('kernel.root_dir') . '/../src/Backend/Modules/' . $module . '/Entity'; if (!$filesystem->exists($dir)) { continue; } // @TODO Check for YAML/XML files and set the type accordingly $container->prependExtensionConfig( 'doctrine', array( 'orm' => array ( 'mappings' => array ( $module => array ( 'type' => 'annotation', 'is_bundle' => false, 'dir' => $dir, 'prefix' => 'Backend\\Modules\\' . $module . '\\Entity', 'alias' => $module, ), ), ), ) ); } } }
Work on fixing a regression
package io.disassemble.asm.visitor.flow; import org.objectweb.asm.tree.AbstractInsnNode; /** * @author Tyler Sedlar * @since 4/8/16 */ public class BasicInstruction { public final BasicBlock block; public final AbstractInsnNode insn; protected BasicInstruction previous; public BasicInstruction(BasicBlock block, AbstractInsnNode insn) { this.block = block; this.insn = insn; } /** * Gets the BasicInstruction prior to this instruction. * * @return The BasicInstruction prior to this instruction. */ public BasicInstruction previous() { return (block.size() > 1 ? block.get(block.indexOf(this) - 1) : null); } /** * Gets the BasicInstruction after this instruction. * * @return The BasicInstruction after this instruction. */ public BasicInstruction next() { int idx = block.indexOf(this); return ((idx + 1) < block.size() ? block.get(idx + 1) : null); } /** * Gets the predecessor block's ending instruction. * * @return The predecessor block's ending instruction. */ public BasicInstruction parent() { return (block.predecessor != null ? block.predecessor.exit() : null); } @Override public boolean equals(Object o) { return super.equals(o); //Broken return o instanceof BasicInstruction && insn.getOpcode() == ((BasicInstruction) o).insn.getOpcode() && block.equals(((BasicInstruction) o).block); } @Override public int hashCode() { return insn.hashCode(); } }
package io.disassemble.asm.visitor.flow; import org.objectweb.asm.tree.AbstractInsnNode; /** * @author Tyler Sedlar * @since 4/8/16 */ public class BasicInstruction { public final BasicBlock block; public final AbstractInsnNode insn; protected BasicInstruction previous; public BasicInstruction(BasicBlock block, AbstractInsnNode insn) { this.block = block; this.insn = insn; } /** * Gets the BasicInstruction prior to this instruction. * * @return The BasicInstruction prior to this instruction. */ public BasicInstruction previous() { return (block.size() > 1 ? block.get(block.indexOf(this) - 1) : null); } /** * Gets the BasicInstruction after this instruction. * * @return The BasicInstruction after this instruction. */ public BasicInstruction next() { int idx = block.indexOf(this); return ((idx + 1) < block.size() ? block.get(idx + 1) : null); } /** * Gets the predecessor block's ending instruction. * * @return The predecessor block's ending instruction. */ public BasicInstruction parent() { return (block.predecessor != null ? block.predecessor.exit() : null); } @Override public boolean equals(Object o) { return o instanceof BasicInstruction && insn.getOpcode() == ((BasicInstruction) o).insn.getOpcode() && block.equals(((BasicInstruction) o).block); } @Override public int hashCode() { return insn.hashCode(); } }
Add check to verify if model is in config callback state.
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): self.model = None config = self.store_model_config(config) if not config: return base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) self.model_class = getattr(module, model_type) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q def store_model_config(self, _config): try: config = self.vip.config.get("model") except KeyError: config = {} try: self.vip.config.set("model", _config, send_update=False) except RuntimeError: _log.debug("Cannot change config store on config callback!") _config.update(config) return _config
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): self.model = None config = self.store_model_config(config) if not config: return base_module = "volttron.pnnl.models." try: model_type = config["model_type"] except KeyError as e: _log.exception("Missing Model Type key: {}".format(e)) raise e _file, model_type = model_type.split(".") module = importlib.import_module(base_module + _file) self.model_class = getattr(module, model_type) def get_q(self, _set, sched_index, market_index, occupied): q = self.model.predict(_set, sched_index, market_index, occupied) return q def store_model_config(self, _config): try: config = self.vip.config.get("model") except KeyError: config = {} self.vip.config.set("model", _config, send_update=False) _config.update(config) return _config
Use cycle instead of counting an index ourselves
from itertools import cycle from psycopg2.extras import register_hstore, register_json import psycopg2 import threading import ujson class DBAffinityConnectionsNoLimit(object): # Similar to the db affinity pool, but without keeping track of # the connections. It's the caller's responsibility to call us # back with the connection objects so that we can close them. def __init__(self, dbnames, conn_info): self.dbnames = cycle(dbnames) self.conn_info = conn_info self.conn_mapping = {} self.lock = threading.Lock() def _make_conn(self, conn_info): conn = psycopg2.connect(**conn_info) conn.set_session(readonly=True, autocommit=True) register_hstore(conn) register_json(conn, loads=ujson.loads) return conn def get_conns(self, n_conn): with self.lock: dbname = self.dbnames.next() conn_info_with_db = dict(self.conn_info, dbname=dbname) conns = [self._make_conn(conn_info_with_db) for i in range(n_conn)] return conns def put_conns(self, conns): for conn in conns: try: conn.close() except: pass def closeall(self): raise Exception('DBAffinityConnectionsNoLimit pool does not track ' 'connections')
from itertools import cycle from psycopg2.extras import register_hstore, register_json import psycopg2 import threading import ujson class DBAffinityConnectionsNoLimit(object): # Similar to the db affinity pool, but without keeping track of # the connections. It's the caller's responsibility to call us # back with the connection objects so that we can close them. def __init__(self, dbnames, conn_info): self.dbnames = dbnames self.conn_info = conn_info self.conn_mapping = {} self.lock = threading.Lock() self.dbname_index = 0 def _make_conn(self, conn_info): conn = psycopg2.connect(**conn_info) conn.set_session(readonly=True, autocommit=True) register_hstore(conn) register_json(conn, loads=ujson.loads) return conn def get_conns(self, n_conn): with self.lock: dbname = self.dbnames[self.dbname_index] self.dbname_index += 1 if self.dbname_index >= len(self.dbnames): self.dbname_index = 0 conn_info_with_db = dict(self.conn_info, dbname=dbname) conns = [self._make_conn(conn_info_with_db) for i in range(n_conn)] return conns def put_conns(self, conns): for conn in conns: try: conn.close() except: pass def closeall(self): raise Exception('DBAffinityConnectionsNoLimit pool does not track ' 'connections')
Remove makeweatherfiles, add template for Windows version file
#!/usr/bin/python # source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4', 'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters', 'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax', 'makegrid', 'makeweatherfiles', 'newstation', 'plotweather', 'powerclasses', 'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun', 'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc', 'station', 'superpower', 'towns', 'turbine', 'updateswis', 'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan', 'getfiles.ini', 'about.html', 'credits.html', 'help.html', 'SIREN_notes.html', 'siren_versions.csv', 'siren_files.py', 'compare_to_siren.git.py'] version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid', 'makeweatherfiles', 'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd', 'template', 'updateswis']
#!/usr/bin/python # source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4', 'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters', 'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax', 'makegrid', 'makeweatherfiles', 'newstation', 'plotweather', 'powerclasses', 'powermatch', 'powermodel', 'powerplot', 'sammodels', 'samrun', 'senutils', 'siren', 'sirenicons', 'sirenm', 'sirenupd', 'ssc', 'station', 'superpower', 'towns', 'turbine', 'updateswis', 'viewresource', 'visualise', 'wascene', 'worldwindow', 'zoompan', 'getfiles.ini', 'about.html', 'credits.html', 'help.html', 'makeweatherfiles.html', 'SIREN_notes.html', 'siren_versions.csv', 'siren_files.py', 'compare_to_siren.git.py'] version_files = ['flexiplot', 'getmap', 'getmerra2', 'indexweather', 'makegrid', 'makeweatherfiles', 'powermatch', 'powerplot', 'siren', 'sirenm', 'sirenupd', 'updateswis']
Put a bunch of stars together, and you can see that they twinkle at the same rate.
var TwinklingStar = new Class({ Extends: Star, initialize: function(options) { this.parent(options); if (this.brightness < 4) this.brightness = 4; this.color = "#eeeeee"; this.stepSeed = Math.random() * Math.PI; this.stepScale = Math.random() / 3; }, draw: function() { var x = cx(this.pos.x); var y = cy(this.pos.y); var brightness = this.brightness; brightness += Math.sin(FRAME * this.stepScale + this.stepSeed); context.save(); context.fillStyle = this.color; context.beginPath(); context.moveTo(x - brightness, y); context.quadraticCurveTo(x, y, x, y - brightness); context.quadraticCurveTo(x, y, x + brightness, y); context.quadraticCurveTo(x, y, x, y + brightness); context.quadraticCurveTo(x, y, x - brightness, y); context.fill(); context.closePath(); context.restore(); this.update(); }, }); function makeTwinkles(locations) { var stars = []; var i = 0; stars = locations.map(function (coords) { return new TwinklingStar({ x: coords[0], y: coords[1], brightness: Math.random() * 3 + 4, }); }); return { draw: function () { Array.each(stars, function(star) { star.draw(); }); }, locations: locations, }; }
var TwinklingStar = new Class({ Extends: Star, initialize: function(options) { this.parent(options); if (this.brightness < 4) this.brightness = 4; this.color = "#eeeeee"; this.stepSeed = Math.random() * Math.PI; }, draw: function() { var x = cx(this.pos.x); var y = cy(this.pos.y); var brightness = this.brightness; brightness += Math.sin(FRAME * 0.3 + this.stepSeed); context.save(); context.fillStyle = this.color; context.beginPath(); context.moveTo(x - brightness, y); context.quadraticCurveTo(x, y, x, y - brightness); context.quadraticCurveTo(x, y, x + brightness, y); context.quadraticCurveTo(x, y, x, y + brightness); context.quadraticCurveTo(x, y, x - brightness, y); context.fill(); context.closePath(); context.restore(); this.update(); }, }); function makeTwinkles(locations) { var stars = []; var i = 0; stars = locations.map(function (coords) { return new TwinklingStar({ x: coords[0], y: coords[1], brightness: Math.random() * 3 + 4, }); }); return { draw: function () { Array.each(stars, function(star) { star.draw(); }); }, locations: locations, }; }
Allow param exception to trickle up.
/* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */ package abra; import java.io.IOException; import joptsimple.OptionParser; import joptsimple.OptionSet; /** * Abstract base class for helping with options parsing. * * @author Lisle E. Mose (lmose at unc dot edu) */ public abstract class Options { protected static final String HELP = "help"; private OptionSet options; protected void printHelp() { try { getOptionParser().printHelpOn(System.err); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("IOException encountered when attempting to output help."); } } public void parseOptions(String[] args) { try { options = getOptionParser().parse(args); if (options.has(HELP)) { printHelp(); } else { init(); validate(); } } catch (joptsimple.OptionException e) { System.err.println(e.getMessage()); printHelp(); throw e; } } protected OptionSet getOptions() { return options; } abstract protected OptionParser getOptionParser(); abstract protected void validate(); protected void init() { } }
/* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */ package abra; import java.io.IOException; import joptsimple.OptionParser; import joptsimple.OptionSet; /** * Abstract base class for helping with options parsing. * * @author Lisle E. Mose (lmose at unc dot edu) */ public abstract class Options { protected static final String HELP = "help"; private OptionSet options; protected void printHelp() { try { getOptionParser().printHelpOn(System.err); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("IOException encountered when attempting to output help."); } } public void parseOptions(String[] args) { try { options = getOptionParser().parse(args); if (options.has(HELP)) { printHelp(); } else { init(); validate(); } } catch (joptsimple.OptionException e) { System.err.println(e.getMessage()); printHelp(); } } protected OptionSet getOptions() { return options; } abstract protected OptionParser getOptionParser(); abstract protected void validate(); protected void init() { } }
Add a timeout to the delta detector Make it so that the detector doesn't beep more than once per second. It would be even better if the beeping occurred in another thread...
import numpy as N import gobject import gtk.gdk class DeltaDetector(object): def __init__(self, active=False, threshold=20.0): self._previous_frame = None self._frame = None self.active = active self.threshold = threshold self._timed_out = False def send_frame(self, frame): self._previous_frame = self._frame self._frame = N.array(frame, dtype=float) if self._timed_out: return if not self.active: return if self._previous_frame is None: return if(self._previous_frame.shape != self._frame.shape): self._previous_frame = None return if N.max(N.abs(self._frame - self._previous_frame)) > self.threshold: gtk.gdk.beep() # Don't beep more than once per second self._timed_out = True gobject.timeout_add(1000, self._switch_on_timeout) def _switch_on_timeout(self): self._timed_out = False return False # Properties @property def active(self): return self._active @active.setter def active(self, value): self._active = bool(value) @property def threshold(self): return self._threshold @threshold.setter def threshold(self, value): self._threshold = float(value) @property def average(self): if self._frame is None or self._previous_frame is None: return 0.0 return N.mean(self._frame - self._previous_frame)
import numpy as N import gtk.gdk class DeltaDetector(object): def __init__(self, active=False, threshold=20.0): self._previous_frame = None self._frame = None self.active = active self.threshold = threshold def send_frame(self, frame): self._previous_frame = self._frame self._frame = N.array(frame, dtype=float) if not self.active: return if self._previous_frame is None: return if(self._previous_frame.shape != self._frame.shape): self._previous_frame = None return if N.max(N.abs(self._frame - self._previous_frame)) > self.threshold: gtk.gdk.beep() # Properties @property def active(self): return self._active @active.setter def active(self, value): self._active = bool(value) @property def threshold(self): return self._threshold @threshold.setter def threshold(self, value): self._threshold = float(value) @property def average(self): if self._frame is None or self._previous_frame is None: return 0.0 return N.mean(self._frame - self._previous_frame)
Make compatible with CentOS 8
#!/usr/bin/python3 import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{http://www.loc.gov/zing/srw/}recordData'): genre = recordData.find('.//{http://www.loc.gov/mods/v3}genre') name = recordData.find('.//{http://www.loc.gov/mods/v3}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
#!/usr/bin/python3 import re import sys import xml.etree.ElementTree as ET valid_gnd = re.compile('[0-9\-X]+') def Main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " kalliope_originator_record_file") exit(1) root = ET.parse(sys.argv[1]).getroot() gnds_and_type = {} for recordData in root.findall('.//{*}recordData'): genre = recordData.find('.//{*}genre') name = recordData.find('.//{*}name') if genre is not None and name is not None : gnd = name.get('valueURI').replace('https://d-nb.info/gnd/','') if name.get('valueURI') else None originator_type = genre.text if gnd and originator_type and valid_gnd.match(gnd): if gnd in gnds_and_type and not originator_type in gnds_and_type[gnd]: gnds_and_type[gnd].add(originator_type) else: gnds_and_type[gnd] = { originator_type } for gnd, originator_type in gnds_and_type.items(): print(gnd, ' - ', end='') print(*originator_type, sep=', ') try: Main() except Exception as e: print("ERROR: " + e)
Remove Shepway election id (waiting on feedback)
from data_collection.morph_importer import BaseMorphApiImporter class Command(BaseMorphApiImporter): srid = 4326 districts_srid = 4326 council_id = 'E07000112' #elections = ['parl.2017-06-08'] scraper_name = 'wdiv-scrapers/DC-PollingStations-Shepway' geom_type = 'geojson' def district_record_to_dict(self, record): poly = self.extract_geometry(record, self.geom_type, self.get_srid('districts')) code = record['dist_code'].strip() return { 'internal_council_id': code, 'name': record['district_n'].strip() + ' - ' + code, 'area': poly, 'polling_station_id': code, } def station_record_to_dict(self, record): location = self.extract_geometry(record, self.geom_type, self.get_srid('stations')) codes = record['polling_di'].split('\\') codes = [code.strip() for code in codes] stations = [] for code in codes: stations.append({ 'internal_council_id': code, 'postcode': '', 'address': record['address'].strip(), 'location': location, }) return stations
from data_collection.morph_importer import BaseMorphApiImporter class Command(BaseMorphApiImporter): srid = 4326 districts_srid = 4326 council_id = 'E07000112' elections = ['parl.2017-06-08'] scraper_name = 'wdiv-scrapers/DC-PollingStations-Shepway' geom_type = 'geojson' def district_record_to_dict(self, record): poly = self.extract_geometry(record, self.geom_type, self.get_srid('districts')) code = record['dist_code'].strip() return { 'internal_council_id': code, 'name': record['district_n'].strip() + ' - ' + code, 'area': poly, 'polling_station_id': code, } def station_record_to_dict(self, record): location = self.extract_geometry(record, self.geom_type, self.get_srid('stations')) codes = record['polling_di'].split('\\') codes = [code.strip() for code in codes] stations = [] for code in codes: stations.append({ 'internal_council_id': code, 'postcode': '', 'address': record['address'].strip(), 'location': location, }) return stations
Fix >> to create a new file
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.aesh.command.impl.operator; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.readline.AeshContext; /** * * @author [email protected] */ /** * * @author [email protected] */ public class AppendOutputRedirectionOperator implements ConfigurationOperator { private class OutputDelegateImpl extends FileOutputDelegate { private OutputDelegateImpl(String file) throws IOException { super(context, file); } @Override protected BufferedWriter buildWriter(File f) throws IOException { return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE); } } private CommandInvocationConfiguration config; private String argument; private final AeshContext context; public AppendOutputRedirectionOperator(AeshContext context) { this.context = context; } @Override public CommandInvocationConfiguration getConfiguration() throws IOException { if (config == null) { config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument)); } return config; } @Override public void setArgument(String argument) { this.argument = argument; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.aesh.command.impl.operator; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.aesh.command.invocation.CommandInvocationConfiguration; import org.aesh.readline.AeshContext; /** * * @author [email protected] */ /** * * @author [email protected] */ public class AppendOutputRedirectionOperator implements ConfigurationOperator { private class OutputDelegateImpl extends FileOutputDelegate { private OutputDelegateImpl(String file) throws IOException { super(context, file); } @Override protected BufferedWriter buildWriter(File f) throws IOException { return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8, StandardOpenOption.APPEND); } } private CommandInvocationConfiguration config; private String argument; private final AeshContext context; public AppendOutputRedirectionOperator(AeshContext context) { this.context = context; } @Override public CommandInvocationConfiguration getConfiguration() throws IOException { if (config == null) { config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument)); } return config; } @Override public void setArgument(String argument) { this.argument = argument; } }
Update convention and add variables to core-cron task. Signed-off-by: Karl Hepworth <[email protected]>
import React from 'react'; import { Mutation } from 'react-apollo'; import gql from 'graphql-tag'; import ReactSelect from 'react-select'; import Button from 'components/Button'; import { bp, color, fontSize } from 'lib/variables'; const taskDrushCron = gql` mutation taskDrushCron($environment: Int!) { taskDrushCron(environment: $environment) { id name status created started completed remoteId command service } } `; const DrushCron = ({ pageEnvironment, onCompleted, onError }) => ( <Mutation mutation={taskDrushCron} onCompleted={onCompleted} onError={onError} variables={{ environment: pageEnvironment.id }} > {(taskDrushCron, { loading, called, error, data }) => { return ( <React.Fragment> <div className="envSelect"> <label id="dest-env">Environment:</label> <ReactSelect aria-labelledby="dest-env" name="dest-environment" value={{ label: pageEnvironment.name, value: pageEnvironment.id }} options={[ { label: pageEnvironment.name, value: pageEnvironment.id } ]} isDisabled required /> </div> <Button action={taskDrushCron}>Add task</Button> <style jsx>{` .envSelect { margin: 10px 0; } `}</style> </React.Fragment> ); }} </Mutation> ); export default DrushCron;
import React from 'react'; import { Mutation } from 'react-apollo'; import gql from 'graphql-tag'; import ReactSelect from 'react-select'; import Button from 'components/Button'; import { bp, color, fontSize } from 'lib/variables'; const taskDrushCron = gql` mutation taskDrushCron( $environment: Int! ) { taskDrushCron( environment: $environment ) { id name status created started completed remoteId command service } } `; const DrushCron = ({ pageEnvironment, onCompleted, onError, }) => ( <Mutation mutation={taskDrushCron} onCompleted={onCompleted} onError={onError} > {(taskDrushCron, { loading, called, error, data }) => { return ( <React.Fragment> <div className="envSelect"> <label id="dest-env">Environment:</label> <ReactSelect aria-labelledby="dest-env" name="dest-environment" value={{ label: pageEnvironment.name, value: pageEnvironment.id }} options={[ { label: pageEnvironment.name, value: pageEnvironment.id } ]} isDisabled required /> </div> <Button action={taskDrushCron}>Add task</Button> <style jsx>{` .envSelect { margin: 10px 0; } `}</style> </React.Fragment> ); }} </Mutation> ); export default DrushCron;
Use the error string if we have one for malformed json
import queryString from "query-string"; class Api { static get(url, data = {}) { return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET"); } static post(url, data = {}) { return this.request(url, data, "POST"); } static delete(url, data = {}) { return this.request(url, data, "DELETE"); } static patch(url, data = {}) { return this.request(url, data, "PATCH"); } static request(url, data, method) { let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, { method: method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }); return new Promise((resolve, reject) => { req.then((response) => { response.json().then((data) => { if (response.ok && data.success) { resolve(data.data); } else { let e = new Error(data.message); e.response = response; reject(e); } }).catch(() => { if(response.ok) { let e = new Error('Malformed response'); e.response = response; reject(e); } else { let e = new Error(response.statusText); e.response = response; reject(e); } }) }).catch((e) => { reject(new Error(e)); }) }); } } export default Api;
import queryString from "query-string"; class Api { static get(url, data = {}) { return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET"); } static post(url, data = {}) { return this.request(url, data, "POST"); } static delete(url, data = {}) { return this.request(url, data, "DELETE"); } static patch(url, data = {}) { return this.request(url, data, "PATCH"); } static request(url, data, method) { let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, { method: method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(data) }); return new Promise((resolve, reject) => { req.then((response) => { response.json().then((data) => { if (response.ok && data.success) { resolve(data.data); } else { let e = new Error(data.message); e.response = response; reject(e); } }).catch(() => { let e = new Error('Malformed response'); e.response = response; reject(e); }) }).catch((e) => { reject(new Error(e)); }) }); } } export default Api;
Change a comment to mention the organism taxonomy ID from NCBI.
from django.db import models from django.utils import timezone class TimeTrackedModel(models.Model): created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField() def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() return super(TimeTrackedModel, self).save(*args, **kwargs) class Meta: abstract = True # This model still has a prototypical status, but I needed something to # test with and it's at least in the right ballpark class Batch(TimeTrackedModel): source_type = models.CharField(max_length=256) size_in_bytes = models.IntegerField() download_url = models.CharField(max_length=2048) raw_format = models.CharField(max_length=256) processed_format = models.CharField(max_length=256) processor_required = models.IntegerField() accession_code = models.CharField(max_length=256) # This field will denote where in our system the file can be found internal_location = models.CharField(max_length=256) # This will utilize the organism taxonomy ID from NCBI organism = models.IntegerField() STATUSES = ( ("NEW", "New"), ("DOWNLOADED", "Downloaded"), ("PROCESSED", "Proccessed"), ) status = models.CharField(max_length=10, choices=STATUSES)
from django.db import models from django.utils import timezone class TimeTrackedModel(models.Model): created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField() def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created_at = timezone.now() self.updated_at = timezone.now() return super(TimeTrackedModel, self).save(*args, **kwargs) class Meta: abstract = True # This model still has a prototypical status, but I needed something to # test with and it's at least in the right ballpark class Batch(TimeTrackedModel): source_type = models.CharField(max_length=256) size_in_bytes = models.IntegerField() download_url = models.CharField(max_length=2048) raw_format = models.CharField(max_length=256) processed_format = models.CharField(max_length=256) processor_required = models.IntegerField() accession_code = models.CharField(max_length=256) # This field will denote where in our system the file can be found internal_location = models.CharField(max_length=256) # This will at some be a meaningful integer->organism lookup thing organism = models.IntegerField() STATUSES = ( ("NEW", "New"), ("DOWNLOADED", "Downloaded"), ("PROCESSED", "Proccessed"), ) status = models.CharField(max_length=10, choices=STATUSES)
Reformat and normalize messages, include -h and --help parameters
<?php /** * Script to validate cfdi files and show all the errors found */ require_once __DIR__ . '/../vendor/autoload.php'; use CFDIReader\CFDIFactory; $script = array_shift($argv); if ($argc == 1 || in_array('-h', $argv) || in_array('--help', $argv)) { echo "Set the file of the file to validate\n"; echo "Usage: $script [file1.xml] [file2.xml]\n"; exit; } // create the factory $factory = new CFDIFactory(); while (count($argv)) { // process next argument $argument = array_shift($argv); $filename = realpath($argument); if ("" === $filename or !is_file($filename) or !is_readable($filename)) { echo "File $argument FATAL: not found or is not readable\n"; continue; } // do the object creation $errors = []; $warnings = []; try { $reader = $factory->newCFDIReader(file_get_contents($filename), $errors, $warnings); foreach ($errors as $message) { echo "File $argument ERROR: $message\n"; } foreach ($warnings as $message) { echo "File $argument WARNING: $message\n"; } echo "File $argument UUID: " . $reader->getUUID(), "\n"; } catch (Exception $ex) { echo "File $argument FATAL: ", $ex->getMessage(), "\n"; } }
<?php /** * Script to validate a cfdi and show all the errors found */ require_once __DIR__ . '/../vendor/autoload.php'; use CFDIReader\CFDIFactory; call_user_func(function() use($argv, $argc) { $script = array_shift($argv); if ($argc == 1) { echo "Set the file of the file to validate\n"; echo "Usage: $script [file1.xml] [file2.xml]\n"; exit; } // create objects $factory = new CFDIFactory(); while(count($argv)) { $argument = array_shift($argv); $filename = realpath($argument); if ("" === $filename or !is_readable($filename)) { echo "File $argument was not found or is not readable\n"; continue; } try { $errors = []; $warnings = []; $reader = $factory->newCFDIReader(file_get_contents($filename), $errors, $warnings); foreach($errors as $message) { echo "File $argument ERROR: $message\n"; } foreach($warnings as $message) { echo "File $argument ERROR: $message\n"; } echo "File $argument with UUID " . $reader->getUUID(), " OK\n"; } catch(Exception $ex) { echo "File $argument give exception: ", $ex->getMessage(), "\n"; echo $ex->getTraceAsString(), "\n"; } } });
fix: Use date_created for "My Builds" sort
from sqlalchemy.orm import contains_eager, joinedload, subqueryload_all from zeus import auth from zeus.config import db from zeus.models import Author, Build, Email, Source, User from .base import Resource from ..schemas import BuildSchema builds_schema = BuildSchema(many=True, strict=True) class UserBuildsResource(Resource): def get(self, user_id): """ Return a list of builds for the given user. """ if user_id == 'me': user = auth.get_current_user() if not user: return self.error('not authenticated', 401) else: user = User.query.get(user_id) query = Build.query.options( joinedload('repository'), contains_eager('source'), joinedload('source').joinedload('author'), joinedload('source').joinedload('revision'), joinedload('source').joinedload('patch'), subqueryload_all('stats'), ).join( Source, Build.source_id == Source.id, ).filter( Source.author_id.in_(db.session.query(Author.id).filter(Author.email.in_( db.session.query(Email.email).filter( Email.user_id == user.id ) ))) ).order_by(Build.number.date_created()) return self.paginate_with_schema(builds_schema, query)
from sqlalchemy.orm import contains_eager, joinedload, subqueryload_all from zeus import auth from zeus.config import db from zeus.models import Author, Build, Email, Source, User from .base import Resource from ..schemas import BuildSchema builds_schema = BuildSchema(many=True, strict=True) class UserBuildsResource(Resource): def get(self, user_id): """ Return a list of builds for the given user. """ if user_id == 'me': user = auth.get_current_user() if not user: return self.error('not authenticated', 401) else: user = User.query.get(user_id) query = Build.query.options( joinedload('repository'), contains_eager('source'), joinedload('source').joinedload('author'), joinedload('source').joinedload('revision'), joinedload('source').joinedload('patch'), subqueryload_all('stats'), ).join( Source, Build.source_id == Source.id, ).filter( Source.author_id.in_(db.session.query(Author.id).filter(Author.email.in_( db.session.query(Email.email).filter( Email.user_id == user.id ) ))) ).order_by(Build.number.desc()) return self.paginate_with_schema(builds_schema, query)
Add second set of pages to test
<?php use Codeception\Util\Fixtures; use Codeception\Util\Stub; use Grav\Common\Grav; use Grav\Common\Page\Pages; use Grav\Common\Page\Page; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; /** * Class PagesTest */ class PagesTest extends \Codeception\TestCase\Test { /** @var Grav $grav */ protected $grav; /** @var Pages $pages */ protected $pages; /** @var Page $root_page */ protected $root_page; protected function _before() { $this->grav = Fixtures::get('grav'); $this->pages = $this->grav['pages']; /** @var UniformResourceLocator $locator */ $locator = $this->grav['locator']; $locator->addPath('page', '', 'tests/fake/simple-site/user/pages', false); $this->pages->init(); } public function testAll() { $this->assertTrue(is_object($this->pages->all())); $this->assertTrue(is_array($this->pages->all()->toArray())); $this->assertInstanceOf('Grav\Common\Page\Page', $this->pages->all()->first()); } public function testGetList() { $list = $this->pages->getList(); $this->assertTrue(is_array($list)); $this->assertSame($list['/'], 'Home'); $this->assertSame($list['/blog'], 'Blog'); } }
<?php use Codeception\Util\Fixtures; use Codeception\Util\Stub; use Grav\Common\Grav; use Grav\Common\Page\Pages; use Grav\Common\Page\Page; use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator; /** * Class PagesTest */ class PagesTest extends \Codeception\TestCase\Test { /** @var Grav $grav */ protected $grav; /** @var Pages $pages */ protected $pages; /** @var Page $root_page */ protected $root_page; protected function _before() { $this->grav = Fixtures::get('grav'); $this->pages = $this->grav['pages']; /** @var UniformResourceLocator $locator */ // $locator = $this->grav['locator']; // $locator->addPath('page', '', 'tests/fake/simple-site/user/pages', false); // $this->pages->init(); } public function testAll() { $this->assertTrue(is_object($this->pages->all())); $this->assertTrue(is_array($this->pages->all()->toArray())); $this->assertInstanceOf('Grav\Common\Page\Page', $this->pages->all()->first()); } public function testGetList() { $list = $this->pages->getList(); $this->assertTrue(is_array($list)); // $this->assertSame($list['/home'], 'Home'); // $this->assertSame($list['/blog'], 'Blog'); } }
Add path to theme attributes
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { $attributes = Json::make($path = $file->getRealPath())->toArray(); $attributes['path'] = dirname($path); return $attributes; } }
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { return Json::make($file->getRealPath())->toArray(); } }
Change 1s to 2 ms
<?php namespace Tests\Unit; use Performance\Performance; use Performance\Config; class ConfigLtirmRtrimTest extends \PHPUnit_Framework_TestCase { protected function setUp() { Config::reset(); } public function testStaticFunctionPoint() { // You can specify the characters you want to strip Config::set(Config::POINT_LABEL_LTRIM, 'synchronize'); Config::set(Config::POINT_LABEL_RTRIM, 'Run'); $this->synchronizeTaskARun(); $this->synchronizeTaskBRun(); $this->synchronizeTaskCRun(); // Finish all tasks and show test results Performance::results(); } // Create task public function synchronizeTaskARun() { // Set point Task A Performance::point(__FUNCTION__); // // Run code // sleep(1); usleep(2000); // // Finish point Task C Performance::finish(); } public function synchronizeTaskBRun() { // Set point Task B Performance::point(__FUNCTION__); // // Run code usleep(2000); // // Finish point Task B Performance::finish(); } public function synchronizeTaskCRun() { // Set point Task C Performance::point(__FUNCTION__); // // Run code usleep(2000); // // Finish point Task C Performance::finish(); } }
<?php namespace Tests\Unit; use Performance\Performance; use Performance\Config; class ConfigLtirmRtrimTest extends \PHPUnit_Framework_TestCase { protected function setUp() { Config::reset(); } public function testStaticFunctionPoint() { // You can specify the characters you want to strip Config::set(Config::POINT_LABEL_LTRIM, 'synchronize'); Config::set(Config::POINT_LABEL_RTRIM, 'Run'); $this->synchronizeTaskARun(); $this->synchronizeTaskBRun(); $this->synchronizeTaskCRun(); // Finish all tasks and show test results Performance::results(); } // Create task public function synchronizeTaskARun() { // Set point Task A Performance::point(__FUNCTION__); // // Run code sleep(1); // // Finish point Task C Performance::finish(); } public function synchronizeTaskBRun() { // Set point Task B Performance::point(__FUNCTION__); // // Run code sleep(1); // // Finish point Task B Performance::finish(); } public function synchronizeTaskCRun() { // Set point Task C Performance::point(__FUNCTION__); // // Run code // // Finish point Task C Performance::finish(); } }
Remove test bundle from app kernel
<?php use Tomahawk\HttpKernel\Kernel; class AppKernel extends Kernel { /** * Register bundles * * @return array */ public function registerBundles() { $bundles = [ new \Tomahawk\Bundle\FrameworkBundle\FrameworkBundle(), new \Tomahawk\Bundle\MonologBundle\MonologBundle(), new \Tomahawk\Bundle\ErrorHandlerBundle\ErrorHandlerBundle(), new \Tomahawk\Bundle\GeneratorBundle\GeneratorBundle(), new \Tomahawk\Bundle\DoctrineBundle\DoctrineBundle(), new \Tomahawk\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new \Tomahawk\Bundle\CSRFBundle\CSRFBundle(), new \MyApplication\Bundle\MyBundle\MyBundle(), ]; if ('dev' === $this->getEnvironment()) { $bundles[] = new \Tomahawk\Bundle\WebProfilerBundle\WebProfilerBundle(); } return $bundles; } /** * Return root directory * * @return string */ public function getRootDir() { return __DIR__; } /** * Returns cache directory * * @return string */ public function getCacheDir() { return dirname(__DIR__).'/var/cache'; } /** * Return log directory * * @return string */ public function getLogDir() { return dirname(__DIR__).'/var/log'; } }
<?php use Tomahawk\HttpKernel\Kernel; class AppKernel extends Kernel { /** * Register bundles * * @return array */ public function registerBundles() { $bundles = [ new \Tomahawk\Bundle\FrameworkBundle\FrameworkBundle(), new \Tomahawk\Bundle\MonologBundle\MonologBundle(), new \Tomahawk\Bundle\ErrorHandlerBundle\ErrorHandlerBundle(), new \Tomahawk\Bundle\GeneratorBundle\GeneratorBundle(), new \Tomahawk\Bundle\DoctrineBundle\DoctrineBundle(), new \Tomahawk\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new \Tomahawk\Bundle\CSRFBundle\CSRFBundle(), new \MyApplication\Bundle\MyBundle\MyBundle(), new \TestApplication\Bundle\TestBundle\TestBundle(), ]; if ('dev' === $this->getEnvironment()) { $bundles[] = new \Tomahawk\Bundle\WebProfilerBundle\WebProfilerBundle(); } return $bundles; } /** * Return root directory * * @return string */ public function getRootDir() { return __DIR__; } /** * Returns cache directory * * @return string */ public function getCacheDir() { return dirname(__DIR__).'/var/cache'; } /** * Return log directory * * @return string */ public function getLogDir() { return dirname(__DIR__).'/var/log'; } }
Add path to theme attributes
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { $attributes = Json::make($path = $file->getRealPath())->toArray(); $attributes['path'] = dirname($path); return $attributes; } }
<?php namespace Pingpong\Themes; use Illuminate\Filesystem\Filesystem; use Pingpong\Modules\Json; use Symfony\Component\Finder\Finder as SymfonyFinder; class Finder { /** * The symfony finder instance. * * @var SymfonyFinder */ protected $finder; /** * The constructor. * * @param $finder SymfonyFinder */ public function __construct(SymfonyFinder $finder = null) { $this->finder = $finder ?: new SymfonyFinder; } /** * Find the specified theme by searching a 'theme.json' file as identifier. * * @param string $path * @param string $filename * @return array */ public function find($path, $filename = 'theme.json') { $themes = []; if(is_dir($path)) { $found = $this->finder->in($path)->files()->name($filename)->depth('<= 3')->followLinks(); foreach ($found as $file) $themes[] = new Theme($this->getInfo($file)); } return $themes; } /** * Get theme info from json file. * * @param SplFileInfo $file * @return array */ protected function getInfo($file) { return Json::make($file->getRealPath())->toArray(); } }
Modify the condition for selection of longest patterns
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0]), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
from marisa_trie import RecordTrie from .trie import TrieSearch class RecordTrieSearch(RecordTrie, TrieSearch): def __init__(self, record_format, records=None, filepath=None): super(RecordTrieSearch, self).__init__(record_format, records) if filepath: self.load(filepath) def search_all_patterns(self, text, splitter=u' ', min_weight=0.0): for pattern, start_idx in super( RecordTrie, self).search_all_patterns(text, splitter): weight = self[pattern][0][0] if weight < min_weight: continue yield pattern, start_idx, weight def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0): all_patterns = self.search_all_patterns(text, splitter, min_weight) check_field = [0] * len(text) for pattern, start_idx, weight in sorted( all_patterns, key=lambda x: len(x[0].split(splitter)), reverse=True): target_field = check_field[start_idx:start_idx + len(pattern)] check_sum = sum(target_field) if check_sum != len(target_field): for i in range(len(pattern)): check_field[start_idx + i] = 1 yield pattern, start_idx, weight
Set correct service-name in command
package com.opera.core.systems.scope; import com.opera.core.systems.model.ICommand; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * This enum maps the commands for the <a href= * "http://dragonfly.opera.com/app/scope-interface/services/DesktopWindowManager/DesktopWindowManager_2_0.html" * >Window Manager 2.0</a>. * */ public enum DesktopWindowManagerCommand implements ICommand { GET_ACTIVE_WINDOW(1), LIST_WINDOWS(2), LIST_QUICK_WIDGETS(3), WINDOW_UPDATED(4), // event WINDOW_CLOSED(5), // event WINDOW_ACTIVATED(6), // event WINDOW_LOADED(7), DEFAULT(-1); // event private int code; private static final Map<Integer, DesktopWindowManagerCommand> lookup = new HashMap<Integer, DesktopWindowManagerCommand>(); static { for (DesktopWindowManagerCommand command : EnumSet.allOf(DesktopWindowManagerCommand.class)) lookup.put(command.getCommandID(), command); } private DesktopWindowManagerCommand(int code) { this.code = code; } public int getCommandID() { return code; } public String getServiceName() { return "desktop-window-manager"; } public static DesktopWindowManagerCommand get(int code) { DesktopWindowManagerCommand command = lookup.get(code); return (command != null) ? command : DEFAULT; } }
package com.opera.core.systems.scope; import com.opera.core.systems.model.ICommand; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * This enum maps the commands for the <a href= * "http://dragonfly.opera.com/app/scope-interface/services/DesktopWindowManager/DesktopWindowManager_2_0.html" * >Window Manager 2.0</a>. * */ public enum DesktopWindowManagerCommand implements ICommand { GET_ACTIVE_WINDOW(1), LIST_WINDOWS(2), LIST_QUICK_WIDGETS(3), WINDOW_UPDATED(4), // event WINDOW_CLOSED(5), // event WINDOW_ACTIVATED(6), // event WINDOW_LOADED(7), DEFAULT(-1); // event private int code; private static final Map<Integer, DesktopWindowManagerCommand> lookup = new HashMap<Integer, DesktopWindowManagerCommand>(); static { for (DesktopWindowManagerCommand command : EnumSet.allOf(DesktopWindowManagerCommand.class)) lookup.put(command.getCommandID(), command); } private DesktopWindowManagerCommand(int code) { this.code = code; } public int getCommandID() { return code; } public String getServiceName() { return "window-manager"; } public static DesktopWindowManagerCommand get(int code) { DesktopWindowManagerCommand command = lookup.get(code); return (command != null) ? command : DEFAULT; } }
Check both key and value, throw error only if values differ
package io.quarkus.deployment.steps; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Properties; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.ArchiveRootBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateOutputBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateSystemPropertyBuildItem; public class SubstrateSystemPropertiesBuildStep { @BuildStep SubstrateOutputBuildItem writeNativeProps(ArchiveRootBuildItem root, List<SubstrateSystemPropertyBuildItem> props) throws Exception { final Properties properties = new Properties(); for (SubstrateSystemPropertyBuildItem i : props) { if (!properties.containsKey(i.getKey())) { properties.put(i.getKey(), i.getValue()); } else if (!properties.get(i.getKey()).equals(i.getValue())) { throw new RuntimeException("Duplicate native image system property under " + i.getKey() + " conflicting values of " + i.getValue() + " and " + properties.get(i.getKey())); } } try (FileOutputStream os = new FileOutputStream(new File(root.getArchiveRoot().toFile(), "native-image.properties"))) { try (OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8)) { properties.store(osw, "Generated properties (do not edit)"); } } return new SubstrateOutputBuildItem(); } }
package io.quarkus.deployment.steps; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Properties; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.ArchiveRootBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateOutputBuildItem; import io.quarkus.deployment.builditem.substrate.SubstrateSystemPropertyBuildItem; public class SubstrateSystemPropertiesBuildStep { @BuildStep SubstrateOutputBuildItem writeNativeProps(ArchiveRootBuildItem root, List<SubstrateSystemPropertyBuildItem> props) throws Exception { final Properties properties = new Properties(); for (SubstrateSystemPropertyBuildItem i : props) { if (properties.containsKey(i.getKey())) { throw new RuntimeException("Duplicate native image system property under " + i.getKey() + " conflicting values of " + i.getValue() + " and " + properties.get(i.getKey())); } properties.put(i.getKey(), i.getValue()); } try (FileOutputStream os = new FileOutputStream(new File(root.getArchiveRoot().toFile(), "native-image.properties"))) { try (OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8)) { properties.store(osw, "Generated properties (do not edit)"); } } return new SubstrateOutputBuildItem(); } }
Remove required fields from address state
<?php namespace PatternSeek\ECommerce\ViewState; use PatternSeek\ComponentView\ViewState\ViewState; use Symfony\Component\Validator\Constraints as Assert; /** * Class AddressState * @package PatternSeek\ECommerce */ class AddressState extends ViewState { /** * @var string * * @Assert\Type(type="string") */ public $addressLine1; /** * @var string * * @Assert\Type(type="string") */ public $addressLine2; /** * @var string * * @Assert\Type(type="string") */ public $townOrCity; /** * @var string * * @Assert\Type(type="string") */ public $stateOrRegion; /** * @var string * * @Assert\Type(type="string") */ public $postCode; /** * @var string * * @Assert\Type(type="string") */ public $countryString; /** * @var string * * @Assert\Type(type="string") * @Assert\Length(min="2", max="2") */ public $countryCode; /** * @var string * * @Assert\Type(type="string") * @Assert\Choice(choices = {"edit", "view"}) */ public $mode = 'view'; }
<?php namespace PatternSeek\ECommerce\ViewState; use PatternSeek\ComponentView\ViewState\ViewState; use Symfony\Component\Validator\Constraints as Assert; /** * Class AddressState * @package PatternSeek\ECommerce */ class AddressState extends ViewState { /** * @var string * * @Assert\Type(type="string") * @Assert\NotBlank() */ public $addressLine1; /** * @var string * * @Assert\Type(type="string") */ public $addressLine2; /** * @var string * * @Assert\Type(type="string") * @Assert\NotBlank() */ public $townOrCity; /** * @var string * * @Assert\Type(type="string") */ public $stateOrRegion; /** * @var string * * @Assert\Type(type="string") */ public $postCode; /** * @var string * * @Assert\Type(type="string") */ public $countryString; /** * @var string * * @Assert\Type(type="string") * @Assert\NotBlank() * @Assert\Length(min="2", max="2") */ public $countryCode; /** * @var string * * @Assert\Type(type="string") * @Assert\Choice(choices = {"edit", "view"}) */ public $mode = 'view'; }
Fix for bug introduced with r510. Only make the removeChild call if the parentNode is properly set. This way we can zap the grid div contents quickly with the div.innerHTML = "" but still have a valid good destroy() function. git-svn-id: 86a4f41f9d0383640198789122b520d4105b319a@511 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
// @require: OpenLayers/Tile.js /** * @class */ OpenLayers.Tile.Image = Class.create(); OpenLayers.Tile.Image.prototype = Object.extend( new OpenLayers.Tile(), { /** @type DOMElement img */ img:null, /** * @constructor * * @param {OpenLayers.Grid} layer * @param {OpenLayers.Pixel} position * @param {OpenLayers.Bounds} bounds * @param {String} url * @param {OpenLayers.Size} size */ initialize: function(layer, position, bounds, url, size) { OpenLayers.Tile.prototype.initialize.apply(this, arguments); }, destroy: function() { if (this.img.parentNode == this.layer.div) { this.layer.div.removeChild(this.img); } this.img = null; }, /** */ draw:function() { OpenLayers.Tile.prototype.draw.apply(this, arguments); this.img = OpenLayers.Util.createImage(null, this.position, this.size, this.url, "absolute"); this.layer.div.appendChild(this.img); }, /** @final @type String */ CLASS_NAME: "OpenLayers.Tile.Image" } );
// @require: OpenLayers/Tile.js /** * @class */ OpenLayers.Tile.Image = Class.create(); OpenLayers.Tile.Image.prototype = Object.extend( new OpenLayers.Tile(), { /** @type DOMElement img */ img:null, /** * @constructor * * @param {OpenLayers.Grid} layer * @param {OpenLayers.Pixel} position * @param {OpenLayers.Bounds} bounds * @param {String} url * @param {OpenLayers.Size} size */ initialize: function(layer, position, bounds, url, size) { OpenLayers.Tile.prototype.initialize.apply(this, arguments); }, destroy: function() { this.layer.div.removeChild(this.img); this.img = null; }, /** */ draw:function() { OpenLayers.Tile.prototype.draw.apply(this, arguments); this.img = OpenLayers.Util.createImage(null, this.position, this.size, this.url, "absolute"); this.layer.div.appendChild(this.img); }, /** @final @type String */ CLASS_NAME: "OpenLayers.Tile.Image" } );
Return the newly created control This enables code like: var button = L.easyButton(...); map.removeControl(button);
L.Control.EasyButtons = L.Control.extend({ options: { position: 'topleft', title: '', intentedIcon: 'fa-circle-o' }, onAdd: function () { var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control'); this.link = L.DomUtil.create('a', 'leaflet-bar-part', container); L.DomUtil.create('i', 'fa fa-lg ' + this.options.intentedIcon , this.link); this.link.href = '#'; L.DomEvent.on(this.link, 'click', this._click, this); this.link.title = this.options.title; return container; }, intendedFunction: function(){ alert('no function selected');}, _click: function (e) { L.DomEvent.stopPropagation(e); L.DomEvent.preventDefault(e); this.intendedFunction(); }, }); L.easyButton = function( btnIcon , btnFunction , btnTitle , btnMap ) { var newControl = new L.Control.EasyButtons; if (btnIcon) newControl.options.intentedIcon = btnIcon; if ( typeof btnFunction === 'function'){ newControl.intendedFunction = btnFunction; } if (btnTitle) newControl.options.title = btnTitle; if ( btnMap ){ newControl.addTo(btnMap); } else { newControl.addTo(map); } return newControl; };
L.Control.EasyButtons = L.Control.extend({ options: { position: 'topleft', title: '', intentedIcon: 'fa-circle-o' }, onAdd: function () { var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control'); this.link = L.DomUtil.create('a', 'leaflet-bar-part', container); L.DomUtil.create('i', 'fa fa-lg ' + this.options.intentedIcon , this.link); this.link.href = '#'; L.DomEvent.on(this.link, 'click', this._click, this); this.link.title = this.options.title; return container; }, intendedFunction: function(){ alert('no function selected');}, _click: function (e) { L.DomEvent.stopPropagation(e); L.DomEvent.preventDefault(e); this.intendedFunction(); }, }); L.easyButton = function( btnIcon , btnFunction , btnTitle , btnMap ) { var newControl = new L.Control.EasyButtons; if (btnIcon) newControl.options.intentedIcon = btnIcon; if ( typeof btnFunction === 'function'){ newControl.intendedFunction = btnFunction; } if (btnTitle) newControl.options.title = btnTitle; if ( btnMap ){ newControl.addTo(btnMap); } else { newControl.addTo(map); } };
Fix length calculation in the exception path
/* Copyright 2011 Frederic Langlet 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 kanzi.entropy; import kanzi.EntropyEncoder; import kanzi.BitStream; import kanzi.BitStreamException; public abstract class AbstractEncoder implements EntropyEncoder { @Override public abstract boolean encodeByte(byte val); @Override public abstract BitStream getBitStream(); // Default implementation: fallback to encodeByte // Some implementations should be able to use an optimized algorithm @Override public int encode(byte[] array, int blkptr, int len) { if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0)) return -1; int end = blkptr + len; int i = blkptr; try { while (i < end) { if (this.encodeByte(array[i]) == false) return i; i++; } } catch (BitStreamException e) { return i - blkptr; } return len; } @Override public void dispose() { } }
/* Copyright 2011 Frederic Langlet 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 kanzi.entropy; import kanzi.EntropyEncoder; import kanzi.BitStream; import kanzi.BitStreamException; public abstract class AbstractEncoder implements EntropyEncoder { @Override public abstract boolean encodeByte(byte val); @Override public abstract BitStream getBitStream(); // Default implementation: fallback to encodeByte // Some implementations should be able to use an optimized algorithm @Override public int encode(byte[] array, int blkptr, int len) { if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0)) return -1; int end = blkptr + len; int i = blkptr; try { while (i < end) { if (this.encodeByte(array[i]) == false) return i; i++; } } catch (BitStreamException e) { return i; } return len; } @Override public void dispose() { } }
FIX - No such file or directory: 'README.md'
# coding=utf-8 from setuptools import setup, find_packages VERSION = "0.1.11" setup( name="PyTrustNFe", version=VERSION, author="Danimar Ribeiro", author_email='[email protected]', keywords=['nfe', 'mdf-e'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v2 or \ later (LGPLv2+)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=find_packages(exclude=['*test*']), package_data={'pytrustnfe': ['nfe/templates/*xml', 'nfse/paulistana/templates/*xml']}, url='https://github.com/danimaribeiro/PyTrustNFe', license='LGPL-v2.1+', description='PyTrustNFe é uma biblioteca para envio de NF-e', long_description=open('README.md', 'r').read(), install_requires=[ 'Jinja2 >= 2.8', 'signxml >= 2.0.0', ], test_suite='nose.collector', tests_require=[ 'nose', 'mock', ], )
# coding=utf-8 from setuptools import setup, find_packages long_description = open('README.md').read() VERSION = "0.1.10" setup( name="PyTrustNFe", version=VERSION, author="Danimar Ribeiro", author_email='[email protected]', keywords=['nfe', 'mdf-e'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v2 or \ later (LGPLv2+)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], packages=find_packages(exclude=['*test*']), package_data={'pytrustnfe': ['nfe/templates/*xml', 'nfse/paulistana/templates/*xml']}, url='https://github.com/danimaribeiro/PyTrustNFe', license='LGPL-v2.1+', description='PyTrustNFe é uma biblioteca para envio de NF-e', long_description=long_description, install_requires=[ 'Jinja2 >= 2.8', 'signxml >= 2.0.0', ], test_suite='nose.collector', tests_require=[ 'nose', 'mock', ], )
Fix invalid statement for SubjectAlternativeName in self signed cert.
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([ DNSName(cn) ]), False ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName( DNSName(cn) ) ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
Fix wrong created_at field type
<?php use yii\db\Schema; use yii\db\Migration; class m140703_123104_page extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%page}}', [ 'id' => Schema::TYPE_PK, 'alias' => Schema::TYPE_STRING . '(1024) NOT NULL', 'title' => Schema::TYPE_STRING . '(512) NOT NULL', 'body' => Schema::TYPE_TEXT . ' NOT NULL', 'status' => Schema::TYPE_SMALLINT . ' NOT NULL', 'created_at' => Schema::TYPE_INTEGER, 'updated_at' => Schema::TYPE_INTEGER, ], $tableOptions); $this->insert('{{%page}}', [ 'alias'=>'about', 'title'=>'About', 'body'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'status'=>\common\models\Page::STATUS_PUBLISHED, 'created_at'=>time(), 'updated_at'=>time(), ]); } public function down() { $this->dropTable('{{%page}}'); } }
<?php use yii\db\Schema; use yii\db\Migration; class m140703_123104_page extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('{{%page}}', [ 'id' => Schema::TYPE_PK, 'alias' => Schema::TYPE_STRING . '(1024) NOT NULL', 'title' => Schema::TYPE_STRING . '(512) NOT NULL', 'body' => Schema::TYPE_TEXT . ' NOT NULL', 'status' => Schema::TYPE_SMALLINT . ' NOT NULL', 'created_at' => Schema::TYPE_INTEGER, 'updated_at' => Schema::TYPE_INTEGER, ], $tableOptions); $this->insert('{{%page}}', [ 'alias'=>'about', 'title'=>'About', 'body'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'status'=>\common\models\Page::STATUS_PUBLISHED, 'created_at'=>new \yii\db\Expression('NOW()'), 'updated_at'=>new \yii\db\Expression('NOW()'), ]); } public function down() { $this->dropTable('{{%page}}'); } }
Add a class for a known error that prevents implementation. Signed-off-by: mulhern <[email protected]>
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """ _FMT_STR = "value '%s' for parameter %s is unacceptable" def __init__(self, value, param, msg=None): """ Initializer. :param object value: the value :param str param: the parameter :param str msg: an explanatory message """ # pylint: disable=super-init-not-called self._value = value self._param = param self._msg = msg def __str__(self): # pragma: no cover if self._msg: fmt_str = self._FMT_STR + ": %s" return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param) class StratisCliValueUnimplementedError(StratisCliValueError): """ Raised if a parameter is not intrinsically bad but functionality is unimplemented for this value. """ pass class StratisCliUnimplementedError(StratisCliError): """ Raised if a method is temporarily unimplemented. """ pass class StratisCliKnownBugError(StratisCliError): """ Raised if a method is unimplemented due to a bug. """ pass
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """ _FMT_STR = "value '%s' for parameter %s is unacceptable" def __init__(self, value, param, msg=None): """ Initializer. :param object value: the value :param str param: the parameter :param str msg: an explanatory message """ # pylint: disable=super-init-not-called self._value = value self._param = param self._msg = msg def __str__(self): # pragma: no cover if self._msg: fmt_str = self._FMT_STR + ": %s" return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param) class StratisCliValueUnimplementedError(StratisCliValueError): """ Raised if a parameter is not intrinsically bad but functionality is unimplemented for this value. """ pass class StratisCliUnimplementedError(StratisCliError): """ Raised if a method is temporarily unimplemented. """ pass
:bug: Fix test completion, check for bash completion file before running
import os import subprocess import sys from pathlib import Path import typer from typer.testing import CliRunner from first_steps import tutorial001 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_show_completion(): result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --show-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout def test_install_completion(): bash_completion_path: Path = Path.home() / ".bash_completion" text = "" if bash_completion_path.is_file(): text = bash_completion_path.read_text() result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --install-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) new_text = bash_completion_path.read_text() assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text bash_completion_path.write_text(text)
import os import subprocess import sys from pathlib import Path import typer from typer.testing import CliRunner from first_steps import tutorial001 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_show_completion(): result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --show-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout def test_install_completion(): bash_completion_path: Path = Path.home() / ".bash_completion" text = bash_completion_path.read_text() result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --install-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) new_text = bash_completion_path.read_text() assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text bash_completion_path.write_text(text)
Use ternary operator in image loader method
'use strict'; import $ from 'jquery'; export default class ImageLoader { constructor(dataSrcAttr) { this.dataSrcAttr = dataSrcAttr || 'data-preload-src'; } isInlineImage($el) { return $el.is('img'); } getDataSrc($el) { return $el.attr(this.dataSrcAttr); } setInlineImageSrc($el, src) { $el.attr('src', src); } setBackgroundImageUrl($el, src) { var val = `url(${src})`; $el.css({'background-image': val}); } setSrc($el, src) { return this.isInlineImage($el) ? this.setInlineImageSrc($el, src) : this.setBackgroundImageUrl($el, src); } load($image) { return new Promise((resolve, reject) => { var img = new Image(), src = this.getDataSrc($image); img.src = src; img.addEventListener('load', () => { this.setSrc($image, src); resolve($image); }); img.addEventListener('error', () => { reject(`Error loading image src ${src}`); }); }); } loadAll($images) { var len = $images.length, promises = []; for (let i = 0; i < len; i++) { let $image = $($images[i]), promise = this.load($image); promises.push(promise); } return Promise.all(promises); } }
'use strict'; import $ from 'jquery'; export default class ImageLoader { constructor(dataSrcAttr) { this.dataSrcAttr = dataSrcAttr || 'data-preload-src'; } isInlineImage($el) { return $el.is('img'); } getDataSrc($el) { return $el.attr(this.dataSrcAttr); } setInlineImageSrc($el, src) { $el.attr('src', src); } setBackgroundImageUrl($el, src) { var val = `url(${src})`; $el.css({'background-image': val}); } setSrc($el, src) { if (this.isInlineImage($el)) { this.setInlineImageSrc($el, src); } else { this.setBackgroundImageUrl($el, src); } } load($image) { return new Promise((resolve, reject) => { var img = new Image(), src = this.getDataSrc($image); img.src = src; img.addEventListener('load', () => { this.setSrc($image, src); resolve($image); }); img.addEventListener('error', () => { reject(`Error loading image src ${src}`); }); }); } loadAll($images) { var len = $images.length, promises = []; for (let i = 0; i < len; i++) { let $image = $($images[i]), promise = this.load($image); promises.push(promise); } return Promise.all(promises); } }
Bump version number for next release
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="Pinax Team", author_email="[email protected]", description="a user to user join invitations app", name="pinax-invitations", long_description=read("README.rst"), version="2.2.0.dev1", url="http://github.com/pinax/pinax-invitations/", license="MIT", packages=find_packages(), package_data={ "invitations": [] }, test_suite="runtests.runtests", install_requires=[ "django-appconf>=1.0.1", "django-user-accounts>=1.2" ], tests_require=[ ], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() setup( author="Pinax Team", author_email="[email protected]", description="a user to user join invitations app", name="pinax-invitations", long_description=read("README.rst"), version="2.1.1", url="http://github.com/pinax/pinax-invitations/", license="MIT", packages=find_packages(), package_data={ "invitations": [] }, test_suite="runtests.runtests", install_requires=[ "django-appconf>=1.0.1", "django-user-accounts>=1.2" ], tests_require=[ ], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
Update admin area queries to use new `filter` parameter refs #6005 - updates use of the query params removed in #6005 to use new `filter` param
import Ember from 'ember'; export default Ember.Controller.extend({ notifications: Ember.inject.service(), userPostCount: Ember.computed('model.id', function () { var promise, query = { filter: `author:${this.get('model.slug')}`, status: 'all' }; promise = this.store.query('post', query).then(function (results) { return results.meta.pagination.total; }); return Ember.Object.extend(Ember.PromiseProxyMixin, { count: Ember.computed.alias('content'), inflection: Ember.computed('count', function () { return this.get('count') > 1 ? 'posts' : 'post'; }) }).create({promise: promise}); }), actions: { confirmAccept: function () { var self = this, user = this.get('model'); user.destroyRecord().then(function () { self.get('notifications').closeAlerts('user.delete'); self.store.unloadAll('post'); self.transitionToRoute('team'); }, function () { self.get('notifications').showAlert('The user could not be deleted. Please try again.', {type: 'error', key: 'user.delete.failed'}); }); }, confirmReject: function () { return false; } }, confirm: { accept: { text: 'Delete User', buttonClass: 'btn btn-red' }, reject: { text: 'Cancel', buttonClass: 'btn btn-default btn-minor' } } });
import Ember from 'ember'; export default Ember.Controller.extend({ notifications: Ember.inject.service(), userPostCount: Ember.computed('model.id', function () { var promise, query = { author: this.get('model.slug'), status: 'all' }; promise = this.store.query('post', query).then(function (results) { return results.meta.pagination.total; }); return Ember.Object.extend(Ember.PromiseProxyMixin, { count: Ember.computed.alias('content'), inflection: Ember.computed('count', function () { return this.get('count') > 1 ? 'posts' : 'post'; }) }).create({promise: promise}); }), actions: { confirmAccept: function () { var self = this, user = this.get('model'); user.destroyRecord().then(function () { self.get('notifications').closeAlerts('user.delete'); self.store.unloadAll('post'); self.transitionToRoute('team'); }, function () { self.get('notifications').showAlert('The user could not be deleted. Please try again.', {type: 'error', key: 'user.delete.failed'}); }); }, confirmReject: function () { return false; } }, confirm: { accept: { text: 'Delete User', buttonClass: 'btn btn-red' }, reject: { text: 'Cancel', buttonClass: 'btn btn-default btn-minor' } } });
Clone api options to avoid always injecting a `headers` key
// @ts-check import { assign, clone, get, defaults, compact } from "lodash" import request from "request" import config from "config" import HTTPError from "lib/http_error" export default (url, options = {}) => { return new Promise((resolve, reject) => { const opts = clone( defaults(options, { method: "GET", timeout: config.REQUEST_TIMEOUT_MS, }) ) // Wrap user agent const userAgent = opts.userAgent ? opts.userAgent + "; Metaphysics" : "Metaphysics" delete opts.userAgent opts.headers = assign({}, { "User-Agent": userAgent }, opts.headers) request(url, opts, (err, response) => { // If there is an error or non-200 status code, reject. if ( !!err || (response.statusCode && !response.statusCode.toString().match(/^2/)) ) { if (err) return reject(err) const message = compact([ get(response, "request.uri.href"), response.body, ]).join(" - ") return reject(new HTTPError(message, response.statusCode)) } try { const shouldParse = typeof response.body === "string" const parsed = shouldParse ? JSON.parse(response.body) : response.body resolve({ body: parsed, headers: response.headers, }) } catch (error) { reject(error) } }) }) }
// @ts-check import { assign, get, defaults, compact } from "lodash" import request from "request" import config from "config" import HTTPError from "lib/http_error" export default (url, options = {}) => { return new Promise((resolve, reject) => { const opts = defaults(options, { method: "GET", timeout: config.REQUEST_TIMEOUT_MS, }) // Wrap user agent const userAgent = opts.userAgent ? opts.userAgent + "; Metaphysics" : "Metaphysics" delete opts.userAgent opts.headers = assign({}, { "User-Agent": userAgent }, opts.headers) request(url, opts, (err, response) => { // If there is an error or non-200 status code, reject. if ( !!err || (response.statusCode && !response.statusCode.toString().match(/^2/)) ) { if (err) return reject(err) const message = compact([ get(response, "request.uri.href"), response.body, ]).join(" - ") return reject(new HTTPError(message, response.statusCode)) } try { const shouldParse = typeof response.body === "string" const parsed = shouldParse ? JSON.parse(response.body) : response.body resolve({ body: parsed, headers: response.headers, }) } catch (error) { reject(error) } }) }) }
Fix for wrong test: create_semester_accounts refs #448
# Copyright (c) 2013 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from tests import OldPythonTestCase __author__ = 'felix_kluge' from pycroft.lib.finance import create_semester, import_csv from pycroft.lib.config import get, config from pycroft.model.finance import FinanceAccount, Journal, JournalEntry from sqlalchemy.orm import backref from pycroft.model import session import time from datetime import date, datetime class Test_010_Semester(OldPythonTestCase): def test_0010_create_semester_accounts(self): """ This test should verify that all semester-related finance-accounts have been created. """ new_semester = create_semester("NewSemesterName", 2500, 1500, date(2013, 9, 1), date(2014, 2, 1)) config._configpath = "../tests/example/test_config.json" for account in config["finance"]["semester_accounts"]: new_created_account = FinanceAccount.q.filter( FinanceAccount.semester == new_semester, FinanceAccount.tag == account["tag"]).first() self.assertEqual(new_created_account.name, account["name"]) self.assertEqual(new_created_account.type, account["type"]) session.session.commit()
# Copyright (c) 2013 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from tests import OldPythonTestCase __author__ = 'felix_kluge' from pycroft.lib.finance import create_semester from pycroft.lib.config import get,config from pycroft.model.finance import FinanceAccount from sqlalchemy.orm import backref from pycroft.model import session import time from datetime import date class Test_010_Semester(OldPythonTestCase): def test_0010_create_semester_accounts(self): """ This test should verify that all semester-related finance-accounts have been created. """ new_semester = create_semester("NewSemesterName", 2500, 1500, date(2013, 9, 1), date(2014, 2, 1)) config._configpath = "../tests/example/test_config.json" for account in config["finance"]["semester_accounts"]: for new_account in new_semester.accounts: if(new_account.tag == account["tag"]): new_account_equivalent = new_account compare_account = FinanceAccount(type=account["type"],name=account["name"],semester=new_semester,tag=account["tag"]) self.assertEqual(new_account_equivalent.name, compare_account.name) self.assertEqual(new_account_equivalent.type, compare_account.type)
Use -platform:anycpu while compiling .NET assemblies
import os.path import SCons.Builder import SCons.Node.FS import SCons.Util csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES" csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES" McsBuilder = SCons.Builder.Builder(action = '$CSCCOM', source_factory = SCons.Node.FS.default_fs.Entry, suffix = '.exe') McsLibBuilder = SCons.Builder.Builder(action = '$CSCLIBCOM', source_factory = SCons.Node.FS.default_fs.Entry, suffix = '.dll') def generate(env): env['BUILDERS']['CLIProgram'] = McsBuilder env['BUILDERS']['CLILibrary'] = McsLibBuilder env['CSC'] = 'gmcs' env['_CSCLIBS'] = "${_stripixes('-r:', CILLIBS, '', '-r', '', __env__)}" env['_CSCLIBPATH'] = "${_stripixes('-lib:', CILLIBPATH, '', '-r', '', __env__)}" env['CSCFLAGS'] = SCons.Util.CLVar('-platform:anycpu') env['CSCLIBFLAGS'] = SCons.Util.CLVar('-platform:anycpu') env['CSCCOM'] = SCons.Action.Action(csccom) env['CSCLIBCOM'] = SCons.Action.Action(csclibcom) def exists(env): return internal_zip or env.Detect('gmcs')
import os.path import SCons.Builder import SCons.Node.FS import SCons.Util csccom = "$CSC $CSCFLAGS $_CSCLIBPATH -r:$_CSCLIBS -out:${TARGET.abspath} $SOURCES" csclibcom = "$CSC -t:library $CSCLIBFLAGS $_CSCLIBPATH $_CSCLIBS -out:${TARGET.abspath} $SOURCES" McsBuilder = SCons.Builder.Builder(action = '$CSCCOM', source_factory = SCons.Node.FS.default_fs.Entry, suffix = '.exe') McsLibBuilder = SCons.Builder.Builder(action = '$CSCLIBCOM', source_factory = SCons.Node.FS.default_fs.Entry, suffix = '.dll') def generate(env): env['BUILDERS']['CLIProgram'] = McsBuilder env['BUILDERS']['CLILibrary'] = McsLibBuilder env['CSC'] = 'gmcs' env['_CSCLIBS'] = "${_stripixes('-r:', CILLIBS, '', '-r', '', __env__)}" env['_CSCLIBPATH'] = "${_stripixes('-lib:', CILLIBPATH, '', '-r', '', __env__)}" env['CSCFLAGS'] = SCons.Util.CLVar('') env['CSCCOM'] = SCons.Action.Action(csccom) env['CSCLIBCOM'] = SCons.Action.Action(csclibcom) def exists(env): return internal_zip or env.Detect('gmcs')
Use built in functionality for calling Promise.all on an object of promises
(function(angular, window) { 'use strict'; angular .module('mwl.bluebird', []) .constant('Bluebird', window.P.noConflict()) .config(function($provide, Bluebird) { //Make bluebird API compatible with angular's subset of $q //Adapted from: https://gist.github.com/petkaantonov/8363789 Bluebird.defer = function() { var b = Bluebird.pending(); b.resolve = angular.bind(b, b.fulfill); b.reject = angular.bind(b, b.reject); b.notify = angular.bind(b, b.progress); return b; }; Bluebird.reject = Bluebird.rejected; Bluebird.when = Bluebird.cast; var originalAll = Bluebird.all; Bluebird.all = function(promises) { if (angular.isObject(promises) && !angular.isArray(promises)) { return Bluebird.props(promises); } else { return originalAll.call(Bluebird, promises); } }; Bluebird.onPossiblyUnhandledRejection(angular.noop); $provide.decorator('$q', function() { return Bluebird; }); }).run(function($rootScope, Bluebird) { Bluebird.setScheduler(function(cb) { $rootScope.$evalAsync(cb); }); }); }(angular, window));
(function(angular, window) { 'use strict'; angular .module('mwl.bluebird', []) .constant('Bluebird', window.P.noConflict()) .config(function($provide, Bluebird) { //Make bluebird API compatible with angular's subset of $q //Adapted from: https://gist.github.com/petkaantonov/8363789 Bluebird.defer = function() { var b = Bluebird.pending(); b.resolve = angular.bind(b, b.fulfill); b.reject = angular.bind(b, b.reject); b.notify = angular.bind(b, b.progress); return b; }; Bluebird.reject = Bluebird.rejected; Bluebird.when = Bluebird.cast; var originalAll = Bluebird.all; Bluebird.all = function(promises) { if (angular.isObject(promises) && !angular.isArray(promises)) { var promiseArray = [], promiseKeysArray = []; angular.forEach(promises, function(promise, key) { promiseKeysArray.push(key); promiseArray.push(promise); }); return originalAll(promiseArray).then(function(results) { var objectResult = {}; angular.forEach(results, function(result, index) { objectResult[promiseKeysArray[index]] = result; }); return objectResult; }); } else { return originalAll(promises); } }; Bluebird.onPossiblyUnhandledRejection(angular.noop); $provide.decorator('$q', function() { return Bluebird; }); }).run(function($rootScope, Bluebird) { Bluebird.setScheduler(function(cb) { $rootScope.$evalAsync(cb); }); }); }(angular, window));
Add configurable path to hosts file for HostLookup() Required for unit testing so that tests don't have to rely on /etc/hosts file.
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = None def __init__(self, hosts_file=None): if hosts_file: self._hosts = hosts(path=hosts_file) else: self._hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: results.append((family, ip)) return results class HostLookup(object): _hosts = hosts() @idiokit.stream def host_lookup(self, host, resolver=None): results = _filter_ips([host]) if not results: results = _filter_ips(self._hosts.load().name_to_ips(host)) if not results: results = [] error = None try: records = yield a(host, resolver) except DNSError as error: results = [] else: results = _filter_ips(records) try: records = yield aaaa(host, resolver) except DNSError: if error is not None: raise error else: results.extend(_filter_ips(records)) idiokit.stop(results) host_lookup = HostLookup().host_lookup
:sparkles: Set Application as a static class in IoC
<?php namespace Tapestry\Providers; use Tapestry\Tapestry; use Tapestry\Console\Application; use Tapestry\Console\Commands\InitCommand; use Tapestry\Console\Commands\BuildCommand; use Tapestry\Console\Commands\SelfUpdateCommand; use League\Container\ServiceProvider\AbstractServiceProvider; class CommandServiceProvider extends AbstractServiceProvider { /** * @var array */ protected $provides = [ Application::class, InitCommand::class, ]; /** * Use the register method to register items with the container via the * protected $this->container property or the `getContainer` method * from the ContainerAwareTrait. * * @return void */ public function register() { $container = $this->getContainer(); $container->add(InitCommand::class) ->withArguments([ \Symfony\Component\Filesystem\Filesystem::class, \Symfony\Component\Finder\Finder::class, ]); $this->getContainer()->add(BuildCommand::class) ->withArguments([ Tapestry::class, $this->getContainer()->get('Compile.Steps'), ]); $container->add(SelfUpdateCommand::class) ->withArguments([ \Symfony\Component\Filesystem\Filesystem::class, \Symfony\Component\Finder\Finder::class, ]); $container->share(Application::class) ->withArguments([ Tapestry::class, [ $container->get(InitCommand::class), $container->get(BuildCommand::class), $container->get(SelfUpdateCommand::class), ], ]); } }
<?php namespace Tapestry\Providers; use Tapestry\Tapestry; use Tapestry\Console\Application; use Tapestry\Console\Commands\InitCommand; use Tapestry\Console\Commands\BuildCommand; use Tapestry\Console\Commands\SelfUpdateCommand; use League\Container\ServiceProvider\AbstractServiceProvider; class CommandServiceProvider extends AbstractServiceProvider { /** * @var array */ protected $provides = [ Application::class, InitCommand::class, ]; /** * Use the register method to register items with the container via the * protected $this->container property or the `getContainer` method * from the ContainerAwareTrait. * * @return void */ public function register() { $container = $this->getContainer(); $container->add(InitCommand::class) ->withArguments([ \Symfony\Component\Filesystem\Filesystem::class, \Symfony\Component\Finder\Finder::class, ]); $this->getContainer()->add(BuildCommand::class) ->withArguments([ Tapestry::class, $this->getContainer()->get('Compile.Steps'), ]); $container->add(SelfUpdateCommand::class) ->withArguments([ \Symfony\Component\Filesystem\Filesystem::class, \Symfony\Component\Finder\Finder::class, ]); $container->add(Application::class) ->withArguments([ Tapestry::class, [ $container->get(InitCommand::class), $container->get(BuildCommand::class), $container->get(SelfUpdateCommand::class), ], ]); } }
Correct import behavior to prevent Runtime error
""" sentry.utils.imports ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pkgutil import six class ModuleProxyCache(dict): def __missing__(self, key): if '.' not in key: return __import__(key) module_name, class_name = key.rsplit('.', 1) module = __import__(module_name, {}, {}, [class_name]) handler = getattr(module, class_name) # We cache a NoneType for missing imports to avoid repeated lookups self[key] = handler return handler _cache = ModuleProxyCache() def import_string(path): """ Path must be module.path.ClassName >>> cls = import_string('sentry.models.Group') """ result = _cache[path] return result def import_submodules(context, root_module, path): """ Import all submodules and register them in the ``context`` namespace. >>> import_submodules(locals(), __name__, __path__) """ for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + '.'): # this causes a Runtime error with model conflicts # module = loader.find_module(module_name).load_module(module_name) module = __import__(module_name, globals(), locals(), ['__name__']) for k, v in six.iteritems(vars(module)): if not k.startswith('_'): context[k] = v context[module_name] = module
""" sentry.utils.imports ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pkgutil import six class ModuleProxyCache(dict): def __missing__(self, key): if '.' not in key: return __import__(key) module_name, class_name = key.rsplit('.', 1) module = __import__(module_name, {}, {}, [class_name]) handler = getattr(module, class_name) # We cache a NoneType for missing imports to avoid repeated lookups self[key] = handler return handler _cache = ModuleProxyCache() def import_string(path): """ Path must be module.path.ClassName >>> cls = import_string('sentry.models.Group') """ result = _cache[path] return result def import_submodules(context, root_module, path): """ Import all submodules and register them in the ``context`` namespace. >>> import_submodules(locals(), __name__, __path__) """ for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + '.'): module = loader.find_module(module_name).load_module(module_name) for k, v in six.iteritems(vars(module)): if not k.startswith('_'): context[k] = v context[module_name] = module
Use conditional validation on contact info only if user has intention
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class FeedbackRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'message' => 'nullable|max:255', 'answer_of_custom_question' => 'nullable|max:255', 'join_club_intention' => 'required|in:0,1,2', 'join_tea_party_intention' => 'required|in:0,1,2', ]; //若非茶會與社團皆不參加,則必須勾選聯絡資訊 if ($this->request->get('join_club_intention') != 0 || $this->request->get('join_tea_party_intention') != 0) { $rules = array_merge($rules, [ 'include_phone' => 'nullable|required_without_all:include_email,include_facebook,include_line', 'include_email' => 'nullable|required_without_all:include_phone,include_facebook,include_line', 'include_facebook' => 'nullable|required_without_all:include_phone,include_email,include_line', 'include_line' => 'nullable|required_without_all:include_phone,include_email,include_facebook', ]); } return $rules; } }
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class FeedbackRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'include_phone' => 'nullable|required_without_all:include_email,include_facebook,include_line', 'include_email' => 'nullable|required_without_all:include_phone,include_facebook,include_line', 'include_facebook' => 'nullable|required_without_all:include_phone,include_email,include_line', 'include_line' => 'nullable|required_without_all:include_phone,include_email,include_facebook', 'message' => 'nullable|max:255', 'answer_of_custom_question' => 'nullable|max:255', 'join_club_intention' => 'required|in:0,1,2', 'join_tea_party_intention' => 'required|in:0,1,2', ]; } }
Remove useless object manager property
<?php namespace Natso\Piraeus\Block\Payment; class Redirect extends \Magento\Framework\View\Element\Template { public $customerSession; public $logger; protected $_helper; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Customer\Model\Session $customerSession, \Natso\Piraeus\Helper\Data $_helper, \Psr\Log\LoggerInterface $logger, array $data = [] ) { parent::__construct($context, $data); $this->customerSession = $customerSession; $this->_helper = $_helper; $this->logger = $logger; } public function generateTicket() { try { $soap = new \Zend\Soap\Client($this->_helper->getTicketUrl()); $xml = array('Request' => $this->_helper->getTicketData()); $response = $soap->IssueNewTicket($xml); $this->logger->debug(print_r($xml, true)); $this->logger->debug(print_r($response, true)); } catch(Exception $e) { //echo $e; } } public function getPostData(){ return $this->_helper->getPostData(); } public function getPostUrl(){ return $this->_helper->getPostUrl(); } }
<?php namespace Natso\Piraeus\Block\Payment; class Redirect extends \Magento\Framework\View\Element\Template { public $customerSession; public $logger; protected $_objectManager; protected $_helper; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Customer\Model\Session $customerSession, \Magento\Framework\ObjectManagerInterface $_objectManager, \Natso\Piraeus\Helper\Data $_helper, \Psr\Log\LoggerInterface $logger, array $data = [] ) { parent::__construct($context, $data); $this->customerSession = $customerSession; $this->_objectManager = $_objectManager; $this->_helper = $_helper; $this->logger = $logger; } public function generateTicket() { try { $soap = new \Zend\Soap\Client($this->_helper->getTicketUrl()); $xml = array('Request' => $this->_helper->getTicketData()); $response = $soap->IssueNewTicket($xml); $this->logger->debug(print_r($xml, true)); $this->logger->debug(print_r($response, true)); } catch(Exception $e) { //echo $e; } } public function getPostData(){ return $this->_helper->getPostData(); } public function getPostUrl(){ return $this->_helper->getPostUrl(); } }
Disable APC cache clearing on SaaS
<?php class Cache { private function createCacheKey($key, $isUserValue, $userId = null) { $CC_CONFIG = Config::getConfig(); $a = $CC_CONFIG["apiKey"][0]; if ($isUserValue) { $cacheKey = "{$key}{$userId}{$a}"; } else { $cacheKey = "{$key}{$a}"; } return $cacheKey; } public function store($key, $value, $isUserValue, $userId = null) { $cacheKey = self::createCacheKey($key, $userId); //XXX: Disabling APC on SaaS because it turns out we have multiple webservers // running, which means we have to use a distributed data cache like memcached. //return apc_store($cacheKey, $value); return false; } public function fetch($key, $isUserValue, $userId = null) { $cacheKey = self::createCacheKey($key, $isUserValue, $userId); //XXX: Disabling APC on SaaS because it turns out we have multiple webservers // running, which means we have to use a distributed data cache like memcached. //return apc_fetch($cacheKey); return false; } public static function clear() { // Disabled on SaaS // apc_clear_cache('user'); // apc_clear_cache(); } }
<?php class Cache { private function createCacheKey($key, $isUserValue, $userId = null) { $CC_CONFIG = Config::getConfig(); $a = $CC_CONFIG["apiKey"][0]; if ($isUserValue) { $cacheKey = "{$key}{$userId}{$a}"; } else { $cacheKey = "{$key}{$a}"; } return $cacheKey; } public function store($key, $value, $isUserValue, $userId = null) { $cacheKey = self::createCacheKey($key, $userId); //XXX: Disabling APC on SaaS because it turns out we have multiple webservers // running, which means we have to use a distributed data cache like memcached. //return apc_store($cacheKey, $value); return false; } public function fetch($key, $isUserValue, $userId = null) { $cacheKey = self::createCacheKey($key, $isUserValue, $userId); //XXX: Disabling APC on SaaS because it turns out we have multiple webservers // running, which means we have to use a distributed data cache like memcached. //return apc_fetch($cacheKey); return false; } public static function clear() { apc_clear_cache('user'); apc_clear_cache(); } }
Add python-dateutil as a project dependency. We need its handy "parse" function.
#!/usr/bin/env python3 import os from setuptools import setup, find_packages def get_readme(): return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() setup( author="Julio Gonzalez Altamirano", author_email='[email protected]', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', ], description="ETL for CapMetro raw data.", entry_points={ 'console_scripts': [ 'capmetrics=capmetrics_etl.cli:etl', 'capmetrics-tables=capmetrics_etl.cli.tables' ], }, install_requires=['click', 'python-dateutil', 'pytz', 'sqlalchemy', 'xlrd'], keywords="python etl transit", license="MIT", long_description=get_readme(), name='capmetrics-etl', package_data={ 'capmetrics_etl': ['templates/*.html'], }, packages=find_packages(include=['capmetrics_etl', 'capmetrics_etl.*'], exclude=['tests', 'tests.*']), platforms=['any'], url='https://github.com/jga/capmetrics-etl', version='0.1.0' )
#!/usr/bin/env python3 import os from setuptools import setup, find_packages def get_readme(): return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() setup( author="Julio Gonzalez Altamirano", author_email='[email protected]', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', ], description="ETL for CapMetro raw data.", entry_points={ 'console_scripts': [ 'capmetrics=capmetrics_etl.cli:etl', 'capmetrics-tables=capmetrics_etl.cli.tables' ], }, install_requires=['click', 'pytz', 'sqlalchemy', 'xlrd'], keywords="python etl transit", license="MIT", long_description=get_readme(), name='capmetrics-etl', package_data={ 'capmetrics_etl': ['templates/*.html'], }, packages=find_packages(include=['capmetrics_etl', 'capmetrics_etl.*'], exclude=['tests', 'tests.*']), platforms=['any'], url='https://github.com/jga/capmetrics-etl', version='0.1.0' )
Add condition to handle the case when `number` is 0
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) sentence = "" if number is 0: sentence = "zero" return sentence
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING)
Fix test failures in Python 3.3b2 The fromlist argument of __import__ was being called as [''], which is meaningless. Because we need fromlist to be non-empty to get the submodule returned, this was changed to ['*'].
""" This module adds several functions for interactive source code inspection. """ import inspect from sympy.core.compatibility import callable def source(object): """ Prints the source code of a given object. """ print 'In file: %s' % inspect.getsourcefile(object) print inspect.getsource(object) def get_class(lookup_view): """ Convert a string version of a class name to the object. For example, get_class('sympy.core.Basic') will return class Basic located in module sympy.core """ if isinstance(lookup_view, str): lookup_view = lookup_view mod_name, func_name = get_mod_func(lookup_view) if func_name != '': lookup_view = getattr(__import__(mod_name, {}, {}, ['*']), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) return lookup_view def get_mod_func(callback): """ splits the string path to a class into a string path to the module and the name of the class. For example: >>> from sympy.utilities.source import get_mod_func >>> get_mod_func('sympy.core.basic.Basic') ('sympy.core.basic', 'Basic') """ dot = callback.rfind('.') if dot == -1: return callback, '' return callback[:dot], callback[dot+1:]
""" This module adds several functions for interactive source code inspection. """ import inspect from sympy.core.compatibility import callable def source(object): """ Prints the source code of a given object. """ print 'In file: %s' % inspect.getsourcefile(object) print inspect.getsource(object) def get_class(lookup_view): """ Convert a string version of a class name to the object. For example, get_class('sympy.core.Basic') will return class Basic located in module sympy.core """ if isinstance(lookup_view, str): lookup_view = lookup_view mod_name, func_name = get_mod_func(lookup_view) if func_name != '': lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) if not callable(lookup_view): raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name)) return lookup_view def get_mod_func(callback): """ splits the string path to a class into a string path to the module and the name of the class. For example: >>> from sympy.utilities.source import get_mod_func >>> get_mod_func('sympy.core.basic.Basic') ('sympy.core.basic', 'Basic') """ dot = callback.rfind('.') if dot == -1: return callback, '' return callback[:dot], callback[dot+1:]
Add an option to show a personalised block to everyone
from __future__ import absolute_import, unicode_literals from django.utils.translation import ugettext_lazy as _ from wagtail.core import blocks from wagtail_personalisation.adapters import get_segment_adapter from wagtail_personalisation.models import Segment def list_segment_choices(): yield -1, ("Show to everyone") for pk, name in Segment.objects.values_list('pk', 'name'): yield pk, name class PersonalisedStructBlock(blocks.StructBlock): """Struct block that allows personalisation per block.""" segment = blocks.ChoiceBlock( choices=list_segment_choices, required=False, label=_("Personalisation segment"), help_text=_("Only show this content block for users in this segment")) def render(self, value, context=None): """Only render this content block for users in this segment. :param value: The value from the block :type value: dict :param context: The context containing the request :type context: dict :returns: The provided block if matched, otherwise an empty string :rtype: blocks.StructBlock or empty str """ request = context['request'] adapter = get_segment_adapter(request) user_segments = adapter.get_segments() try: segment_id = int(value['segment']) except (ValueError, TypeError): return '' if segment_id > 0: for segment in user_segments: if segment.id == segment_id: return super(PersonalisedStructBlock, self).render( value, context) if segment_id == -1: return super(PersonalisedStructBlock, self).render( value, context) return ''
from __future__ import absolute_import, unicode_literals from django.utils.translation import ugettext_lazy as _ from wagtail.core import blocks from wagtail_personalisation.adapters import get_segment_adapter from wagtail_personalisation.models import Segment def list_segment_choices(): for pk, name in Segment.objects.values_list('pk', 'name'): yield pk, name class PersonalisedStructBlock(blocks.StructBlock): """Struct block that allows personalisation per block.""" segment = blocks.ChoiceBlock( choices=list_segment_choices, required=False, label=_("Personalisation segment"), help_text=_("Only show this content block for users in this segment")) def render(self, value, context=None): """Only render this content block for users in this segment. :param value: The value from the block :type value: dict :param context: The context containing the request :type context: dict :returns: The provided block if matched, otherwise an empty string :rtype: blocks.StructBlock or empty str """ request = context['request'] adapter = get_segment_adapter(request) user_segments = adapter.get_segments() if value['segment']: for segment in user_segments: if segment.id == int(value['segment']): return super(PersonalisedStructBlock, self).render( value, context) return ""
Change to minify-plugin from babili
const path = require('path'); const webpack = require('webpack'); const MinifyPlugin = require("babel-minify-webpack-plugin"); const isProd = process.env.NODE_ENV === 'PRODUCTION'; const outputFilename = isProd ? 'react-layout-transition.min.js' : 'react-layout-transition.js'; module.exports = { devtool: !isProd ? 'source-map' : '', entry: path.resolve(__dirname, 'src/index.ts'), output: { path: path.resolve(__dirname, 'dist'), filename: outputFilename, library: 'ReactLayoutTransition', libraryTarget: 'umd', }, externals: { 'react': { commonjs: 'react', commonjs2: 'react', root: 'React', }, }, module: { rules: [ { test: /\.tsx|ts?$/, loader: 'awesome-typescript-loader', exclude: path.resolve(__dirname, 'node_modules'), }, ], }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, plugins: isProd ? [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new MinifyPlugin({}, { removeComments: true, }), ] : [], };
const path = require('path'); const webpack = require('webpack'); const BabiliPlugin = require('babili-webpack-plugin'); const isProd = process.env.NODE_ENV === 'PRODUCTION'; const outputFilename = isProd ? 'react-layout-transition.min.js' : 'react-layout-transition.js'; module.exports = { devtool: !isProd ? 'source-map' : '', entry: path.resolve(__dirname, 'src/index.ts'), output: { path: path.resolve(__dirname, 'dist'), filename: outputFilename, library: 'ReactLayoutTransition', libraryTarget: 'umd', }, externals: { 'react': { commonjs: 'react', commonjs2: 'react', root: 'React', }, }, module: { rules: [ { test: /\.tsx|ts?$/, loader: 'awesome-typescript-loader', exclude: path.resolve(__dirname, 'node_modules'), }, ], }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, plugins: isProd ? [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new BabiliPlugin({}, { removeComments: true, }), ] : [], };
Add more helpful error message Should provide more detailed error message for diagnosing #57
<?php namespace PivotLibre\Tideman; use \InvalidArgumentException; class MarginRegistry { private $registry = array(); protected function makeKey(Candidate $winner, Candidate $loser) : string { $winnerId = $winner->getId(); $loserId = $loser->getId(); $key = $winnerId . $loserId; return $key; } public function register(Margin $margin) : void { $key = $this->makeKey($margin->getWinner(), $margin->getLoser()); if (array_key_exists($key, $this->registry)) { throw new InvalidArgumentException( "This Margin has already been registered: $margin" ); } $this->registry[$key] = $margin; } public function get(Candidate $winner, Candidate $loser) : Margin { $key = $this->makeKey($winner, $loser); if (!array_key_exists($key, $this->registry)) { $marginAsString = "{$winner->getId()} -> {$loser->getId()}"; throw new InvalidArgumentException( "No margin found for the given pair of Candidates. $marginAsString" ); } else { $margin = $this->registry[$key]; return $margin; } } public function getCount() : int { return sizeof($this->registry); } public function getAll() : MarginList { $marginsOnly = array_values($this->registry); $marginsList = new MarginList(...$marginsOnly); return $marginsList; } }
<?php namespace PivotLibre\Tideman; use \InvalidArgumentException; class MarginRegistry { private $registry = array(); protected function makeKey(Candidate $winner, Candidate $loser) : string { $winnerId = $winner->getId(); $loserId = $loser->getId(); $key = $winnerId . $loserId; return $key; } public function register(Margin $margin) : void { $key = $this->makeKey($margin->getWinner(), $margin->getLoser()); if (array_key_exists($key, $this->registry)) { throw new InvalidArgumentException( "This Margin has already been registered." ); } $this->registry[$key] = $margin; } public function get(Candidate $winner, Candidate $loser) : Margin { $key = $this->makeKey($winner, $loser); if (!array_key_exists($key, $this->registry)) { $marginAsString = "{$winner->getId()} -> {$loser->getId()}"; throw new InvalidArgumentException( "No margin found for the given pair of Candidates. $marginAsString" ); } else { $margin = $this->registry[$key]; return $margin; } } public function getCount() : int { return sizeof($this->registry); } public function getAll() : MarginList { $marginsOnly = array_values($this->registry); $marginsList = new MarginList(...$marginsOnly); return $marginsList; } }
Load external firebird or sybase dialect if available Fixes: #5318 Extension of I1660abb11c02656fbf388f2f9c4257075111be58 Change-Id: I32b678430497327f9b08f821bd345a2557e34b1f
# dialects/__init__.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php __all__ = ( "firebird", "mssql", "mysql", "oracle", "postgresql", "sqlite", "sybase", ) from .. import util def _auto_fn(name): """default dialect importer. plugs into the :class:`.PluginLoader` as a first-hit system. """ if "." in name: dialect, driver = name.split(".") else: dialect = name driver = "base" try: if dialect == "firebird": try: module = __import__("sqlalchemy_firebird") except ImportError: module = __import__("sqlalchemy.dialects.firebird").dialects module = getattr(module, dialect) elif dialect == "sybase": try: module = __import__("sqlalchemy_sybase") except ImportError: module = __import__("sqlalchemy.dialects.sybase").dialects module = getattr(module, dialect) else: module = __import__("sqlalchemy.dialects.%s" % (dialect,)).dialects module = getattr(module, dialect) except ImportError: return None if hasattr(module, driver): module = getattr(module, driver) return lambda: module.dialect else: return None registry = util.PluginLoader("sqlalchemy.dialects", auto_fn=_auto_fn) plugins = util.PluginLoader("sqlalchemy.plugins")
# dialects/__init__.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php __all__ = ( "firebird", "mssql", "mysql", "oracle", "postgresql", "sqlite", "sybase", ) from .. import util def _auto_fn(name): """default dialect importer. plugs into the :class:`.PluginLoader` as a first-hit system. """ if "." in name: dialect, driver = name.split(".") else: dialect = name driver = "base" try: if dialect == "firebird": try: module = __import__("sqlalchemy_firebird") dialect = "dialect" except: module = __import__("sqlalchemy.dialects.firebird").dialects else: module = __import__("sqlalchemy.dialects.%s" % (dialect,)).dialects except ImportError: return None module = getattr(module, dialect) if hasattr(module, driver): module = getattr(module, driver) return lambda: module.dialect else: return None registry = util.PluginLoader("sqlalchemy.dialects", auto_fn=_auto_fn) plugins = util.PluginLoader("sqlalchemy.plugins")
Change EventDispatcher use to EventDispatcherInterface This change makes code more testable and decoupled of the EventDispatcher Component
<?php namespace Scarlett; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Matcher\UrlMatcherInterface; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Scarlett\Event\ResponseEvent; use Scarlett\Event\KernelEvents; class Kernel { private $dispatcher; private $matcher; private $resolver; public function __construct(EventDispatcherInterface $dispatcher, UrlMatcherInterface $matcher, ControllerResolverInterface $resolver) { $this->dispatcher = $dispatcher; $this->matcher = $matcher; $this->resolver = $resolver; } public function handle(Request $request) { try{ $request->attributes->add($this->matcher->match($request->getPathInfo())); $controller = $this->resolver->getController($request); $arguments = $this->resolver->getArguments($request, $controller); $response = call_user_func_array($controller, $arguments); }catch(ResourceNotFoundException $e) { $response = new Response('Not found', 404); }catch(\Exception $e){ $response = new Response('[Scarlett Kernel Exception] '.$e->getMessage(), 500); $this->dispatcher->dispatch(KernelEvents::EXCEPTION, new ExceptionEvent($request, $e)); } $this->dispatcher->dispatch(KernelEvents::RESPONSE, new ResponseEvent($request, $response)); return $response; } }
<?php namespace Scarlett; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Matcher\UrlMatcherInterface; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\EventDispatcher\EventDispatcher; use Scarlett\Event\ResponseEvent; use Scarlett\Event\KernelEvents; class Kernel { private $dispatcher; private $matcher; private $resolver; public function __construct(EventDispatcher $dispatcher, UrlMatcherInterface $matcher, ControllerResolverInterface $resolver) { $this->dispatcher = $dispatcher; $this->matcher = $matcher; $this->resolver = $resolver; } public function handle(Request $request) { try{ $request->attributes->add($this->matcher->match($request->getPathInfo())); $controller = $this->resolver->getController($request); $arguments = $this->resolver->getArguments($request, $controller); $response = call_user_func_array($controller, $arguments); }catch(ResourceNotFoundException $e) { $response = new Response('Not found', 404); }catch(\Exception $e){ $response = new Response('[Scarlett Kernel Exception] '.$e->getMessage(), 500); $this->dispatcher->dispatch(KernelEvents::EXCEPTION, new ExceptionEvent($request, $e)); } $this->dispatcher->dispatch(KernelEvents::RESPONSE, new ResponseEvent($request, $response)); return $response; } }
Disable typescript instrument on tests
"use strict"; const Task = require('../Task'), gulp = require('gulp'), mocha = require('gulp-mocha'), istanbul = require('gulp-istanbul'), isparta = require('isparta'), Promise = require('bluebird'); class TestTask extends Task { constructor(buildManager) { super(buildManager); this.command = "test"; let extension = null; if (this._buildManager.options.typescript) { require('ts-node/register'); extension = 'ts'; } else { require('babel-core/register'); extension = 'js'; } this.dependsOn = [() => { if (this._buildManager.options.typescript) return Promise.resolve(); return gulp.src([this._buildManager.options.scripts + '*/*.' + extension]) .pipe(istanbul({ instrumenter: isparta.Instrumenter, includeUntested: true })) .pipe(istanbul.hookRequire()); }]; } action() { return gulp.src(this._buildManager.options.test, {read: false}) .pipe(mocha({ reporter: 'spec', compilers: { ts: require('ts-node/register'), js: require('babel-core/register') } })) .pipe(istanbul.writeReports({ reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })) } } module.exports = TestTask;
"use strict"; const Task = require('../Task'), gulp = require('gulp'), mocha = require('gulp-mocha'), istanbul = require('gulp-istanbul'), isparta = require('isparta'); class TestTask extends Task { constructor(buildManager) { super(buildManager); this.command = "test"; let extension = null; if (this._buildManager.options.typescript) { require('ts-node/register'); extension = 'ts'; } else { require('babel-core/register'); extension = 'js'; } this.dependsOn = [() => { return gulp.src([this._buildManager.options.scripts + '*/*.' + extension]) .pipe(istanbul({ instrumenter: isparta.Instrumenter, includeUntested: true })) .pipe(istanbul.hookRequire()); }]; } action() { return gulp.src(this._buildManager.options.test, {read: false}) .pipe(mocha({ reporter: 'spec', compilers: { ts: require('ts-node/register'), js: require('babel-core/register') } })) .pipe(istanbul.writeReports({ reporters: ['lcov', 'json', 'text', 'text-summary', 'cobertura'] })) } } module.exports = TestTask;
Add cormoran to vendor script
import path from 'path'; import webpack from 'webpack' let config = { entry: { main: './src/main.js', vendor: [ 'react', 'react-dom', 'cormoran' ] }, output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'main.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.less$/, exclude: /node_modules/, loader: 'style!css?modules!less' }, { test: /\.(jpg|png|ttf|eot|woff|woff2|svg)$/, exclude: /node_modules/, loader: 'url?limit=100000' } ] }, devtool: 'eval-source-map', devServer: { historyApiFallback: true }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: [ 'vendor' ], filename: '[name].js', minChunks: Infinity }), ] } if (process.env.NODE_ENV === 'production') { config.devtool = 'source-map'; config.devServer = {}; config.plugins = config.plugins.concat([ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8 : true } }) ]); } export default config
import path from 'path'; import webpack from 'webpack' let config = { entry: { main: './src/main.js', vendor: [ 'react', 'react-dom' ] }, output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'main.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.less$/, exclude: /node_modules/, loader: 'style!css?modules!less' }, { test: /\.(jpg|png|ttf|eot|woff|woff2|svg)$/, exclude: /node_modules/, loader: 'url?limit=100000' } ] }, devtool: 'eval-source-map', devServer: { historyApiFallback: true }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: [ 'vendor' ], filename: '[name].js', minChunks: Infinity }), ] } if (process.env.NODE_ENV === 'production') { config.devtool = 'source-map'; config.devServer = {}; config.plugins = config.plugins.concat([ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8 : true } }) ]); } export default config
Raise ValueError if n < 1
from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n < 1: raise ValueError if n == 1: return Counter() divisor = 2 while n % divisor != 0: divisor = Prime.after(divisor) return Counter({divisor: 1}) + get_prime_factors(n // divisor) def get_flat_prime_factors(n): """ Returns a sorted list of n's prime_factor, where each prime factor is repeated the number of times it divides n """ prime_factors = get_prime_factors(n) return sorted([ x for list_ in ( [factor] * count for factor, count in prime_factors.items() ) for x in list_ ]) def get_divisors(n): """ Returns a set of all divisors of n """ if n < 1: return set() flat_factors = get_flat_prime_factors(n) divisors = set([1, n]) for i in range(len(flat_factors)): for comb in combinations(flat_factors, i + 1): divisors.add(reduce(lambda x, y: x * y, comb)) return divisors def get_proper_divisors(n): """ Returns a set of all proper divisors of n """ return get_divisors(n) - {n}
from collections import Counter from functools import ( lru_cache, reduce, ) from itertools import combinations from prime import Prime @lru_cache(maxsize=None) def get_prime_factors(n): """ Returns the counts of each prime factor of n """ if n == 1: return Counter() divisor = 2 while n % divisor != 0: divisor = Prime.after(divisor) return Counter({divisor: 1}) + get_prime_factors(n // divisor) def get_flat_prime_factors(n): """ Returns a sorted list of n's prime_factor, where each prime factor is repeated the number of times it divides n """ prime_factors = get_prime_factors(n) return sorted([ x for list_ in ( [factor] * count for factor, count in prime_factors.items() ) for x in list_ ]) def get_divisors(n): """ Returns a set of all divisors of n """ if n < 1: return set() flat_factors = get_flat_prime_factors(n) divisors = set([1, n]) for i in range(len(flat_factors)): for comb in combinations(flat_factors, i + 1): divisors.add(reduce(lambda x, y: x * y, comb)) return divisors def get_proper_divisors(n): """ Returns a set of all proper divisors of n """ return get_divisors(n) - {n}
Remove an incorrect documentation URL Fixes #9.
""" Py-Tree-sitter """ import platform from setuptools import setup, Extension setup( name = "tree_sitter", version = "0.0.8", maintainer = "Max Brunsfeld", maintainer_email = "[email protected]", author = "Max Brunsfeld", author_email = "[email protected]", url = "https://github.com/tree-sitter/py-tree-sitter", license = "MIT", platforms = ["any"], python_requires = ">=3.3", description = "Python bindings to the Tree-sitter parsing library", classifiers = [ "License :: OSI Approved :: MIT License", "Topic :: Software Development :: Compilers", "Topic :: Text Processing :: Linguistic", ], packages = ['tree_sitter'], ext_modules = [ Extension( "tree_sitter_binding", [ "tree_sitter/core/lib/src/lib.c", "tree_sitter/binding.c", ], include_dirs = [ "tree_sitter/core/lib/include", "tree_sitter/core/lib/utf8proc", ], extra_compile_args = ( ['-std=c99'] if platform.system() != 'Windows' else None ) ) ], project_urls = { 'Source': 'https://github.com/tree-sitter/py-tree-sitter', } )
""" Py-Tree-sitter """ import platform from setuptools import setup, Extension setup( name = "tree_sitter", version = "0.0.8", maintainer = "Max Brunsfeld", maintainer_email = "[email protected]", author = "Max Brunsfeld", author_email = "[email protected]", url = "https://github.com/tree-sitter/py-tree-sitter", license = "MIT", platforms = ["any"], python_requires = ">=3.3", description = "Python bindings to the Tree-sitter parsing library", classifiers = [ "License :: OSI Approved :: MIT License", "Topic :: Software Development :: Compilers", "Topic :: Text Processing :: Linguistic", ], packages = ['tree_sitter'], ext_modules = [ Extension( "tree_sitter_binding", [ "tree_sitter/core/lib/src/lib.c", "tree_sitter/binding.c", ], include_dirs = [ "tree_sitter/core/lib/include", "tree_sitter/core/lib/utf8proc", ], extra_compile_args = ( ['-std=c99'] if platform.system() != 'Windows' else None ) ) ], project_urls = { 'Source': 'https://github.com/tree-sitter/py-tree-sitter', 'Documentation': 'http://initd.org/psycopg/docs/', } )
Fix no run_run icon in old pycharm version.
package com.iselsoft.ptest.runLineMarker; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.intellij.util.Function; import com.iselsoft.ptest.runConfiguration.PTestConfigurationProducer; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; import org.jetbrains.annotations.Nullable; public class PTestRunLineMarkerContributor extends RunLineMarkerContributor { private static final PTestConfigurationProducer CONFIG_PRODUCER = new PTestConfigurationProducer(); private static final Function<PsiElement, String> TOOLTIP_PROVIDER = new Function<PsiElement, String>() { @Override public String fun(PsiElement psiElement) { return "Run ptest"; } }; @Nullable @Override public Info getInfo(PsiElement psiElement) { if (psiElement instanceof PyFunction && CONFIG_PRODUCER.isPTestMethod(psiElement, null)) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } else if (psiElement instanceof PyClass && CONFIG_PRODUCER.isPTestClass(psiElement, null)) { try { return new Info(AllIcons.RunConfigurations.TestState.Run_run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } catch (NoSuchFieldError e) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } } return null; } }
package com.iselsoft.ptest.runLineMarker; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.intellij.util.Function; import com.iselsoft.ptest.runConfiguration.PTestConfigurationProducer; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; import org.jetbrains.annotations.Nullable; public class PTestRunLineMarkerContributor extends RunLineMarkerContributor { private static final PTestConfigurationProducer CONFIG_PRODUCER = new PTestConfigurationProducer(); private static final Function<PsiElement, String> TOOLTIP_PROVIDER = new Function<PsiElement, String>() { @Override public String fun(PsiElement psiElement) { return "Run ptest"; } }; @Nullable @Override public Info getInfo(PsiElement psiElement) { if (psiElement instanceof PyFunction && CONFIG_PRODUCER.isPTestMethod(psiElement, null)) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } else if (psiElement instanceof PyClass && CONFIG_PRODUCER.isPTestClass(psiElement, null)) { return new Info(AllIcons.RunConfigurations.TestState.Run_run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } return null; } }
Add FormErrors decorator in a better way Thanks to lubs in IRC for pointing this out.
<?php namespace EdpUser\Form; use Zend\Form\Form, EdpCommon\Form\ProvidesEventsForm, EdpUser\Module; class Login extends ProvidesEventsForm { public function init() { $this->setMethod('post') ->loadDefaultDecorators() ->setDecorators(array('FormErrors') + $this->getDecorators()); $this->addElement('text', 'email', array( 'filters' => array('StringTrim'), 'validators' => array( 'EmailAddress', ), 'required' => true, 'label' => 'Email', )); if (Module::getOption('enable_username')) { $emailElement = $this->getElement('email'); $emailElement->removeValidator('EmailAddress') ->setLabel('Email or Username'); // @TODO: make translation-friendly } $this->addElement('password', 'password', array( 'filters' => array('StringTrim'), 'validators' => array( array('StringLength', true, array(6, 999)) ), 'required' => true, 'label' => 'Password', )); $this->addElement('hash', 'csrf', array( 'ignore' => true, 'decorators' => array('ViewHelper'), )); $this->addElement('submit', 'login', array( 'ignore' => true, 'label' => 'Sign In', )); $this->events()->trigger('init', $this); } }
<?php namespace EdpUser\Form; use Zend\Form\Form, EdpCommon\Form\ProvidesEventsForm, EdpUser\Module; class Login extends ProvidesEventsForm { public function init() { $this->setMethod('post'); $this->addDecorator('FormErrors') ->addDecorator('FormElements') ->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'login_form')) ->addDecorator('FormDecorator'); $this->addElement('text', 'email', array( 'filters' => array('StringTrim'), 'validators' => array( 'EmailAddress', ), 'required' => true, 'label' => 'Email', )); if (Module::getOption('enable_username')) { $emailElement = $this->getElement('email'); $emailElement->removeValidator('EmailAddress') ->setLabel('Email or Username'); // @TODO: make translation-friendly } $this->addElement('password', 'password', array( 'filters' => array('StringTrim'), 'validators' => array( array('StringLength', true, array(6, 999)) ), 'required' => true, 'label' => 'Password', )); $this->addElement('hash', 'csrf', array( 'ignore' => true, 'decorators' => array('ViewHelper'), )); $this->addElement('submit', 'login', array( 'ignore' => true, 'label' => 'Sign In', )); $this->events()->trigger('init', $this); } }
Move append out of if/else block
# -*- coding: utf-8 -*- ''' Beacon to manage and report the status of one or more salt proxy processes .. versionadded:: 2015.8.3 ''' # Import python libs from __future__ import absolute_import import logging log = logging.getLogger(__name__) def _run_proxy_processes(proxies): ''' Iterate over a list of proxy names and restart any that aren't running ''' ret = [] for prox_ in proxies: # prox_ is a dict proxy = prox_.keys()[0] result = {} if not __salt__['salt_proxy.is_running'](proxy)['result']: __salt__['salt_proxy.configure_proxy'](proxy, start=True) result[proxy] = 'Proxy {0} was started'.format(proxy) else: msg = 'Proxy {0} is already running'.format(proxy) result[proxy] = msg log.debug(msg) ret.append(result) return ret def beacon(proxies): ''' Handle configured proxies .. code-block:: yaml beacons: salt_proxy: - p8000: {} - p8001: {} ''' log.trace('salt proxy beacon called') return _run_proxy_processes(proxies)
# -*- coding: utf-8 -*- ''' Beacon to manage and report the status of one or more salt proxy processes .. versionadded:: 2015.8.3 ''' # Import python libs from __future__ import absolute_import import logging log = logging.getLogger(__name__) def _run_proxy_processes(proxies): ''' Iterate over a list of proxy names and restart any that aren't running ''' ret = [] for prox_ in proxies: # prox_ is a dict proxy = prox_.keys()[0] result = {} if not __salt__['salt_proxy.is_running'](proxy)['result']: __salt__['salt_proxy.configure_proxy'](proxy, start=True) result[proxy] = 'Proxy {0} was started'.format(proxy) ret.append(result) else: msg = 'Proxy {0} is already running'.format(proxy) result[proxy] = msg ret.append(result) log.debug(msg) return ret def beacon(proxies): ''' Handle configured proxies .. code-block:: yaml beacons: salt_proxy: - p8000: {} - p8001: {} ''' log.trace('salt proxy beacon called') return _run_proxy_processes(proxies)
Enable non-standard imports and indexing in `bulk:all`
<?php namespace App\Console\Commands\Bulk; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class BulkAll extends BaseCommand { protected $signature = 'bulk:all {skip?}'; protected $description = "Reset database and import everything"; public function handle() { $shouldSkipTo = $this->argument('skip') ?? false; // Import all bulkable resources from compliant data services foreach (config('resources.inbound') as $source => $endpoints) { foreach ($endpoints as $endpoint => $resource) { dump("$source >> $endpoint"); if ($shouldSkipTo && $source !== $shouldSkipTo) { dump("Skipping..."); continue; } $this->call('bulk:import', [ 'source' => $source, 'endpoint' => $endpoint, ]); $shouldSkipTo = false; } } // EventOccurrence is not included in import:web to avoid duplication $this->call('import:web-full', ['--yes' => 'default', 'endpoint' => 'event-occurrences']); // Run scout now for faster uptime $this->call('scout:import-all'); // Import non-standard data $this->call('import:mobile'); $this->call('import:sites', ['--yes' => 'default']); $this->call('import:ulan'); // TODO: Use upserts for import:analytics $this->call('import:analytics'); // TODO: Use bulking for import:images $this->call('import:images'); } }
<?php namespace App\Console\Commands\Bulk; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class BulkAll extends BaseCommand { protected $signature = 'bulk:all {skip?}'; protected $description = "Reset database and import everything"; public function handle() { $shouldSkipTo = $this->argument('skip') ?? false; // Import all bulkable resources from compliant data services foreach (config('resources.inbound') as $source => $endpoints) { foreach ($endpoints as $endpoint => $resource) { dump("$source >> $endpoint"); if ($shouldSkipTo && $source !== $shouldSkipTo) { dump("Skipping..."); continue; } $this->call('bulk:import', [ 'source' => $source, 'endpoint' => $endpoint, ]); $shouldSkipTo = false; } } /* // TODO: Use bulking for import:images // TODO: Use upserts for import:analytics // Import non-standard data $this->call('import:mobile'); $this->call('import:sites', ['--yes' => 'default']); $this->call('import:ulan'); $this->call('import:analytics'); // EventOccurrence is not included in import:web to avoid duplication $this->call('import:web-full', ['--yes' => 'default', 'endpoint' => 'event-occurrences']); */ } }
Fix problem with Soundcloud API bug
<?php namespace App\Service; use App\Model\SongRecord; class SoundcloudApiService extends AbstractApiService { public function getSongRecords(array $filters): array { $data = []; foreach($this->licenses as $license) { // because of this: // https://stackoverflow.com/questions/34978178/soundcloud-tracks-api-with-license-cc-by-nc-returning-400-bad-request if ($license === 'by-nc') break; $uri = '?client_id=' . $this->apiKey . '&limit=' . $this->limit . '&license=cc-' . $license . '&tags=' . $filters['tag']; $results = array_values((array)$this->apiClient->performRequest($this->baseUri, $uri)); $data = array_merge($data, $results); } $songRecords = []; foreach($data as $song) { $songRecords[] = new SongRecord( $song['user']['username'], $song['title'], date('i.s', $song['duration']/1000), new \DateTime($song['created_at']), $song['permalink_url'], $song['license'], 'soundcloud' ); } return $songRecords; } }
<?php namespace App\Service; use App\Model\SongRecord; class SoundcloudApiService extends AbstractApiService { public function getSongRecords(array $filters): array { $data = []; foreach($this->licenses as $license) { $uri = '?client_id=' . $this->apiKey . '&limit=' . $this->limit . '&license=cc-' . $license . '&tags=' . $filters['tag']; $results = array_values((array)$this->apiClient->performRequest($this->baseUri, $uri)); $data = array_merge($data, $results); } $songRecords = []; foreach($data as $song) { $songRecords[] = new SongRecord( $song['user']['username'], $song['title'], date('i.s', $song['duration']/1000), new \DateTime($song['created_at']), $song['permalink_url'], $song['license'], 'soundcloud' ); } return $songRecords; } }
Rename the PyPI package to td-watson
from setuptools import setup with open('README.md') as f: readme = f.read() setup( name='td-watson', version='1.0.0', packages=['watson'], author='TailorDev', author_email='[email protected]', license='MIT', long_description=readme, install_requires=[ 'Click', 'arrow', 'requests', ], entry_points={ 'console_scripts': [ 'watson = watson.__main__:cli', ] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Customer Service", "Intended Audience :: End Users/Desktop", "Intended Audience :: Information Technology", "Intended Audience :: Science/Research", "Intended Audience :: Other Audience", "License :: OSI Approved :: MIT License", "Environment :: Console", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Office/Business", "Topic :: Utilities", ], keywords='watson time-tracking time tracking monitoring report', )
from setuptools import setup with open('README.md') as f: readme = f.read() setup( name='watson', version='1.0.0', packages=['watson'], author='TailorDev', author_email='[email protected]', license='MIT', long_description=readme, install_requires=[ 'Click', 'arrow', 'requests', ], entry_points={ 'console_scripts': [ 'watson = watson.__main__:cli', ] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Customer Service", "Intended Audience :: End Users/Desktop", "Intended Audience :: Information Technology", "Intended Audience :: Science/Research", "Intended Audience :: Other Audience", "License :: OSI Approved :: MIT License", "Environment :: Console", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Office/Business", "Topic :: Utilities", ], keywords='watson time-tracking time tracking monitoring report', )
Remove click handler from document when scope is destroyed
angular.module('offClick',[]) .directive('offClick', ['$document', function ($document) { function targetInFilter(target,filter){ if(!target || !filter) return false; var elms = angular.element(filter); var elmsLen = elms.length; for (var i = 0; i< elmsLen; ++i) if(elms[i].contains(target)) return true; return false; } return { restrict: 'A', scope: { offClick: '&', offClickIf: '&' }, link: function (scope, elm, attr) { if (attr.offClickIf) { scope.$watch(scope.offClickIf, function (newVal, oldVal) { if (newVal && !oldVal) { $document.on('click', handler); } else if(!newVal){ $document.off('click', handler); } } ); } else { $document.on('click', handler); } scope.$on('$destroy', function() { $document.off('click', handler); }); function handler(event) { var target = event.target || event.srcElement; if (!(elm[0].contains(target) || targetInFilter(target, attr.offClickFilter))) { scope.$apply(scope.offClick()); } } } }; }]);
angular.module('offClick',[]) .directive('offClick', ['$document', function ($document) { function targetInFilter(target,filter){ if(!target || !filter) return false; var elms = angular.element(filter); var elmsLen = elms.length; for (var i = 0; i< elmsLen; ++i) if(elms[i].contains(target)) return true; return false; } return { restrict: 'A', scope: { offClick: '&', offClickIf: '&' }, link: function (scope, elm, attr) { if (attr.offClickIf) { scope.$watch(scope.offClickIf, function (newVal, oldVal) { if (newVal && !oldVal) { $document.on('click', handler); } else if(!newVal){ $document.off('click', handler); } } ); } else { $document.on('click', handler); } function handler(event) { var target = event.target || event.srcElement; if (!(elm[0].contains(target) || targetInFilter(target, attr.offClickFilter))) { scope.$apply(scope.offClick()); } } } }; }]);
Update package version to 0.1.1
from distutils.core import setup, Extension setup( name = 'iMX233_GPIO', version = '0.1.1', author = 'Stefan Mavrodiev', author_email = '[email protected]', url = 'https://www.olimex.com/', license = 'MIT', description = 'Control GPIOs on iMX233-OLinuXino.', long_description = open('README.txt').read() + open('CHANGES.txt').read(), classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Home Automation', 'Topic :: Software Development :: Embedded Systems' ], ext_modules = [Extension('iMX233_GPIO', ['source/imx233.c'])], package_dir={'': 'source'}, packages=[''], )
from distutils.core import setup, Extension setup( name = 'iMX233_GPIO', version = '0.1.0', author = 'Stefan Mavrodiev', author_email = '[email protected]', url = 'https://www.olimex.com/', license = 'MIT', description = 'Control GPIOs on iMX233-OLinuXino.', long_description = open('README.txt').read() + open('CHANGES.txt').read(), classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Home Automation', 'Topic :: Software Development :: Embedded Systems' ], ext_modules = [Extension('iMX233_GPIO', ['source/imx233.c'])], package_dir={'': 'source'}, packages=[''], )
Fix unit test python3 compatibility.
import base64 import os from distutils.core import Command class TestCommand(Command): description = "Launch all tests under fusion_tables app" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): client_secret = open("/tmp/client_secret.json", "w") data = os.environ.get("CLIENT_SECRET").decode("utf-8") client_secret.write(base64.b64decode(data)) client_secret.close() def configure_settings(self): from django.conf import settings settings.configure( DATABASES={ "default": { "NAME": ":memory:", "ENGINE": "django.db.backends.sqlite3", "TEST": { "NAME": ":memory:" } } }, INSTALLED_APPS=( "django.contrib.contenttypes", "fusion_tables", ), ROOT_URLCONF="tests.urls", MODELS_TO_SYNC=("fusion_tables.SampleModel", ), CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json", LOCATION_FIELDS=("TextField", ) ) def run(self): import django from django.core.management import call_command self.create_client_secret_file() self.configure_settings() django.setup() call_command("test", "fusion_tables")
import base64 import os from distutils.core import Command class TestCommand(Command): description = "Launch all tests under fusion_tables app" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): client_secret = open("/tmp/client_secret.json", "w") data = os.environ.get("CLIENT_SECRET") client_secret.write(base64.b64decode(data)) client_secret.close() def configure_settings(self): from django.conf import settings settings.configure( DATABASES={ "default": { "NAME": ":memory:", "ENGINE": "django.db.backends.sqlite3", "TEST": { "NAME": ":memory:" } } }, INSTALLED_APPS=( "django.contrib.contenttypes", "fusion_tables", ), ROOT_URLCONF="tests.urls", MODELS_TO_SYNC=("fusion_tables.SampleModel", ), CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json", LOCATION_FIELDS=("TextField", ) ) def run(self): import django from django.core.management import call_command self.create_client_secret_file() self.configure_settings() django.setup() call_command("test", "fusion_tables")
Fix displaying the sub query name if not available
import { isString, isEmpty } from 'lodash' import Expression from './base' /** * @class SubQueryExpression */ export default class SubQuery extends Expression { /** * * @param {Query|Literal} query * @constructor */ constructor(query) { super() this.columns = [] this.query = query this._isCTE = false } /** * * @param {String} name * @param {Array} columns */ as(name, ...columns) { this.columns = columns return super.as(name) } /** * * @param {Boolean} flag * @returns {SubQuery} */ isCTE(flag = true) { this._isCTE = flag return this } /** * * @param {Compiler} compiler * @returns {String} */ compile(compiler) { let query = `(${this.query.compile(compiler)})` if (! this.alias ) return query let name = compiler.quote(this.alias) if (! isEmpty(this.columns) ) { let columns = this.columns.map(value => compiler.quote(value)) name += `(${columns.join(', ')})` } return this._isCTE ? `${name} as ${query}` : `${query} as ${name}` } /** * * @param {Any} expr * @returns {Boolean} */ isEqual(expr) { if ( isString(expr) ) return expr === this.alias return super.isEqual() || ( expr instanceof SubQuery && expr.alias === this.alias ) } }
import { isString, isEmpty } from 'lodash' import Expression from './base' /** * @class SubQueryExpression */ export default class SubQuery extends Expression { /** * * @param {Query|Literal} query * @constructor */ constructor(query) { super() this.columns = [] this.query = query this._isCTE = false } /** * * @param {String} table * @param {Array} columns */ as(table, ...columns) { this.columns = columns return super.as(table) } /** * * @param {Boolean} flag * @returns {SubQuery} */ isCTE(flag = true) { this._isCTE = flag return this } /** * * @param {Compiler} compiler * @returns {String} */ compile(compiler) { let table = compiler.quote(this.alias) let query = `(${this.query.compile(compiler)})` if (! isEmpty(this.columns) ) { let columns = this.columns.map(value => compiler.quote(value)) table += `(${columns.join(', ')})` } return this._isCTE ? `${table} as ${query}` : `${query} as ${table}` } /** * * @param {Any} expr * @returns {Boolean} */ isEqual(expr) { if ( isString(expr) ) return expr === this.alias return super.isEqual() || ( expr instanceof SubQuery && expr.alias === this.alias ) } }
Move ESI url prefix to variable
import module from '../../module' import command from '../../components/command' import loader from '../../components/loader' import axios from 'axios' import humanize from '../../utils/humanize' export default module( loader(() => { console.log('test') }), command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => { try { const esiURL = 'https://esi.tech.ccp.is/latest/'; const {data: itemData} = await axios.get( `${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}` ); const itemid = itemData.inventorytype[0]; const {data: priceData} = await axios.get( `http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142` ); const sellFivePercent = humanize(priceData[0].sell.fivePercent); const buyFivePercent = humanize(priceData[0].buy.fivePercent); message.channel.sendMessage( `__Price of **${args}** (or nearest match) in Jita__:\n` + `**Sell**: ${sellFivePercent} ISK\n` + `**Buy**: ${buyFivePercent} ISK` ) } catch(e) { console.error(e); throw e } }) )
import module from '../../module' import command from '../../components/command' import loader from '../../components/loader' import axios from 'axios' import humanize from '../../utils/humanize' export default module( loader(() => { console.log('test') }), command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => { try { const {data: itemData} = await axios.get( `https://esi.tech.ccp.is/latest/search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}` ); const itemid = itemData.inventorytype[0]; const {data: priceData} = await axios.get( `http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142` ); const sellFivePercent = humanize(priceData[0].sell.fivePercent); const buyFivePercent = humanize(priceData[0].buy.fivePercent); message.channel.sendMessage( `__Price of **${args}** (or nearest match) in Jita__:\n` + `**Sell**: ${sellFivePercent} ISK\n` + `**Buy**: ${buyFivePercent} ISK` ) } catch(e) { console.error(e); throw e } }) )
Make the ASCII keyCode unique for the Signature object
$(document).ready(function() { $(document).keyup(function(e) { var tag = e.target.tagName.toLowerCase(); if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) { if (e.keyCode==78 || e.keyCode==77) { $('.nav-menu-icon').trigger('click'); } else if (e.keyCode==65) { $('.search-menu-icon').trigger('click'); } else if (e.keyCode==73 && e.shiftKey) { $( "#new-ip" ).click(); } else if (e.keyCode==73) { $( "#new-indicator" ).click(); } else if (e.keyCode==69 && e.shiftKey) { $( "#new-event" ).click(); } else if (e.keyCode==69) { $( "#new-email-yaml" ).click(); } else if (e.keyCode==68) { $( "#new-domain" ).click(); } else if (e.keyCode==80) { $( "#new-pcap" ).click(); } else if (e.keyCode==83) { $( "#new-sample" ).click(); } else if (e.keyCode==71) { $( "#new-signature" ).click(); } else if (e.keyCode==27) { $( ".mm-opened").trigger('close'); } else if (e.shiftKey && e.keyCode==191) { $( "#shortcut-keys").click(); } } }); });
$(document).ready(function() { $(document).keyup(function(e) { var tag = e.target.tagName.toLowerCase(); if (tag != 'input' && tag != 'textarea' && tag != 'select' && !e.ctrlKey) { if (e.keyCode==78 || e.keyCode==77) { $('.nav-menu-icon').trigger('click'); } else if (e.keyCode==65) { $('.search-menu-icon').trigger('click'); } else if (e.keyCode==73 && e.shiftKey) { $( "#new-ip" ).click(); } else if (e.keyCode==73) { $( "#new-indicator" ).click(); } else if (e.keyCode==69 && e.shiftKey) { $( "#new-event" ).click(); } else if (e.keyCode==69) { $( "#new-email-yaml" ).click(); } else if (e.keyCode==68) { $( "#new-domain" ).click(); } else if (e.keyCode==80) { $( "#new-pcap" ).click(); } else if (e.keyCode==83) { $( "#new-sample" ).click(); } else if (e.keyCode==83) { $( "#new-signature" ).click(); } else if (e.keyCode==27) { $( ".mm-opened").trigger('close'); } else if (e.shiftKey && e.keyCode==191) { $( "#shortcut-keys").click(); } } }); });
Fix one more missing reference
<?php return [ 'method' => 'post', 'elements' => [ 'is_enabled' => [ 'radio', [ 'label' => __('Enable Automated Assignment'), 'description' => __('Allow the system to periodically automatically assign songs to playlists based on their performance. This process will run in the background, and will only run if this option is set to "Enabled" and at least one playlist is set to "Include in Automated Assignment".'), 'default' => '0', 'choices' => [ 0 => __('Disabled'), 1 => __('Enabled'), ], ] ], 'threshold_days' => [ 'radio', [ 'label' => __('Days Between Automated Assignments'), 'description' => __('Based on this setting, the system will automatically reassign songs every (this) days using data from the previous (this) days.'), 'class' => 'inline', 'default' => \AzuraCast\Sync\Task\RadioAutomation::DEFAULT_THRESHOLD_DAYS, 'choices' => [ 7 => sprintf(__('%d days'), 7), 14 => sprintf(__('%d days'), 14), 30 => sprintf(__('%d days'), 30), 60 => sprintf(__('%d days'), 60), ], ] ], 'submit' => [ 'submit', [ 'type' => 'submit', 'label' => __('Save Changes'), 'class' => 'btn btn-lg btn-primary', ] ], ], ];
<?php return [ 'method' => 'post', 'elements' => [ 'is_enabled' => [ 'radio', [ 'label' => __('Enable Automated Assignment'), 'description' => __('Allow the system to periodically automatically assign songs to playlists based on their performance. This process will run in the background, and will only run if this option is set to "Enabled" and at least one playlist is set to "Include in Automated Assignment".'), 'default' => '0', 'choices' => [ 0 => __('Disabled'), 1 => __('Enabled'), ], ] ], 'threshold_days' => [ 'radio', [ 'label' => __('Days Between Automated Assignments'), 'description' => __('Based on this setting, the system will automatically reassign songs every (this) days using data from the previous (this) days.'), 'class' => 'inline', 'default' => \AzuraCast\Sync\RadioAutomation::DEFAULT_THRESHOLD_DAYS, 'choices' => [ 7 => sprintf(__('%d days'), 7), 14 => sprintf(__('%d days'), 14), 30 => sprintf(__('%d days'), 30), 60 => sprintf(__('%d days'), 60), ], ] ], 'submit' => [ 'submit', [ 'type' => 'submit', 'label' => __('Save Changes'), 'class' => 'btn btn-lg btn-primary', ] ], ], ];
Print 16 bit per line
#!/usr/bin/env python2 """ Analyze superblock in ext2 filesystem. Usage: superblock.py <filename> """ import sys import string from binascii import hexlify BLOCKSIZE = 512 def nonprintable_replace(char): if char not in string.printable: return '.' if char in '\n\r\t\x0b\x0c': return '.' return char def block_printer(filename, offset, block_count): with open(filename, 'rb') as f: f.seek(offset * BLOCKSIZE) # Loop over blocks for i in xrange(block_count): # Loop over bytes for j in xrange(BLOCKSIZE / 16): word = f.read(4), f.read(4), f.read(4), f.read(4) hex_string = ' '.join(map(hexlify, word)) ascii_string = ''.join(map(nonprintable_replace, ''.join(word))) print '{0:2}: {1} {2}'.format(j + 1, hex_string, ascii_string) if __name__ == '__main__': if len(sys.argv) < 2: print 'Usage: superblock.py <filename>' sys.exit(1) filename = sys.argv[1] print '\nPrinting superblock (bytes 1024-1535) of file %s.\n' % filename print ' ' * 5 + 'HEX'.center(35) + ' ' + 'ASCII'.center(16) block_printer(filename, 2, 1)
#!/usr/bin/env python2 """ Analyze superblock in ext2 filesystem. Usage: superblock.py <filename> """ import sys import string from binascii import hexlify BLOCKSIZE = 512 def block_printer(filename, offset, block_count): def nonprintable_replace(char): if char not in string.printable: return '.' if char in '\n\r\t\x0b\x0c': return '.' return char with open(filename, 'rb') as f: f.seek(offset * BLOCKSIZE) # Loop over blocks for i in xrange(block_count): # Loop over bytes for j in xrange(BLOCKSIZE / 8): part1 = f.read(4) part2 = f.read(4) print '{0:2}: {1} {2} {3}'.format(j+1, hexlify(part1), hexlify(part2), ''.join(map(nonprintable_replace, part1 + part2))) if __name__ == '__main__': if len(sys.argv) < 2: print 'Usage: superblock.py <filename>' sys.exit(1) filename = sys.argv[1] print 'Printing superblock (bytes 1024-1535) of file %s.\n' % filename print ''.center(5) + 'HEX'.center(18) + 'ASCII'.center(8) block_printer(filename, 2, 1)
Fix trl controller fuer directories
<?php class Vpc_Directories_Item_Directory_Trl_Controller extends Vps_Controller_Action_Auto_Vpc_Grid { protected $_buttons = array( 'save', 'reload', ); protected $_editDialog = array( 'width' => 500, 'height' => 400 ); protected $_hasComponentId = false; //component_id nicht speichern protected $_paging = 25; public function preDispatch() { $this->setModel(new Vpc_Directories_Item_Directory_Trl_AdminModel(array( 'proxyModel' => Vpc_Abstract::createChildModel( Vpc_Abstract::getSetting($this->_getParam('class'), 'masterComponentClass') ), 'trlModel' => Vpc_Abstract::createChildModel($this->_getParam('class')), ))); parent::preDispatch(); $url = Vpc_Admin::getInstance($this->_getParam('class'))->getControllerUrl('Form'); $this->_editDialog['controllerUrl'] = $url; } protected function _initColumns() { parent::_initColumns(); $this->_columns->add(new Vps_Grid_Column('id')); } protected function _getSelect() { $ret = parent::_getSelect(); $ret->whereEquals('component_id', $this->_getParam('componentId')); return $ret; } protected function _getRowById($id) { if (!$id) return null; $s = new Vps_Model_Select(); $s->whereEquals($this->_model->getPrimaryKey(), $id); $s->whereEquals('component_id', $this->_getParam('componentId')); return $this->_model->getRow($s); } }
<?php class Vpc_Directories_Item_Directory_Trl_Controller extends Vps_Controller_Action_Auto_Vpc_Grid { protected $_buttons = array( 'save', 'reload', ); protected $_editDialog = array( 'width' => 500, 'height' => 400 ); protected $_paging = 25; public function preDispatch() { $this->setModel(new Vpc_Directories_Item_Directory_Trl_AdminModel(array( 'proxyModel' => Vpc_Abstract::createChildModel( Vpc_Abstract::getSetting($this->_getParam('class'), 'masterComponentClass') ), 'trlModel' => Vpc_Abstract::createChildModel($this->_getParam('class')), ))); parent::preDispatch(); $url = Vpc_Admin::getInstance($this->_getParam('class'))->getControllerUrl('Form'); $this->_editDialog['controllerUrl'] = $url; } protected function _initColumns() { parent::_initColumns(); $this->_columns->add(new Vps_Grid_Column('id')); } protected function _getRowById($id) { if (!$id) return null; $s = new Vps_Model_Select(); $s->whereEquals($this->_model->getPrimaryKey(), $id); $s->whereEquals('component_id', $this->_getParam('componentId')); return $this->_model->getRow($s); } }
Handle the case where there is no search object in the store
import { SET_BODY } from '../actions/Search' import { RESULT_CLICKED } from '../actions/Analytics' import { SEARCH_REQUEST_SUCCESS } from '../../api/actions/query' let data = { analyticsEnabled: false, body: '' } const events = (analytics) => { window.addEventListener('beforeunload', () => { if (data.analyticsEnabled && data.body) { analytics.onPageClose(data.body) } }) return ({ getState }) => (next) => (action) => { if (action.type === SEARCH_REQUEST_SUCCESS) { data = { ...data, analyticsEnabled: true, body: (getState().search || {}).body, } } if (action.type === SET_BODY) { const previousBody = getState().search.body || '' const newBody = action.body if (previousBody.length >= 2 && newBody.length < 2) { if (data.analyticsEnabled && data.body) { analytics.onBodyReset(previousBody) } data = { ...data, body: '' } } } if (action.type === RESULT_CLICKED) { if (data.analyticsEnabled && data.body) { analytics.onResultClicked(getState().search.body) } data = { ...data, body: '' } } // Call the next dispatch method in the middleware chain. const returnValue = next(action) // This will likely be the action itself, unless // a middleware further in chain changed it. return returnValue } } export default events
import { SET_BODY } from '../actions/Search' import { RESULT_CLICKED } from '../actions/Analytics' import { SEARCH_REQUEST_SUCCESS } from '../../api/actions/query' let data = { analyticsEnabled: false, body: '' } const events = (analytics) => { window.addEventListener('beforeunload', () => { if (data.analyticsEnabled && data.body) { analytics.onPageClose(data.body) } }) return ({ getState }) => (next) => (action) => { if (action.type === SEARCH_REQUEST_SUCCESS) { data = { ...data, analyticsEnabled: true, body: getState().search.body, } } if (action.type === SET_BODY) { const previousBody = getState().search.body || '' const newBody = action.body if (previousBody.length >= 2 && newBody.length < 2) { if (data.analyticsEnabled && data.body) { analytics.onBodyReset(previousBody) } data = { ...data, body: '' } } } if (action.type === RESULT_CLICKED) { if (data.analyticsEnabled && data.body) { analytics.onResultClicked(getState().search.body) } data = { ...data, body: '' } } // Call the next dispatch method in the middleware chain. const returnValue = next(action) // This will likely be the action itself, unless // a middleware further in chain changed it. return returnValue } } export default events
Remove render of header and footer on dashboard
import React, { Component } from 'react' import {BrowserRouter as Router, Route, Link} from 'react-router-dom' import Auth from './Auth' import Dashboard from './Dashboard' import Data from './Data' import Home from './Home' import LanguageBar from './shared/LanguageBar' import Footer from './shared/Footer' import Styles from './Styles' import Transfer from './Transfer' export default class App extends Component { render (){ return ( <Router> <Styles> <Data> {(props) => ( <div> <Route exact path="/dashboard" component={Dashboard}/> <Route exact path="(/|/transfer.*)" render={() => ( <div> <LanguageBar>English</LanguageBar> <Auth user={props.user}> <div> <Route exact path="/" render={() => ( <Home {...props}/> )}/> <Route exact path="/transfer/:amount/to/:to" render={(routeProps) => ( <Transfer {...routeProps} {...props}/> )}/> </div> </Auth> <Footer/> </div> )}/> </div> )} </Data> </Styles> </Router> ) } }
import React, { Component } from 'react' import {BrowserRouter as Router, Route, Link} from 'react-router-dom' import Auth from './Auth' import Dashboard from './Dashboard' import Data from './Data' import Home from './Home' import LanguageBar from './shared/LanguageBar' import Footer from './shared/Footer' import Styles from './Styles' import Transfer from './Transfer' export default class App extends Component { render (){ return ( <Router> <Styles> <Data> {(props) => ( <div> <LanguageBar>English</LanguageBar> <Auth user={props.user}> <div> <Route exact path="/" render={() => ( <Home {...props}/> )}/> <Route exact path="/transfer/:amount/to/:to" render={(routeProps) => ( <Transfer {...routeProps} {...props}/> )}/> <Route exact path="/dashboard" component={Dashboard}/> </div> </Auth> <Footer/> </div> )} </Data> </Styles> </Router> ) } }
Fix time calculation for TryLater in PeriodicTasks
from ..vtask import VTask, TryLater import time from ..sparts import option, counter, samples, SampleType from threading import Event class PeriodicTask(VTask): INTERVAL = None execute_duration = samples(windows=[60, 240], types=[SampleType.AVG, SampleType.MAX, SampleType.MIN]) n_iterations = counter() n_slow_iterations = counter() n_try_later = counter() interval = option(type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): t0 = time.time() while not self.service._stop: try: self.execute() except TryLater: self.n_try_later.increment() continue self.n_iterations.increment() self.execute_duration.add(time.time() - t0) to_sleep = (t0 + self.interval) - time.time() if to_sleep > 0: if self.stop_event.wait(to_sleep): return else: self.n_slow_iterations.increment() t0 = time.time() def execute(self, context=None): self.logger.debug('execute')
from ..vtask import VTask, TryLater import time from ..sparts import option, counter, samples, SampleType from threading import Event class PeriodicTask(VTask): INTERVAL = None execute_duration = samples(windows=[60, 240], types=[SampleType.AVG, SampleType.MAX, SampleType.MIN]) n_iterations = counter() n_slow_iterations = counter() n_try_later = counter() interval = option(type=float, metavar='SECONDS', default=lambda cls: cls.INTERVAL, help='How often this task should run [%(default)s] (s)') def initTask(self): super(PeriodicTask, self).initTask() assert self.getTaskOption('interval') is not None self.stop_event = Event() def stop(self): self.stop_event.set() super(PeriodicTask, self).stop() def _runloop(self): while not self.service._stop: t0 = time.time() try: self.execute() except TryLater: self.n_try_later.increment() continue self.n_iterations.increment() self.execute_duration.add(time.time() - t0) to_sleep = (t0 + self.interval) - time.time() if to_sleep > 0: if self.stop_event.wait(to_sleep): return else: self.n_slow_iterations.increment() def execute(self, context=None): self.logger.debug('execute')
Allow custon io loops for ConnectionPools
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit=limit) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
Mark dirty on placement too
package refinedstorage.apiimpl.network; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import refinedstorage.api.network.INetworkMaster; import java.util.HashMap; import java.util.Map; public class NetworkMasterRegistry { public static final Map<Integer, Map<BlockPos, INetworkMaster>> NETWORKS = new HashMap<Integer, Map<BlockPos, INetworkMaster>>(); public static void add(World world, INetworkMaster network) { add(world.provider.getDimension(), network); NetworkMasterSavedData.getOrLoad(world).markDirty(); } public static void add(int dim, INetworkMaster network) { if (NETWORKS.get(dim) == null) { NETWORKS.put(dim, new HashMap<BlockPos, INetworkMaster>()); } NETWORKS.get(dim).put(network.getPosition(), network); } public static void remove(World world, BlockPos pos) { if (get(world) != null) { INetworkMaster network = get(world).get(pos); if (network != null) { get(world).remove(pos); NetworkMasterSavedData.getOrLoad(world).markDirty(); } } } public static INetworkMaster get(World world, BlockPos pos) { return get(world) == null ? null : get(world).get(pos); } public static Map<BlockPos, INetworkMaster> get(World world) { return NETWORKS.get(world.provider.getDimension()); } public static void clear() { NETWORKS.clear(); } }
package refinedstorage.apiimpl.network; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import refinedstorage.api.network.INetworkMaster; import java.util.HashMap; import java.util.Map; public class NetworkMasterRegistry { public static final Map<Integer, Map<BlockPos, INetworkMaster>> NETWORKS = new HashMap<Integer, Map<BlockPos, INetworkMaster>>(); public static void add(World world, INetworkMaster network) { add(world.provider.getDimension(), network); } public static void add(int dim, INetworkMaster network) { if (NETWORKS.get(dim) == null) { NETWORKS.put(dim, new HashMap<BlockPos, INetworkMaster>()); } NETWORKS.get(dim).put(network.getPosition(), network); } public static void remove(World world, BlockPos pos) { if (get(world) != null) { INetworkMaster network = get(world).get(pos); if (network != null) { get(world).remove(pos); NetworkMasterSavedData.getOrLoad(world).markDirty(); } } } public static INetworkMaster get(World world, BlockPos pos) { return get(world) == null ? null : get(world).get(pos); } public static Map<BlockPos, INetworkMaster> get(World world) { return NETWORKS.get(world.provider.getDimension()); } public static void clear() { NETWORKS.clear(); } }
Add yellow color for services
#coding=utf-8 from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green, yellow from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): print(yellow(service) + ": " + green("start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: print(red(service + ": fail...")) continue print(yellow(service) + ": " + green("end..."))
#coding=utf-8 from __future__ import absolute_import from fabric.api import local, run, sudo, task from fabric.contrib.console import confirm from fabric.state import env from fabric.context_managers import cd, lcd, hide, settings from fabric.colors import red, green from .utils import repl_root from .project import rsync_project @task(alias='p', default=True) def publish(): '''Publish your app''' rsync() restart() @task(alias='rs') def rsync(): '''Rsync your local dir to remote''' rsync_project(env.rsync['rpath'], repl_root(env.rsync['lpath']), sshpass=True) @task(alias='rt') def restart(): '''Restart your services''' for service, need_ops in env.services.iteritems(): print(green(service + "start...")) try: rsync_project(need_ops['rpath'], need_ops['lpath'], sshpass=True) if need_ops['sudo']: sudo(need_ops['command'], pty=False, user=need_ops['user'] if need_ops['user'] else env.user) else: run(need_ops['command']) except: print(red(service + "fail...")) continue print(green(service + "end..."))
Add __bool__ redirect to buttondebounce
import wpilib class ButtonDebouncer: '''Useful utility class for debouncing buttons''' def __init__(self, joystick, buttonnum, period=0.5): ''' :param joystick: Joystick object :type joystick: :class:`wpilib.Joystick` :param buttonnum: Number of button to retrieve :type buttonnum: int :param period: Period of time (in seconds) to wait before allowing new button presses. Defaults to 0.5 seconds. :type period: float ''' self.joystick = joystick self.buttonnum = buttonnum self.latest = 0 self.debounce_period = float(period) self.timer = wpilib.Timer def set_debounce_period(self, period): '''Set number of seconds to wait before returning True for the button again''' self.debounce_period = float(period) def get(self): '''Returns the value of the joystick button. If the button is held down, then True will only be returned once every ``debounce_period`` seconds''' now = self.timer.getFPGATimestamp() if self.joystick.getRawButton(self.buttonnum): if (now-self.latest) > self.debounce_period: self.latest = now return True return False __bool__ = get
import wpilib class ButtonDebouncer: '''Useful utility class for debouncing buttons''' def __init__(self, joystick, buttonnum, period=0.5): ''' :param joystick: Joystick object :type joystick: :class:`wpilib.Joystick` :param buttonnum: Number of button to retrieve :type buttonnum: int :param period: Period of time (in seconds) to wait before allowing new button presses. Defaults to 0.5 seconds. :type period: float ''' self.joystick = joystick self.buttonnum = buttonnum self.latest = 0 self.debounce_period = float(period) self.timer = wpilib.Timer def set_debounce_period(self, period): '''Set number of seconds to wait before returning True for the button again''' self.debounce_period = float(period) def get(self): '''Returns the value of the joystick button. If the button is held down, then True will only be returned once every ``debounce_period`` seconds''' now = self.timer.getFPGATimestamp() if self.joystick.getRawButton(self.buttonnum): if (now-self.latest) > self.debounce_period: self.latest = now return True return False
Add `getMailers` to get all of the created swift mailer instances
<?php namespace KVZ\Laravel\SwitchableMail; use Illuminate\Mail\TransportManager; use Illuminate\Support\Manager; use Swift_Mailer; class SwiftMailerManager extends Manager { /** * The mail transport manager. * * @var \Illuminate\Mail\TransportManager */ protected $transportManager; /** * Get the mail transport manager. * * @return \Illuminate\Mail\TransportManager */ public function getTransportManager() { return $this->transportManager; } /** * Set the mail transport manager. * * @param \Illuminate\Mail\TransportManager $manager * @return $this */ public function setTransportManager(TransportManager $manager) { $this->transportManager = $manager; return $this; } /** * Get a swift mailer instance. * * @param string|null $driver * @return \Swift_Mailer */ public function mailer($driver = null) { return $this->driver($driver); } /** * Get all of the created swift mailer instances. * * @return array */ public function getMailers() { return $this->drivers; } /** * Create a new swift mailer instance. * * @param string $driver * @return \Swift_Mailer */ protected function createDriver($driver) { return new Swift_Mailer($this->transportManager->driver($driver)); } /** * Get the default mail driver name. * * @return string */ public function getDefaultDriver() { return $this->transportManager->getDefaultDriver(); } }
<?php namespace KVZ\Laravel\SwitchableMail; use Illuminate\Mail\TransportManager; use Illuminate\Support\Manager; use Swift_Mailer; class SwiftMailerManager extends Manager { /** * The mail transport manager. * * @var \Illuminate\Mail\TransportManager */ protected $transportManager; /** * Get the mail transport manager. * * @return \Illuminate\Mail\TransportManager */ public function getTransportManager() { return $this->transportManager; } /** * Set the mail transport manager. * * @param \Illuminate\Mail\TransportManager $manager * @return $this */ public function setTransportManager(TransportManager $manager) { $this->transportManager = $manager; return $this; } /** * Get a swift mailer instance. * * @param string|null $driver * @return \Swift_Mailer */ public function mailer($driver = null) { return $this->driver($driver); } /** * Create a new swift mailer instance. * * @param string $driver * @return \Swift_Mailer */ protected function createDriver($driver) { return new Swift_Mailer($this->transportManager->driver($driver)); } /** * Get the default mail driver name. * * @return string */ public function getDefaultDriver() { return $this->transportManager->getDefaultDriver(); } }
Increase timeout to 10 hours (temporarily). The job is expected to take 3-4 hours, but was intermittently timing out at 6 hours. Increase to 10 hours while profiling and debugging the job.
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': '[email protected]', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['[email protected]', '[email protected]'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 2, 'retry_delay': timedelta(minutes=30), } dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily') # Make sure all the data for the given day has arrived before running. t0 = BashOperator(task_id="delayed_start", bash_command="sleep 1800", dag=dag) t1 = EMRSparkOperator(task_id="main_summary", job_name="Main Summary View", execution_timeout=timedelta(hours=10), instance_count=10, env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.airflow_bucket }}"}, uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh", dag=dag) # Wait a little while after midnight to start for a given day. t1.set_upstream(t0)
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': '[email protected]', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['[email protected]', '[email protected]'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 2, 'retry_delay': timedelta(minutes=30), } dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily') # Make sure all the data for the given day has arrived before running. t0 = BashOperator(task_id="delayed_start", bash_command="sleep 1800", dag=dag) t1 = EMRSparkOperator(task_id="main_summary", job_name="Main Summary View", execution_timeout=timedelta(hours=6), instance_count=10, env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.airflow_bucket }}"}, uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh", dag=dag) # Wait a little while after midnight to start for a given day. t1.set_upstream(t0)
Add some braces around an if guard
package com.yammer.tenacity.core.properties; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicConfiguration; import com.netflix.config.FixedDelayPollingScheduler; import com.netflix.config.PolledConfigurationSource; import com.netflix.config.sources.URLConfigurationSource; import com.yammer.tenacity.core.config.BreakerboxConfiguration; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ArchaiusPropertyRegister { private static class TenacityPollingScheduler extends FixedDelayPollingScheduler { private static final Logger LOGGER = LoggerFactory.getLogger(TenacityPollingScheduler.class); public TenacityPollingScheduler(int initialDelayMillis, int delayMillis, boolean ignoreDeletesFromSource) { super(initialDelayMillis, delayMillis, ignoreDeletesFromSource); } @Override protected synchronized void initialLoad(PolledConfigurationSource source, Configuration config) { try { super.initialLoad(source, config); } catch (Exception err) { LOGGER.warn("Initial dynamic configuration load failed", err); } } } public void register(BreakerboxConfiguration breakerboxConfiguration) { if (breakerboxConfiguration.getUrls().isEmpty()) { return; } ConfigurationManager.install( new DynamicConfiguration( new URLConfigurationSource(breakerboxConfiguration.getUrls().split(",")), new TenacityPollingScheduler( (int)breakerboxConfiguration.getInitialDelay().toMilliseconds(), (int)breakerboxConfiguration.getDelay().toMilliseconds(), true))); } }
package com.yammer.tenacity.core.properties; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicConfiguration; import com.netflix.config.FixedDelayPollingScheduler; import com.netflix.config.PolledConfigurationSource; import com.netflix.config.sources.URLConfigurationSource; import com.yammer.tenacity.core.config.BreakerboxConfiguration; import org.apache.commons.configuration.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ArchaiusPropertyRegister { private static class TenacityPollingScheduler extends FixedDelayPollingScheduler { private static final Logger LOGGER = LoggerFactory.getLogger(TenacityPollingScheduler.class); public TenacityPollingScheduler(int initialDelayMillis, int delayMillis, boolean ignoreDeletesFromSource) { super(initialDelayMillis, delayMillis, ignoreDeletesFromSource); } @Override protected synchronized void initialLoad(PolledConfigurationSource source, Configuration config) { try { super.initialLoad(source, config); } catch (Exception err) { LOGGER.warn("Initial dynamic configuration load failed", err); } } } public void register(BreakerboxConfiguration breakerboxConfiguration) { if(breakerboxConfiguration.getUrls().isEmpty()) return; ConfigurationManager.install( new DynamicConfiguration( new URLConfigurationSource(breakerboxConfiguration.getUrls().split(",")), new TenacityPollingScheduler( (int)breakerboxConfiguration.getInitialDelay().toMilliseconds(), (int)breakerboxConfiguration.getDelay().toMilliseconds(), true))); } }
Add a test for RelativeTimer send() to make sure it sends metrics
<?php namespace Test\Statsd\Client; use Statsd\Client\RelativeTimer; use Statsd\Client; class RelativeTimerTest extends \PHPUnit_Framework_TestCase { public function testGetters() { $client = new Client(); $timer = new RelativeTimer($client, 1500); $this->assertSame($client, $timer->getClient()); $this->assertEquals(1500, $timer->getReferenceTimestamp()); } public function testDefaultReferenceIsNow() { $testStart = microtime(true); $timer = new RelativeTimer(new Client()); $this->assertGreaterThanOrEqual($testStart, $timer->getReferenceTimestamp()); } public function testSendDurationSinceReference() { $self = $this; $sockMock = $this->mockConnection(); $sockMock->expects($this->once())->method('send') ->with( $this->matchesRegularExpression('/^foo\.bar\:\d{1,2}\|ms/') ); $client = new Client(array('connection' => $sockMock)); $timer = new RelativeTimer($client); $timer->send('foo.bar'); } public function testSendReturnsTimerSelfReferenceForFluentApi() { $timer = new RelativeTimer($this->createClientWithMockedSocket()); $this->assertSame($timer, $timer->send('foo.bar')); } private function createClientWithMockedSocket() { return new Client(array('connection' => $this->mockConnection())); } private function mockConnection() { return $this->getMock( '\Statsd\Client\SocketConnection', array( 'send' ), array( array( 'throw_exception' => false, 'host' => 'foo.bar', ) ) ); } }
<?php namespace Test\Statsd\Client; use Statsd\Client\RelativeTimer; use Statsd\Client; class RelativeTimerTest extends \PHPUnit_Framework_TestCase { public function testGetters() { $client = new Client(); $timer = new RelativeTimer($client, 1500); $this->assertSame($client, $timer->getClient()); $this->assertEquals(1500, $timer->getReferenceTimestamp()); } public function testDefaultReferenceIsNow() { $testStart = microtime(true); $timer = new RelativeTimer(new Client()); $this->assertGreaterThanOrEqual($testStart, $timer->getReferenceTimestamp()); } public function testSendReturnsTimerSelfReferenceForFluentApi() { $timer = new RelativeTimer($this->createClientWithMockedSocket()); $this->assertSame($timer, $timer->send('foo.bar')); } private function createClientWithMockedSocket() { return new Client(array('connection' => $this->mockConnection())); } private function mockConnection() { return $this->getMock( '\Statsd\Client\SocketConnection', array( 'send' ), array( array( 'throw_exception' => false, 'host' => 'foo.bar', ) ) ); } }
Add routing to 404 component
import React from 'react'; import { BrowserRouter, Match, Miss } from 'react-router' import Header from './components/Header'; import CTA from './components/CTA'; import Footer from './components/Footer'; import routes from './config/routes'; import FourOhFour from './components/404'; const App = () => ( // <BrowserRouter history={history}> <BrowserRouter> <div> <Header /> { routes.map((route, index) => ( // rendering `Match`s with different // components but the same pattern as before <Match // FIXME: index as key key={index} pattern={route.pattern} // component={route.main} render={matchProps => { const Component = route.main; // TODO: double check where to put scrolling window.scroll(0, 0); return ( <div className="content"> <Component {...matchProps} /> <CTA matchProps={matchProps} /> </div> ); }} exactly={route.exactly} /> )) } <Miss component={FourOhFour} /> <Footer /> </div> </BrowserRouter> ); export default App;
import React from 'react'; import { BrowserRouter, Match } from 'react-router' import Header from './components/Header'; import CTA from './components/CTA'; import Footer from './components/Footer'; import routes from './config/routes'; const App = () => ( // <BrowserRouter history={history}> <BrowserRouter> <div> <Header /> { routes.map((route, index) => ( // rendering `Match`s with different // components but the same pattern as before <Match // FIXME: index as key key={index} pattern={route.pattern} // component={route.main} render={matchProps => { const Component = route.main; return ( <div className="content"> <Component {...matchProps} /> <CTA matchProps={matchProps} /> </div> ); }} exactly={route.exactly} /> )) } <Footer /> </div> </BrowserRouter> ); export default App;
Call `cb` immediately if `pending` is zero
'use strict'; var tape = require('tape'); var through = require('through2'); var PluginError = require('gulp-util').PluginError; var requireUncached = require('require-uncached'); var PLUGIN_NAME = 'gulp-tape'; var gulpTape = function(opts) { opts = opts || {}; var outputStream = opts.outputStream || process.stdout; var reporter = opts.reporter || through.obj(); var files = []; var transform = function(file, encoding, cb) { if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming is not supported')); } files.push(file.path); cb(null, file); }; var flush = function(cb) { try { tape.createStream().pipe(reporter).pipe(outputStream); files.forEach(function(file) { requireUncached(file); }); var tests = tape.getHarness()._tests; var pending = tests.length; if (pending === 0) { return cb(); } tests.forEach(function(test) { test.once('end', function() { if (--pending === 0) { cb(); } }); }); } catch (err) { cb(new PluginError(PLUGIN_NAME, err)); } }; return through.obj(transform, flush); }; module.exports = gulpTape;
'use strict'; var tape = require('tape'); var through = require('through2'); var PluginError = require('gulp-util').PluginError; var requireUncached = require('require-uncached'); var PLUGIN_NAME = 'gulp-tape'; var gulpTape = function(opts) { opts = opts || {}; var outputStream = opts.outputStream || process.stdout; var reporter = opts.reporter || through.obj(); var files = []; var transform = function(file, encoding, cb) { if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming is not supported')); } files.push(file.path); cb(null, file); }; var flush = function(cb) { try { tape.createStream().pipe(reporter).pipe(outputStream); files.forEach(function(file) { requireUncached(file); }); var tests = tape.getHarness()._tests; var pending = tests.length; tests.forEach(function(test) { test.once('end', function() { if (--pending === 0) { cb(); } }); }); } catch (err) { cb(new PluginError(PLUGIN_NAME, err)); } }; return through.obj(transform, flush); }; module.exports = gulpTape;
Remove helper dependency in observer class
<?php /** * MinTotalQty observer model * * @category Jvs * @package Jvs_MinTotalQty * @author Javier Villanueva <[email protected]> */ class Jvs_MinTotalQty_Model_Observer { /** * Check minimun order totals * * @param Varien_Event_Observer $observer * @return void */ public function checkTotalQtyBeforeCheckout(Varien_Event_Observer $observer) { $quote = $observer->getDataObject(); $customer = Mage::helper('customer')->getCustomer(); // If the minimun total quantity is not met // redirect to cart page with error message if ($minQty = Mage::helper('jvs_mintotalqty')->minimunOrderQty($quote, $customer)) { Mage::getSingleton('checkout/session')->addUniqueMessages( Mage::getSingleton('core/message') ->error( Mage::helper('cataloginventory') ->__( 'The minimum quantity allowed for purchase is %s.', $minQty ) ) ); // Check if we are not already on the cart page if (!Mage::helper('jvs_mintotalqty')->isCartPage()) { Mage::app()->getFrontController()->getResponse() ->setRedirect(Mage::getUrl('checkout/cart')); Mage::app()->getRequest()->setDispatched(true); } } } }
<?php /** * MinTotalQty observer model * * @category Jvs * @package Jvs_MinTotalQty * @author Javier Villanueva <[email protected]> */ class Jvs_MinTotalQty_Model_Observer extends Mage_CatalogInventory_Helper_Minsaleqty { /** * Check minimun order totals * * @param Varien_Event_Observer $observer * @return void */ public function checkTotalQtyBeforeCheckout(Varien_Event_Observer $observer) { $quote = $observer->getDataObject(); $customer = Mage::helper('customer')->getCustomer(); // If the minimun total quantity is not met // redirect to cart page with error message if ($minQty = Mage::helper('jvs_mintotalqty')->minimunOrderQty($quote, $customer)) { Mage::getSingleton('checkout/session')->addUniqueMessages( Mage::getSingleton('core/message') ->error( Mage::helper('cataloginventory') ->__( 'The minimum quantity allowed for purchase is %s.', $minQty ) ) ); // Check if we are not already on the cart page if (!Mage::helper('jvs_mintotalqty')->isCartPage()) { Mage::app()->getFrontController()->getResponse() ->setRedirect(Mage::getUrl('checkout/cart')); Mage::app()->getRequest()->setDispatched(true); } } } }
Fix bug in call to get default swimlane
Meteor.methods({ moveSwimlane(swimlaneId, toBoardId) { check(swimlaneId, String); check(toBoardId, String); const swimlane = Swimlanes.findOne(swimlaneId); const fromBoard = Boards.findOne(swimlane.boardId); const toBoard = Boards.findOne(toBoardId); if (swimlane && toBoard) { swimlane.lists().forEach(list => { const toList = Lists.findOne({ boardId: toBoardId, title: list.title, archived: false, }); let toListId; if (toList) { toListId = toList._id; } else { toListId = Lists.insert({ title: list.title, boardId: toBoardId, type: list.type, archived: false, wipLimit: list.wipLimit, }); } Cards.find({ listId: list._id, swimlaneId, }).forEach(card => { card.move(toBoardId, swimlaneId, toListId); }); }); Swimlanes.update(swimlaneId, { $set: { boardId: toBoardId, }, }); // make sure there is a default swimlane fromBoard.getDefaultSwimline(); return true; } return false; }, });
Meteor.methods({ moveSwimlane(swimlaneId, toBoardId) { check(swimlaneId, String); check(toBoardId, String); const swimlane = Swimlanes.findOne(swimlaneId); const board = Boards.findOne(toBoardId); if (swimlane && board) { swimlane.lists().forEach(list => { const boardList = Lists.findOne({ boardId: toBoardId, title: list.title, archived: false, }); let toListId; if (boardList) { toListId = boardList._id; } else { toListId = Lists.insert({ title: list.title, boardId: toBoardId, type: list.type, archived: false, wipLimit: list.wipLimit, }); } Cards.find({ listId: list._id, swimlaneId, }).forEach(card => { card.move(toBoardId, swimlaneId, toListId); }); }); Swimlanes.update(swimlaneId, { $set: { boardId: toBoardId, }, }); // make sure there is a default swimlane this.board().getDefaultSwimline(); return true; } return false; }, });
Fix default empty configuration acceptance tests.
<?php use Centreon\Test\Behat\CentreonContext; /** * Defines application features from the specific context. */ class EmptyDefaultConfigurationContext extends CentreonContext { /** * @When I list the :arg1 */ public function iListThe($arg1) { switch ($arg1) { case 'host template': $p = '/main.php?p=60103'; break; case 'service template': $p = '/main.php?p=60206'; break; case 'command': $p = '/main.php?p=60801&type=2'; break; default: throw new Exception('Page not know'); break; } $this->visit($p); } /** * @Then no item is display */ public function noItemIsDisplay() { $table = $this->assertFind('css', 'table.ListTable'); $list = $table->findAll('css', 'tr'); if (count($list) != 1) { throw new Exception('Some items are presents.'); } } }
<?php use Centreon\Test\Behat\CentreonContext; /** * Defines application features from the specific context. */ class EmptyDefaultConfigurationContext extends CentreonContext { /** * @When I list the :arg1 */ public function iListThe($arg1) { switch ($arg1) { case 'host template': $p = '/main.php?p=60103'; break; case 'service template': $p = '/main.php?p=60106'; break; case 'command': $p = 'main.php?p=60801&type=2'; break; default: throw new Exception('Page not know'); break; } $this->visit($p); } /** * @Then no item is display */ public function noItemIsDisplay() { $table = $this->assertFind('css', 'table.ListTable'); $list = $table->findAll('css', 'tr'); if (count($list) != 1) { throw new Exception('Some items are presents.'); } } }
Replace string substitution with string formatting
# -*- coding: utf-8 -*- ''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = ''' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> '''.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write('Supported programs: {0!r}\n'.format(supported_programs)) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
# -*- coding: utf-8 -*- ''' Manage launchd plist files ''' # Import python libs import os import sys def write_launchd_plist(program): ''' Write a launchd plist for managing salt-master or salt-minion CLI Example: .. code-block:: bash salt-run launchd.write_launchd_plist salt-master ''' plist_sample_text = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>org.saltstack.{program}</string> <key>ProgramArguments</key> <array> <string>{python}</string> <string>{script}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> """.strip() supported_programs = ['salt-master', 'salt-minion'] if program not in supported_programs: sys.stderr.write("Supported programs: %r\n" % supported_programs) sys.exit(-1) sys.stdout.write( plist_sample_text.format( program=program, python=sys.executable, script=os.path.join(os.path.dirname(sys.executable), program) ) )
Fix Apollo Client subscription test
/* eslint-disable prefer-arrow-callback, func-names */ /* eslint-env mocha */ import chai from 'chai'; import gql from 'graphql-tag'; import { Promise } from 'meteor/promise'; import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { getDDPLink } from '../../lib/client/apollo-link-ddp'; import { FOO_CHANGED_TOPIC } from '../data/resolvers'; describe('ApolloClient with DDP link', function () { beforeEach(function () { // The ApolloClient won't recognize Promise in package tests unless exported like this global.Promise = Promise; this.client = new ApolloClient({ link: getDDPLink(), cache: new InMemoryCache(), }); }); describe('#query', function () { it('returns query data', async function () { const { data } = await this.client.query({ query: gql`query { foo }` }); chai.expect(data.foo).to.be.a('string'); }); it('returns subscription data', function (done) { const message = { fooSub: 'bar' }; const observer = this.client.subscribe({ query: gql`subscription { fooSub }` }); const subscription = observer.subscribe({ next: ({ data }) => { try { chai.expect(data).to.deep.equal(message); subscription.unsubscribe(); done(); } catch (e) { done(e); } }, }); Meteor.call('ddp-apollo/publish', FOO_CHANGED_TOPIC, message); }); }); });
/* eslint-disable prefer-arrow-callback, func-names */ /* eslint-env mocha */ import chai from 'chai'; import gql from 'graphql-tag'; import { Promise } from 'meteor/promise'; import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { getDDPLink } from '../../lib/client/apollo-link-ddp'; import { FOO_CHANGED_TOPIC } from '../data/resolvers'; describe('ApolloClient with DDP link', function () { beforeEach(function () { // The ApolloClient won't recognize Promise in package tests unless exported like this global.Promise = Promise; this.client = new ApolloClient({ link: getDDPLink(), cache: new InMemoryCache(), }); }); describe('#query', function () { it('returns query data', async function () { const { data } = await this.client.query({ query: gql`query { foo }` }); chai.expect(data.foo).to.be.a('string'); }); it('returns subscription data', function (done) { const message = { fooSub: 'bar' }; const observer = this.client.subscribe({ query: gql`subscription { fooSub }` }); const subscription = observer.subscribe({ next: (data) => { try { chai.expect(data).to.deep.equal(message); subscription.unsubscribe(); done(); } catch (e) { done(e); } }, }); Meteor.call('ddp-apollo/publish', FOO_CHANGED_TOPIC, message); }); }); });
Add name when creating Target
import django import os import yaml from backend.settings import BASE_DIR from django.db import IntegrityError os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django.setup() from breach.models import Target def create_target(target): t = Target( name=target['name'], endpoint=target['endpoint'], prefix=target['prefix'], alphabet=target['alphabet'], secretlength=target['secretlength'], alignmentalphabet=target['alignmentalphabet'], recordscardinality=target['recordscardinality'] ) t.save() print '''Created Target: \tname: {} \tendpoint: {} \tprefix: {} \talphabet: {} \tsecretlength: {} \talignmentalphabet: {} \trecordscardinality'''.format( t.name, t.endpoint, t.prefix, t.alphabet, t.secretlength, t.alignmentalphabet, t.recordscardinality ) if __name__ == '__main__': try: with open(os.path.join(BASE_DIR, 'target_config.yml'), 'r') as ymlconf: cfg = yaml.load(ymlconf) except IOError, err: print 'IOError: %s' % err exit(1) targets = cfg.items() for t in targets: target = t[1] target['name'] = t[0] try: create_target(target) except (IntegrityError, ValueError), err: if isinstance(err, IntegrityError): print '[!] Target "{}" already exists.'.format(target['name']) elif isinstance(err, ValueError): print '[!] Invalid parameters for target "{}".'.format(target['name'])
import django import os import yaml from backend.settings import BASE_DIR os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') django.setup() from breach.models import Target def create_target(target): t = Target( endpoint=target['endpoint'], prefix=target['prefix'], alphabet=target['alphabet'], secretlength=target['secretlength'], alignmentalphabet=target['alignmentalphabet'], recordscardinality=target['recordscardinality'] ) t.save() print '''Created Target: \tendpoint: {} \tprefix: {} \talphabet: {} \tsecretlength: {} \talignmentalphabet: {} \trecordscardinality'''.format( t.endpoint, t.prefix, t.alphabet, t.secretlength, t.alignmentalphabet, t.recordscardinality ) if __name__ == '__main__': try: with open(os.path.join(BASE_DIR, 'target_config.yml'), 'r') as ymlconf: cfg = yaml.load(ymlconf) except IOError, err: print 'IOError: %s' % err exit(1) targets = cfg.values() for target in targets: create_target(target)
Put file created by the gtts on tmp folder
import time import os from tempfile import NamedTemporaryFile from sys import platform as _platform from gtts import gTTS from pygame import mixer from .playsound import playsound from ..components import _BaseComponent class TextToSpeech(_BaseComponent): def __init__(self, queues): super().__init__(queues) self.queue_tts = None def setup(self): self.queue_tts = self._queues['QueueTextToSpeech'] def run(self): while self._is_init: sentence = self.queue_tts.get() if sentence is None: break print('To say out loud : {}'.format(sentence)) tts = gTTS(text=sentence, lang='en') if _platform == "darwin": with NamedTemporaryFile() as audio_file: tts.write_to_fp(audio_file) audio_file.seek(0) playsound(audio_file.name) else: filename = os.environ['TMP'] + str(time.time()).split('.')[0] + ".mp3" tts.save(filename) if _platform == "linux" or _platform == "linux2": mixer.init() mixer.music.load(filename) mixer.music.play() else: playsound(filename) os.remove(filename) self.queue_tts.task_done() def stop(self): print('Stopping {0}...'.format(self.__class__.__name__)) self._is_init = False self.queue_tts.put(None)
import time import os from tempfile import NamedTemporaryFile from sys import platform as _platform from gtts import gTTS from pygame import mixer from .playsound import playsound from ..components import _BaseComponent class TextToSpeech(_BaseComponent): def __init__(self, queues): super().__init__(queues) self.queue_tts = None def setup(self): self.queue_tts = self._queues['QueueTextToSpeech'] def run(self): while self._is_init: sentence = self.queue_tts.get() if sentence is None: break print('To say out loud : {}'.format(sentence)) tts = gTTS(text=sentence, lang='en') if _platform == "darwin": with NamedTemporaryFile() as audio_file: tts.write_to_fp(audio_file) audio_file.seek(0) playsound(audio_file.name) else: filename = str(time.time()).split('.')[0] + ".mp3" tts.save(filename) if _platform == "linux" or _platform == "linux2": mixer.init() mixer.music.load(filename) mixer.music.play() else: playsound(filename) os.remove(filename) self.queue_tts.task_done() def stop(self): print('Stopping {0}...'.format(self.__class__.__name__)) self._is_init = False self.queue_tts.put(None)
Maintain Java 6 compatibility for now
/* * Copyright (C) 2011 Information Management Services, Inc. */ package com.imsweb.seerapi.client.cs; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Simple Java object that contains all of the schemas relevant information. */ public class CsSchema { @JsonProperty("schema_number") protected int _schemaNumber; @JsonProperty("name") protected String _name; @JsonProperty("title") protected String _title; @JsonProperty("subtitle") protected String _subtitle; @JsonProperty("site_summary") protected String _siteSummary; @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<CsSiteSpecificFactor>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") protected String _revisionDate; public int getSchemaNumber() { return _schemaNumber; } public String getName() { return _name; } public String getTitle() { return _title; } public String getSubtitle() { return _subtitle; } public String getSiteSummary() { return _siteSummary; } public List<String> getNotes() { return _notes; } public List<CsSiteSpecificFactor> getSiteSpecificFactors() { return _siteSpecificFactors; } public int getNumTables() { return _numTables; } public String getRevisionDate() { return _revisionDate; } }
/* * Copyright (C) 2011 Information Management Services, Inc. */ package com.imsweb.seerapi.client.cs; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonProperty; /** * Simple Java object that contains all of the schemas relevant information. */ public class CsSchema { @JsonProperty("schema_number") protected int _schemaNumber; @JsonProperty("name") protected String _name; @JsonProperty("title") protected String _title; @JsonProperty("subtitle") protected String _subtitle; @JsonProperty("site_summary") protected String _siteSummary; @JsonProperty("note") protected List<String> _notes; @JsonProperty("ssf") protected List<CsSiteSpecificFactor> _siteSpecificFactors = new ArrayList<>(); @JsonProperty("num_tables") protected int _numTables; @JsonProperty("revision_date") protected String _revisionDate; public int getSchemaNumber() { return _schemaNumber; } public String getName() { return _name; } public String getTitle() { return _title; } public String getSubtitle() { return _subtitle; } public String getSiteSummary() { return _siteSummary; } public List<String> getNotes() { return _notes; } public List<CsSiteSpecificFactor> getSiteSpecificFactors() { return _siteSpecificFactors; } public int getNumTables() { return _numTables; } public String getRevisionDate() { return _revisionDate; } }
Fix problem in help plugin
const Promise = require('bluebird'); const Plugin = require('../plugin'); module.exports = Plugin.define('help', ['commands'], { defaultConfig: { 'commands': ['help'], 'parse_mode': 'markdown', 'disable_web_page_preview': true, 'disable_notification': false, }, whitelistConfig: [ 'commands', 'text', 'parse_mode', 'disable_web_page_preview', 'disable_notification' ], }, { async start (config) { const commands = new Set(config.commands || ['help']); this.on('command', async ($evt, cmd, msg) => { /* Check if the help text has been set up and the command is in the list */ if (config.commands.has(cmd.name)) { bot.logger.info('sending help message on /%s command to <#%s, %s>', cmd.name, msg.chat.id, msg.chat.full_name); $evt.stop(); return await this.sendHelp(msg.chat.id); } }); }, async sendHelp (chatId) { return await this.api.sendMessage(Object.assign(this.config, { 'commands': undefined, 'chat_id': chatId, })); }, });
const Promise = require('bluebird'); const Plugin = require('../plugin'); module.exports = Plugin.define('help', ['commands'], { defaultConfig: { 'commands': ['help'], 'parse_mode': 'markdown', 'disable_web_page_preview': true, 'disable_notification': false, }, whitelistConfig: [ 'commands', 'text', 'parse_mode', 'disable_web_page_preview', 'disable_notification' ], }, { async start (config) { const commands = new Set(this.config.commands || ['help']); this.on('command', async ($evt, cmd, msg) => { /* Check if the help text has been set up and the command is in the list */ if (config.commands.has(cmd.name)) { bot.logger.info('sending help message on /%s command to <#%s, %s>', cmd.name, msg.chat.id, msg.chat.full_name); $evt.stop(); return await this.sendHelp(msg.chat.id); } }); }, async sendHelp (chatId) { return await this.api.sendMessage(Object.assign(this.config, { 'commands': undefined, 'chat_id': chatId, })); }, });
:white_check_mark: Update completion tests, checking for printed message
import os import subprocess import sys from pathlib import Path import typer from typer.testing import CliRunner from first_steps import tutorial001 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_show_completion(): result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --show-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout def test_install_completion(): bash_completion_path: Path = Path.home() / ".bash_completion" text = "" if bash_completion_path.is_file(): text = bash_completion_path.read_text() result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --install-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) new_text = bash_completion_path.read_text() bash_completion_path.write_text(text) assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text assert "completion installed in" in result.stdout assert "Completion will take effect once you restart the terminal." in result.stdout
import os import subprocess import sys from pathlib import Path import typer from typer.testing import CliRunner from first_steps import tutorial001 as mod runner = CliRunner() app = typer.Typer() app.command()(mod.main) def test_show_completion(): result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --show-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout def test_install_completion(): bash_completion_path: Path = Path.home() / ".bash_completion" text = "" if bash_completion_path.is_file(): text = bash_completion_path.read_text() result = subprocess.run( [ "bash", "-c", f"{sys.executable} -m coverage run {mod.__file__} --install-completion", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", env={**os.environ, "SHELL": "/bin/bash"}, ) new_text = bash_completion_path.read_text() assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text bash_completion_path.write_text(text)
Remove order as the tests are independent of the order.
package com.telecomsys.cmc.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; /** * The schedule message model which encapsulates the request and response sent when the client requests details about a * scheduled message. */ @JsonRootName("schedulemessage") @JsonIgnoreProperties(ignoreUnknown = true) public class ScheduleMessage { /** * Message id of the scheduled message. */ @JsonProperty("messageID") private Long messageId; /** * Message data. */ private Message message; /** * Schedule data. */ private Schedule schedule; /** * @return the messageId */ public Long getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(Long messageId) { this.messageId = messageId; } /** * @return the schedule */ public Schedule getSchedule() { return schedule; } /** * @param schedule the schedule to set */ public void setSchedule(Schedule schedule) { this.schedule = schedule; } /** * @return the message */ public Message getMessage() { return message; } /** * @param message the message to set */ public void setMessage(Message message) { this.message = message; } }
package com.telecomsys.cmc.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonRootName; /** * The schedule message model which encapsulates the request and response sent when the client requests details about a * scheduled message. */ @JsonRootName("schedulemessage") @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder(alphabetic = true) public class ScheduleMessage { /** * Message id of the scheduled message. */ @JsonProperty("messageID") private Long messageId; /** * Message data. */ private Message message; /** * Schedule data. */ private Schedule schedule; /** * @return the messageId */ public Long getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(Long messageId) { this.messageId = messageId; } /** * @return the schedule */ public Schedule getSchedule() { return schedule; } /** * @param schedule the schedule to set */ public void setSchedule(Schedule schedule) { this.schedule = schedule; } /** * @return the message */ public Message getMessage() { return message; } /** * @param message the message to set */ public void setMessage(Message message) { this.message = message; } }
Change stream test to not require additional dependency
var fs = require('fs'); describe('Writeable Stream Input API', function () { var feedPath = __dirname + '/feeds/rss2sample.xml'; describe('.pipe()', function () { it('works', function (done) { var events = []; fs.createReadStream(feedPath).pipe(FeedParser()) .on('error', function (err) { assert.ifError(err); events.push('error'); }) .on('meta', function (meta) { assert.notEqual(meta, null); events.push('meta'); }) .on('article', function (article) { assert.notEqual(article, null); events.push('article'); }) .on('complete', function (meta, articles) { assert.notEqual(meta, null); assert.ok(articles.length); events.push('complete'); }) .on('end', function () { assert.equal(events.indexOf('error'), -1); assert.ok(~events.indexOf('meta')); assert.ok(~events.indexOf('article')); assert.ok(~events.indexOf('complete')); done(); }) .resume(); }); }); describe('.pipe()', function () { it('works', function (done) { fs.createReadStream(feedPath) .pipe(FeedParser()) .on('readable', function () { var stream = this, items = [], item; while (item = stream.read()) { items.push(item); } assert.ok(items.length); }) .on('end', done) .on('error', done); }); }); });
var fs = require('fs'); var endpoint = require('endpoint'); describe('Writeable Stream Input API', function () { var feedPath = __dirname + '/feeds/rss2sample.xml'; describe('.pipe()', function () { it('works', function (done) { var events = []; fs.createReadStream(feedPath).pipe(FeedParser()) .on('error', function (err) { assert.ifError(err); events.push('error'); }) .on('meta', function (meta) { assert.notEqual(meta, null); events.push('meta'); }) .on('article', function (article) { assert.notEqual(article, null); events.push('article'); }) .on('complete', function (meta, articles) { assert.notEqual(meta, null); assert.ok(articles.length); events.push('complete'); }) .on('end', function () { assert.equal(events.indexOf('error'), -1); assert.ok(~events.indexOf('meta')); assert.ok(~events.indexOf('article')); assert.ok(~events.indexOf('complete')); done(); }) .resume(); }); }); describe('.pipe()', function () { it('works', function (done) { fs.createReadStream(feedPath) .pipe(FeedParser()) .pipe(endpoint({objectMode: true}, function (err, articles) { assert.equal(err, null); assert.ok(articles.length); done(); })); }); }); });