text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Replace Arabic char with Persian one
package com.hosseini.persian.dt.PersianDate.enumCollections; /** * Month name and month number */ public enum Months { /* * dont worry we just use values */ Farvardin("فروردین", 1), Ordibehesht("اردیبهشت", 2), Khordad("خرداد", 3), tir("تیر", 4), Mordad("مرداد", 5), shahrivar("شهریور", 6), Mehr("مهر", 7), Aban("آبان", 8), Azar("آذر", 9), Dy("دی", 10), Bahman("بهمن", 11), Esfand("اسفند", 12); private String monthS; private int monthI; Months(String name, int index) { this.monthS = name; this.monthI = index; } /** * Getter for property 'monthAsString'. * * @return Value for property 'monthAsString'. */ public String getMonthAsString() { return monthS; } /** * Getter for property 'monthAsInt'. * * @return Value for property 'monthAsInt'. */ public int getMonthAsInt() { return monthI; } }
package com.hosseini.persian.dt.PersianDate.enumCollections; /** * Month name and month number */ public enum Months { /* * dont worry we just use values */ Farvardin("فروردین", 1), Ordibehesht("ارديبهشت", 2), Khordad("خرداد", 3), tir("تير", 4), Mordad("مرداد", 5), shahrivar("شهريور", 6), Mehr("مهر", 7), Aban("آبان", 8), Azar("آذر", 9), Dy("دي", 10), Bahman("بهمن", 11), Esfand("اسفند", 12); private String monthS; private int monthI; Months(String name, int index) { this.monthS = name; this.monthI = index; } /** * Getter for property 'monthAsString'. * * @return Value for property 'monthAsString'. */ public String getMonthAsString() { return monthS; } /** * Getter for property 'monthAsInt'. * * @return Value for property 'monthAsInt'. */ public int getMonthAsInt() { return monthI; } }
Correct cyrillic to match preferred pronunciation.
# coding: utf-8 from __future__ import unicode_literals import io import six from setuptools.command import setopt from setuptools.extern.six.moves import configparser class TestEdit: @staticmethod def parse_config(filename): parser = configparser.ConfigParser() with io.open(filename, encoding='utf-8') as reader: (parser.read_file if six.PY3 else parser.readfp)(reader) return parser @staticmethod def write_text(file, content): with io.open(file, 'wb') as strm: strm.write(content.encode('utf-8')) def test_utf8_encoding_retained(self, tmpdir): """ When editing a file, non-ASCII characters encoded in UTF-8 should be retained. """ config = tmpdir.join('setup.cfg') self.write_text(str(config), '[names]\njaraco=джарако') setopt.edit_config(str(config), dict(names=dict(other='yes'))) parser = self.parse_config(str(config)) assert parser.get('names', 'jaraco') == 'джарако' assert parser.get('names', 'other') == 'yes'
# coding: utf-8 from __future__ import unicode_literals import io import six from setuptools.command import setopt from setuptools.extern.six.moves import configparser class TestEdit: @staticmethod def parse_config(filename): parser = configparser.ConfigParser() with io.open(filename, encoding='utf-8') as reader: (parser.read_file if six.PY3 else parser.readfp)(reader) return parser @staticmethod def write_text(file, content): with io.open(file, 'wb') as strm: strm.write(content.encode('utf-8')) def test_utf8_encoding_retained(self, tmpdir): """ When editing a file, non-ASCII characters encoded in UTF-8 should be retained. """ config = tmpdir.join('setup.cfg') self.write_text(str(config), '[names]\njaraco=йарацо') setopt.edit_config(str(config), dict(names=dict(other='yes'))) parser = self.parse_config(str(config)) assert parser.get('names', 'jaraco') == 'йарацо' assert parser.get('names', 'other') == 'yes'
Remove suppression for serialisation warning
package org.workcraft.gui.controls; import org.workcraft.utils.GuiUtils; import javax.swing.*; import javax.swing.table.TableCellRenderer; import java.awt.*; public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { setText(""); setOpaque(true); } else { String text = value.toString(); setText(text); setFont(table.getFont()); setOpaque(text.isEmpty()); } setBorder(GuiUtils.getTableCellBorder()); return this; } }
package org.workcraft.gui.controls; import org.workcraft.utils.GuiUtils; import javax.swing.*; import javax.swing.table.TableCellRenderer; import java.awt.*; @SuppressWarnings("serial") public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { setText(""); setOpaque(true); } else { String text = value.toString(); setText(text); setFont(table.getFont()); setOpaque(text.isEmpty()); } setBorder(GuiUtils.getTableCellBorder()); return this; } }
Add utf-8 support for long description
from setuptools import setup, find_packages from os.path import join, dirname import sys if sys.version_info.major < 3: print("Sorry, currently only Python 3 is supported!") sys.exit(1) setup( name = 'CollectionBatchTool', version=__import__('collectionbatchtool').__version__, description = 'batch import and export of Specify data', long_description = open( join(dirname(__file__), 'README.rst'), encoding='utf-8').read(), packages = find_packages(), py_modules = ['collectionbatchtool', 'specifymodels'], install_requires = ['pandas>=0.16', 'peewee>=2.6', 'pymysql'], author = 'Markus Englund', author_email = 'jan.markus.englund@gmail.com', url = 'https://github.com/jmenglund/CollectionBatchTool', license = 'MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], keywords = ['Specify', 'Collection management'] )
from setuptools import setup, find_packages from os.path import join, dirname import sys if sys.version_info.major < 3: print("Sorry, currently only Python 3 is supported!") sys.exit(1) setup( name = 'CollectionBatchTool', version=__import__('collectionbatchtool').__version__, description = 'batch import and export of Specify data', long_description = open(join(dirname(__file__), 'README.rst')).read(), packages = find_packages(), py_modules = ['collectionbatchtool', 'specifymodels'], install_requires = ['pandas>=0.16', 'peewee>=2.6', 'pymysql'], author = 'Markus Englund', author_email = 'jan.markus.englund@gmail.com', url = 'https://github.com/jmenglund/CollectionBatchTool', license = 'MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], keywords = ['Specify', 'Collection management'] )
Replace use of SCRIPT_URI for OS X Server compatibility (mod_php environment).
<?php // Setup require_once '../cassowary/cassowary-setup.php'; // logout if necessary if (phpCAS::isAuthenticated()) { phpCAS::logoutWithRedirectService( ($_SERVER["'HTTPS'"] ? "https://" : "http://" ) . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); } ?> <!DOCTYPE html> <html> <head> <title>Logged Out</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> <?php if ($cassowary_show_pics): ?> html { height: 100%; background: url(/cassowary/casuarius-egg.jpg) no-repeat center center; background-size: cover; } <?php endif ?> body { max-width: 40em; margin: auto; background-color: rgba(255,255,255,0.5); } </style> </head> <body> <h1>Logout successful</h1> <p>You have successfully logged out. <P><a href="/login/">Click here to login to <strong><?php echo $_SERVER["HTTP_HOST"] ?></strong> again</a> <p>For security reasons, exit your web browser. </body> </html>
<?php // Setup require_once '../cassowary/cassowary-setup.php'; // logout if necessary if (phpCAS::isAuthenticated()) { phpCAS::logoutWithRedirectService($_SERVER["SCRIPT_URI"]); } ?> <!DOCTYPE html> <html> <head> <title>Logged Out</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> <?php if ($cassowary_show_pics): ?> html { height: 100%; background: url(/cassowary/casuarius-egg.jpg) no-repeat center center; background-size: cover; } <?php endif ?> body { max-width: 40em; margin: auto; background-color: rgba(255,255,255,0.5); } </style> </head> <body> <h1>Logout successful</h1> <p>You have successfully logged out. <P><a href="/login/">Click here to login to <strong><?php echo $_SERVER["HTTP_HOST"] ?></strong> again</a> <p>For security reasons, exit your web browser. </body> </html>
Fix an issue where SSH workflows would execute immediately Summary: rPe397103bf broke this since one of the implementations was `return false;`, not `return true;`. Auditors: chad
<?php abstract class PhabricatorSSHWorkflow extends PhabricatorManagementWorkflow { private $user; private $iochannel; private $errorChannel; public function isExecutable() { return false; } public function setErrorChannel(PhutilChannel $error_channel) { $this->errorChannel = $error_channel; return $this; } public function getErrorChannel() { return $this->errorChannel; } public function setUser(PhabricatorUser $user) { $this->user = $user; return $this; } public function getUser() { return $this->user; } public function setIOChannel(PhutilChannel $channel) { $this->iochannel = $channel; return $this; } public function getIOChannel() { return $this->iochannel; } public function readAllInput() { $channel = $this->getIOChannel(); while ($channel->update()) { PhutilChannel::waitForAny(array($channel)); if (!$channel->isOpenForReading()) { break; } } return $channel->read(); } public function writeIO($data) { $this->getIOChannel()->write($data); return $this; } public function writeErrorIO($data) { $this->getErrorChannel()->write($data); return $this; } protected function newPassthruCommand() { return id(new PhabricatorSSHPassthruCommand()) ->setErrorChannel($this->getErrorChannel()); } }
<?php abstract class PhabricatorSSHWorkflow extends PhabricatorManagementWorkflow { private $user; private $iochannel; private $errorChannel; public function setErrorChannel(PhutilChannel $error_channel) { $this->errorChannel = $error_channel; return $this; } public function getErrorChannel() { return $this->errorChannel; } public function setUser(PhabricatorUser $user) { $this->user = $user; return $this; } public function getUser() { return $this->user; } public function setIOChannel(PhutilChannel $channel) { $this->iochannel = $channel; return $this; } public function getIOChannel() { return $this->iochannel; } public function readAllInput() { $channel = $this->getIOChannel(); while ($channel->update()) { PhutilChannel::waitForAny(array($channel)); if (!$channel->isOpenForReading()) { break; } } return $channel->read(); } public function writeIO($data) { $this->getIOChannel()->write($data); return $this; } public function writeErrorIO($data) { $this->getErrorChannel()->write($data); return $this; } protected function newPassthruCommand() { return id(new PhabricatorSSHPassthruCommand()) ->setErrorChannel($this->getErrorChannel()); } }
CHANGE the size at which we go to mobile layout to 600
import React from 'react'; import styled from '@emotion/styled'; import ResizeDetector from 'react-resize-detector'; import { inject, observer } from 'mobx-react'; import { Mobile } from './components/layout/mobile'; import { Desktop } from './components/layout/desktop'; import Nav from './containers/nav'; import Preview from './containers/preview'; import Panel from './containers/panel'; const Reset = styled.div(({ theme }) => ({ fontFamily: theme.mainTextFace, color: theme.mainTextColor, background: theme.mainBackground, WebkitFontSmoothing: 'antialiased', fontSize: theme.mainTextSize, position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, width: '100vw', height: '100vh', overflow: 'hidden', })); const App = ({ uiStore }) => { const props = { Nav, Preview, Panel, options: { ...uiStore, }, }; return ( <Reset> <ResizeDetector handleWidth> {width => { if (width === 0) return <div />; if (width < 600) return <Mobile {...props} />; return <Desktop {...props} />; }} </ResizeDetector> </Reset> ); }; // TODO: use a uiStore and observer in the layout export default inject('uiStore')(observer(App));
import React from 'react'; import styled from '@emotion/styled'; import ResizeDetector from 'react-resize-detector'; import { inject, observer } from 'mobx-react'; import { Mobile } from './components/layout/mobile'; import { Desktop } from './components/layout/desktop'; import Nav from './containers/nav'; import Preview from './containers/preview'; import Panel from './containers/panel'; const Reset = styled.div(({ theme }) => ({ fontFamily: theme.mainTextFace, color: theme.mainTextColor, background: theme.mainBackground, WebkitFontSmoothing: 'antialiased', fontSize: theme.mainTextSize, position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, width: '100vw', height: '100vh', overflow: 'hidden', })); const App = ({ uiStore }) => { const props = { Nav, Preview, Panel, options: { ...uiStore, }, }; return ( <Reset> <ResizeDetector handleWidth> {width => { if (width === 0) return <div />; if (width < 500) return <Mobile {...props} />; return <Desktop {...props} />; }} </ResizeDetector> </Reset> ); }; // TODO: use a uiStore and observer in the layout export default inject('uiStore')(observer(App));
Make it work with pages which use `serverTiming`
(function(){ 'use strict'; if (document.readyState === 'complete') { startCollect(); } else { window.addEventListener('load', startCollect); } function startCollect() { const timing = performance.getEntriesByType('navigation')[0].toJSON(); timing.start = performance.timing.requestStart; delete timing.serverTiming; if (timing.duration > 0) { // fetchStart sometimes negative in FF, make an adjustment based on fetchStart var adjustment = timing.fetchStart < 0 ? -timing.fetchStart : 0; ['domainLookupStart', 'domainLookupEnd', 'connectStart', 'connectEnd', 'requestStart', 'responseStart', 'responseEnd', 'domComplete', 'domInteractive', 'domContentLoadedEventStart', 'domContentLoadedEventEnd', 'loadEventStart', 'loadEventEnd', 'duration' ].forEach(i => { timing[i] +=adjustment; }); // we have only 4 chars in our disposal including decimal point var time = (timing.duration / 1000).toFixed(2); var promise = browser.runtime.sendMessage({time: time, timing: timing}); promise.catch((reason) => console.log(reason)); } else { setTimeout(startCollect, 100); } } })();
(function(){ 'use strict'; if (document.readyState === 'complete') { startCollect(); } else { window.addEventListener('load', startCollect); } function startCollect() { const timing = performance.getEntriesByType('navigation')[0].toJSON(); timing.start = performance.timing.requestStart; if (timing.duration > 0) { // fetchStart sometimes negative in FF, make an adjustment based on fetchStart var adjustment = timing.fetchStart < 0 ? -timing.fetchStart : 0; ['domainLookupStart', 'domainLookupEnd', 'connectStart', 'connectEnd', 'requestStart', 'responseStart', 'responseEnd', 'domComplete', 'domInteractive', 'domContentLoadedEventStart', 'domContentLoadedEventEnd', 'loadEventStart', 'loadEventEnd', 'duration' ].forEach(i => { timing[i] +=adjustment; }); // we have only 4 chars in our disposal including decimal point var time = (timing.duration / 1000).toFixed(2); browser.runtime.sendMessage({time: time, timing: timing}); } else { setTimeout(startCollect, 100); } } })();
Add a constructor for result Add a constructor for result
package com.poco.PoCoRuntime; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Single unit for matching a PoCo event or result. */ public class Match implements Matchable { private String matchString; private boolean isWildcard; private boolean isAction; private boolean isResult; /** * This constructor creates an Action match * @param matchString */ public Match(String matchString) { // This constructor creates an Action match isAction = true; isResult = false; isWildcard = (matchString == "%"); this.matchString = matchString; } /** * Constructor for Match when it is result instead of action * @param matchString */ public Match(String matchString, boolean isaction, boolean isresult) { isAction = isaction; isResult = isresult; isWildcard = (matchString == "%"); this.matchString = matchString; } @Override public boolean accepts(Event event) { if (isWildcard) { return true; } Pattern pattern = Pattern.compile(matchString); Matcher matcher = pattern.matcher(event.getSignature()); return matcher.find(); } }
package com.poco.PoCoRuntime; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Single unit for matching a PoCo event or result. */ public class Match implements Matchable { private String matchString; private boolean isWildcard; private boolean isAction; private boolean isResult; public Match(String matchString) { // This constructor creates an Action match isAction = true; isResult = false; isWildcard = (matchString == "%"); this.matchString = matchString; } @Override public boolean accepts(Event event) { if (isWildcard) { return true; } Pattern pattern = Pattern.compile(matchString); Matcher matcher = pattern.matcher(event.getSignature()); return matcher.find(); } }
Revert "fixed pen styling bug" This reverts commit 2acf214f5479ca2a691e0f4b09bcef8a28f99e2a.
package application.Actions; import javafx.geometry.Point2D; import application.SLogoCanvas; import application.Turtle; public class ForwardAction extends AbstractAction { public ForwardAction(double distance) { myValue = distance; } @Override public void update(Turtle turtle, SLogoCanvas canvas) { Point2D previousLocation = turtle.getLocation(); double remainder = myValue; while (remainder > 0) { //I PROMISE I WILL COME UP WITH A BETTER SOLUTION //BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING //PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH if (turtle.getPen().isDashed() && myValue > 30) { canvas.displayLine(turtle.move(30)); remainder -= 20; } else if (turtle.getPen().isDotted() && myValue > 5) { canvas.displayLine(turtle.move(5)); remainder -= 5; } else { canvas.displayLine(turtle.move(1)); remainder -= 1; } } // System.out.println("***Prior Location: " + prevLoc); // System.out.println("***Prior Location: " + turt.getLocation()); } @Override public String toString() { return "fwd " + myValue; } }
package application.Actions; import javafx.geometry.Point2D; import application.SLogoCanvas; import application.Turtle; public class ForwardAction extends AbstractAction { public ForwardAction(double distance) { myValue = distance; } @Override public void update(Turtle turtle, SLogoCanvas canvas) { Point2D previousLocation = turtle.getLocation(); double remainder = myValue; while (remainder > 0) { //I PROMISE I WILL COME UP WITH A BETTER SOLUTION //BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING //PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH if (turtle.getPen().isDashed() && remainder >= 30) { canvas.displayLine(turtle.move(30)); remainder -= 30; } else if (turtle.getPen().isDotted() && remainder >= 5) { canvas.displayLine(turtle.move(5)); remainder -= 5; } else { canvas.displayLine(turtle.move(1)); remainder -= 1; } } // System.out.println("***Prior Location: " + prevLoc); // System.out.println("***Prior Location: " + turt.getLocation()); } @Override public String toString() { return "fwd " + myValue; } }
Remove superseded config default for `ROOT_REDIRECT_STATUS_CODE`
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None ROOT_REDIRECT_STATUS_CODE = 307 # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
Allow also array as style prop type
import React, { PropTypes } from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( <View style={[customStyles.optionsWrapper, style]}> { React.Children.map(children, c => React.isValidElement(c) ? React.cloneElement(c, { onSelect: c.props.onSelect || onSelect, customStyles: Object.keys(c.props.customStyles || {}).length ? c.props.customStyles : customStyles }) : c ) } </View> ); MenuOptions.propTypes = { onSelect: PropTypes.func, customStyles: PropTypes.object, renderOptionsContainer: PropTypes.func, optionsContainerStyle: PropTypes.oneOfType([ PropTypes.object, PropTypes.number, PropTypes.array, ]), }; MenuOptions.defaultProps = { customStyles: {}, }; export default MenuOptions;
import React from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( <View style={[customStyles.optionsWrapper, style]}> { React.Children.map(children, c => React.isValidElement(c) ? React.cloneElement(c, { onSelect: c.props.onSelect || onSelect, customStyles: Object.keys(c.props.customStyles || {}).length ? c.props.customStyles : customStyles }) : c ) } </View> ); MenuOptions.propTypes = { onSelect: React.PropTypes.func, customStyles: React.PropTypes.object, renderOptionsContainer: React.PropTypes.func, optionsContainerStyle: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.number, ]), }; MenuOptions.defaultProps = { customStyles: {}, }; export default MenuOptions;
Increase HTTP timeout to 60 seconds
import logging import requests import time from cattle import type_manager from cattle.utils import log_request log = logging.getLogger("agent") class Publisher: def __init__(self, url, auth): self._url = url self._auth = auth self._marshaller = type_manager.get_type(type_manager.MARSHALLER) self._session = requests.Session() def publish(self, resp): line = self._marshaller.to_string(resp) start = time.time() try: r = self._session.post(self._url, data=line, auth=self._auth, timeout=60) if r.status_code != 201: log.error("Error [%s], Request [%s]", r.text, line) finally: log_request(resp, log, 'Response: %s [%s] seconds', line, time.time() - start) @property def url(self): return self._url @property def auth(self): return self._auth
import logging import requests import time from cattle import type_manager from cattle.utils import log_request log = logging.getLogger("agent") class Publisher: def __init__(self, url, auth): self._url = url self._auth = auth self._marshaller = type_manager.get_type(type_manager.MARSHALLER) self._session = requests.Session() def publish(self, resp): line = self._marshaller.to_string(resp) start = time.time() try: r = self._session.post(self._url, data=line, auth=self._auth, timeout=5) if r.status_code != 201: log.error("Error [%s], Request [%s]", r.text, line) finally: log_request(resp, log, 'Response: %s [%s] seconds', line, time.time() - start) @property def url(self): return self._url @property def auth(self): return self._auth
Fix wrong error code in 5.4 test. Section 5.1 of http2-16 states that an idle stream receiving a frame other than HEADERS, PUSH_PROMISE, or PRIORITY must be treated as a PROTOCOL_ERROR.
package h2spec import ( "github.com/bradfitz/http2" "io" "time" ) func TestErrorHandling(ctx *Context) { PrintHeader("5.4. Error Handling", 0) TestConnectionErrorHandling(ctx) PrintFooter() } func TestConnectionErrorHandling(ctx *Context) { PrintHeader("5.4.1. Connection Error Handling", 1) func(ctx *Context) { desc := "Receives a GOAWAY frame" msg := "After sending the GOAWAY frame, the endpoint MUST close the TCP connection." gfResult := false closeResult := false http2Conn := CreateHttp2Conn(ctx, true) defer http2Conn.conn.Close() http2Conn.fr.WriteData(1, true, []byte("test")) timeCh := time.After(3 * time.Second) loop: for { select { case f := <-http2Conn.dataCh: gf, ok := f.(*http2.GoAwayFrame) if ok { if gf.ErrCode == http2.ErrCodeProtocol { gfResult = true } } case err := <-http2Conn.errCh: if err == io.EOF { closeResult = true } break loop case <-timeCh: break loop } } PrintResult(gfResult && closeResult, desc, msg, 1) }(ctx) }
package h2spec import ( "github.com/bradfitz/http2" "io" "time" ) func TestErrorHandling(ctx *Context) { PrintHeader("5.4. Error Handling", 0) TestConnectionErrorHandling(ctx) PrintFooter() } func TestConnectionErrorHandling(ctx *Context) { PrintHeader("5.4.1. Connection Error Handling", 1) func(ctx *Context) { desc := "Receives a GOAWAY frame" msg := "After sending the GOAWAY frame, the endpoint MUST close the TCP connection." gfResult := false closeResult := false http2Conn := CreateHttp2Conn(ctx, true) defer http2Conn.conn.Close() http2Conn.fr.WriteData(1, true, []byte("test")) timeCh := time.After(3 * time.Second) loop: for { select { case f := <-http2Conn.dataCh: gf, ok := f.(*http2.GoAwayFrame) if ok { if gf.ErrCode == http2.ErrCodeStreamClosed { gfResult = true } } case err := <-http2Conn.errCh: if err == io.EOF { closeResult = true } break loop case <-timeCh: break loop } } PrintResult(gfResult && closeResult, desc, msg, 1) }(ctx) }
Fix ecu id retrieval ??
<?php // Set Logger Def $defFile = '../../misc/loggerdefs/' . $_POST['Definition']; if(!file_exists($defFile)) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); echo "Invalid File: {$_POST['Definition']}"; exit; } $LoggerDef = simplexml_load_file($defFile); // Find our ECU IDs $ecuArray = array(); $tmpArray = $LoggerDef->xpath('//ecuparam/ecu/@id'); foreach($tmpArray as $value) { $ecuArray = array_unique(array_merge($ecuArray, explode(',', (string)$value))); } // Get sorted, unique IDs $ecuArray = array_unique($ecuArray); sort($ecuArray); // 500 on empty array if(empty($ecuArray)) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); echo "No ECU Parameters in Definition File"; exit; } // Send it on back echo json_encode($ecuArray);
<?php // Set Logger Def $defFile = '../../misc/loggerdefs/' . $_POST['Definition']; if(!file_exists($defFile)) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); echo "Invalid File: {$_POST['Definition']}"; exit; } $LoggerDef = simplexml_load_file($defFile); // Find our ECU IDs $ecuArray = array(); $tmpArray = $LoggerDef->xpath('//ecuparam/ecu/@id'); foreach($tmpArray as $value) { $ecuArray = array_merge($ecuArray, explode(',', (string)$value)); } // Get sorted, unique IDs $ecuArray = array_unique($ecuArray); sort($ecuArray); // 500 on empty array if(empty($ecuArray)) { header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); echo "No ECU Parameters in Definition File"; exit; } // Send it on back echo json_encode($ecuArray);
Fix up the cleanup of the temporary DB so it works for BSD DB's compatibility layer as well as "classic" ndbm.
#! /usr/bin/env python """Test script for the dbm module Roger E. Masse """ import dbm from dbm import error from test_support import verbose filename = '/tmp/delete_me' d = dbm.open(filename, 'c') d['a'] = 'b' d['12345678910'] = '019237410982340912840198242' d.keys() if d.has_key('a'): if verbose: print 'Test dbm keys: ', d.keys() d.close() d = dbm.open(filename, 'r') d.close() d = dbm.open(filename, 'rw') d.close() d = dbm.open(filename, 'w') d.close() d = dbm.open(filename, 'n') d.close() try: import os if dbm.library == "ndbm": # classic dbm os.unlink(filename + '.dir') os.unlink(filename + '.pag') elif dbm.library == "BSD db": # BSD DB's compatibility layer os.unlink(filename + '.db') else: # GNU gdbm compatibility layer os.unlink(filename) except: pass
#! /usr/bin/env python """Test script for the dbm module Roger E. Masse """ import dbm from dbm import error from test_support import verbose filename= '/tmp/delete_me' d = dbm.open(filename, 'c') d['a'] = 'b' d['12345678910'] = '019237410982340912840198242' d.keys() if d.has_key('a'): if verbose: print 'Test dbm keys: ', d.keys() d.close() d = dbm.open(filename, 'r') d.close() d = dbm.open(filename, 'rw') d.close() d = dbm.open(filename, 'w') d.close() d = dbm.open(filename, 'n') d.close() try: import os os.unlink(filename + '.dir') os.unlink(filename + '.pag') except: pass
Fix periodic tasks model display
# -*- coding: utf-8 -*- from __future__ import unicode_literals from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS from udata.i18n import lazy_gettext as _ from udata.models import db __all__ = ('PeriodicTask', 'PERIODS') CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week}' class PeriodicTask(BasePeriodicTask): last_run_id = db.StringField() class Interval(BasePeriodicTask.Interval): def __unicode__(self): if self.every == 1: return _('every {0.period_singular}').format(self) return _('every {0.every} {0.period}').format(self) class Crontab(BasePeriodicTask.Crontab): def __unicode__(self): return CRON.format(**self._data) @property def schedule_display(self): if self.interval: return str(self.interval) elif self.crontab: return str(self.crontab) else: raise Exception("must define internal or crontab schedule") interval = db.EmbeddedDocumentField(Interval) crontab = db.EmbeddedDocumentField(Crontab)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS from udata.i18n import lazy_gettext as _ from udata.models import db __all__ = ('PeriodicTask', 'PERIODS') class PeriodicTask(BasePeriodicTask): last_run_id = db.StringField() class Interval(BasePeriodicTask.Interval): def __unicode__(self): if self.every == 1: return _('every {0.period_singular}').format(self) return _('every {0.every} {0.period}').format(self) @property def schedule_display(self): if self.interval: return str(self.interval) elif self.crontab: return str(self.crontab) else: raise Exception("must define internal or crontab schedule")
Set the main section of the page to align with the responsive web design changes.
<?php include('./requires.inc.php'); include('./config/loadConfiguration.php'); include('./header.inc.php'); ?> <?php include('./navigation.inc.php'); ?> <section role="main"> <div class="blog"> <?php if ($_SESSION["admin"] == 1) { ?> <div class="addPost"><a href="admin-addPost.php">Add Post</a></div> <?php } $blogDao = new BlogDAO(); echo $blogDao->getBlogInformation()->toHTML(); ?> </div> </section> <?php include('./utilities.inc.php'); ?> <?php include('./footer.inc.php'); ?>
<?php include('./requires.inc.php'); include('./config/loadConfiguration.php'); include('./header.inc.php'); ?> <?php include('./navigation.inc.php'); ?> <div class="content"> <div class="blog"> <?php if ($_SESSION["admin"] == 1) { ?> <div class="addPost"><a href="admin-addPost.php">Add Post</a></div> <?php } $blogDao = new BlogDAO(); echo $blogDao->getBlogInformation()->toHTML(); ?> </div> </div> <?php include('./utilities.inc.php'); ?> <?php include('./footer.inc.php'); ?>
Add no-args constructor to avoid NPE during page de-serialization
package com.jvm_bloggers.frontend.public_area.common_layout; import com.jvm_bloggers.domain.query.newsletter_issue_for_listing.NewsletterIssueForListing; import com.jvm_bloggers.domain.query.newsletter_issue_for_listing.NewsletterIssueForListingQuery; import javaslang.collection.Seq; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @NoArgsConstructor public class RightFrontendSidebarBackingBean { private NewsletterIssueForListingQuery query; @Autowired public RightFrontendSidebarBackingBean(NewsletterIssueForListingQuery query) { this.query = query; } public Seq<NewsletterIssueForListing> getLatestIssues(int numberOfListedIssues) { return query.findLatestIssues(numberOfListedIssues); } }
package com.jvm_bloggers.frontend.public_area.common_layout; import com.jvm_bloggers.domain.query.newsletter_issue_for_listing.NewsletterIssueForListing; import com.jvm_bloggers.domain.query.newsletter_issue_for_listing.NewsletterIssueForListingQuery; import javaslang.collection.Seq; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RightFrontendSidebarBackingBean { private final NewsletterIssueForListingQuery query; @Autowired public RightFrontendSidebarBackingBean(NewsletterIssueForListingQuery query) { this.query = query; } public Seq<NewsletterIssueForListing> getLatestIssues(int numberOfListedIssues) { return query.findLatestIssues(numberOfListedIssues); } }
Define HasAbilities trait on default user.
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\HasAbilities; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword, HasAbilities; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
Add auth header to challenge browsers
Meteor.startup(function () { var stack; if (process.env.RESTRICT_ENV) { // Ensure credentials are provided if (!Meteor.settings.basicAuth) { throw new Error("[talos:basic-auth] No credentials were found in your meteor settings"); } // Add handler WebApp.connectHandlers.use(function (req, res, next) { var auth = Npm.require("basic-auth"), valid = Meteor.settings.basicAuth, user = auth(req); if (!user || user.name !== valid.name || user.pass !== valid.pass) { res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm="Promised Land"'); res.end('Access denied'); } else { next(); } }); // Move handler to the top of the stack stack = WebApp.connectHandlers.stack; stack.unshift(stack.pop()); } });
Meteor.startup(function () { var stack; if (process.env.RESTRICT_ENV) { // Ensure credentials are provided if (!Meteor.settings.basicAuth) { throw new Error("[talos:basic-auth] No credentials were found in your meteor settings"); } // Add handler WebApp.connectHandlers.use(function (req, res, next) { var auth = Npm.require("basic-auth"), valid = Meteor.settings.basicAuth, user = auth(req); if (!user || user.name !== valid.name || user.pass !== valid.pass) { res.statusCode = 401; res.end('Access denied'); } else { next(); } }); // Move handler to the top of the stack stack = WebApp.connectHandlers.stack; stack.unshift(stack.pop()); } });
[test] Make exit codes more specific When an uncaught exception is thrown, `node ` exits with `1`. Make it clear that exits are cause by listening errors.
/* * Test _doListen function in net.js of haibu.carapace when there are multiple servers * */ var net = require('net'), port = 8000; var server1 = net.createServer(function (socket) { }); var server2 = net.createServer(function (socket) { }); var server3 = net.createServer(function (socket) { }); server1.addListener('error', function (err) { process.exit(101); }); server2.addListener('error', function (err) { process.exit(102); }); server3.addListener('error', function (err) { process.exit(103); }); // // start server1 to use the test port and address... // server1.listen(port, 'localhost', function () { var ready = false; // // Server1 is occupying the test port and address so now spawn up more servers // server2.listen(port, 'localhost', function () { if (ready) process.exit(0); ready = true; }); server3.listen(port, 'localhost', function () { if (ready) process.exit(0); ready = true; }); });
/* * Test _doListen function in net.js of haibu.carapace when there are multiple servers * */ var net = require('net'), port = 8000; var server1 = net.createServer(function (socket) { }); var server2 = net.createServer(function (socket) { }); var server3 = net.createServer(function (socket) { }); server1.addListener('error', function (err) { process.exit(1); }); server2.addListener('error', function (err) { process.exit(2); }); server3.addListener('error', function (err) { process.exit(3); }); // // start server1 to use the test port and address... // server1.listen(port, 'localhost', function () { var ready = false; // // Server1 is occupying the test port and address so now spawn up more servers // server2.listen(port, 'localhost', function () { if (ready) process.exit(0); ready = true; }); server3.listen(port, 'localhost', function () { if (ready) process.exit(0); ready = true; }); });
Move /collection to path prepended to emoticonRoutes
const express = require('express'), app = express(), bodyParser = require('body-parser'), methodOverride = require('method-override'), mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mojibox'); app.set('view engine', 'pug'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({extended: true})); app.use(methodOverride('_method')); const userRoutes = require('./routes/users'); const emoticonRoutes = require('./routes/emoticons'); app.use('/user', userRoutes); app.use('/user/:username/collection', emoticonRoutes); app.get('/', function(req, res, next) { res.redirect('/user'); }); if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } app.listen(3000, function() { console.log('Server is listening on port 3000'); });
const express = require('express'), app = express(), bodyParser = require('body-parser'), methodOverride = require('method-override'), mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mojibox'); app.set('view engine', 'pug'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.urlencoded({extended: true})); app.use(methodOverride('_method')); const userRoutes = require('./routes/users'); const emoticonRoutes = require('./routes/emoticons'); app.use('/user', userRoutes); // app.use('/user/:user_id/', emoticonRoutes); app.get('/', function(req, res, next) { res.redirect('/user'); }); if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } app.listen(3000, function() { console.log('Server is listening on port 3000'); });
Make python script work with python 3 as well as python 2.7
from gi.repository import GLib import dbus import dbus.service from dbus.mainloop.glib import DBusGMainLoop class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('com.zielmicha.test', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/com/zielmicha/test') @dbus.service.method('com.zielmicha.test') def hello(self, *args, **kwargs): print( 'hello world {} {}'.format(args, kwargs) ) return ("Hello, world!", args[0] if args else 1) @dbus.service.signal('com.zielmicha.testsignal') def hello_sig(self): print( 'hello world sig' ) DBusGMainLoop(set_as_default=True) myservice = MyDBUSService() loop = GLib.MainLoop() loop.run()
from gi.repository import GLib import dbus import dbus.service from dbus.mainloop.glib import DBusGMainLoop class MyDBUSService(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('com.zielmicha.test', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/com/zielmicha/test') @dbus.service.method('com.zielmicha.test') def hello(self, *args, **kwargs): print 'hello world {} {}'.format(args, kwargs) return ("Hello, world!", args[0] if args else 1) @dbus.service.signal('com.zielmicha.testsignal') def hello_sig(self): print 'hello world sig' DBusGMainLoop(set_as_default=True) myservice = MyDBUSService() loop = GLib.MainLoop() loop.run()
Move clouds down a little
import React from 'react' import PropTypes from 'prop-types' export const Content = ({ children, clouds }) => ( <main> {children} <style jsx>{` @import 'colors'; main { background-color: $white; padding: 2em 0 10em; display: flex; flex-direction: column; flex: 1; ${clouds && (` background: url('/static/images/clouds.svg') bottom -120px right 0, linear-gradient(to top, #41dcd7, #3083b2); background-repeat: no-repeat; background-size: 100%; `)} } `}</style> </main> ) Content.propTypes = { children: PropTypes.node, clouds: PropTypes.bool } Content.defaultProps = { clouds: false } export default Content
import React from 'react' import PropTypes from 'prop-types' export const Content = ({ children, clouds }) => ( <main> {children} <style jsx>{` @import 'colors'; main { background-color: $white; padding: 2em 0 10em; display: flex; flex-direction: column; flex: 1; ${clouds && (` background: url('/static/images/clouds.svg') bottom / 101% no-repeat, linear-gradient(to top, #41dcd7, #3083b2); `)} } `}</style> </main> ) Content.propTypes = { children: PropTypes.node, clouds: PropTypes.bool } Content.defaultProps = { clouds: false } export default Content
Use raw strings for regexes.
import re class Phage: supported_databases = { # European Nucleotide Archive phage database "ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": r"^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parsePhage(raw_text, phage_finder) def _parsePhage(self, raw_text, phage_finder): for db, regex in Phage.supported_databases.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.findByPhage(short_name, cluster) self.db = db
import re class Phage: supported_databases = { # European Nucleotide Archive phage database "ENA": "^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$", # National Center for Biotechnology Information phage database "NCBI": "^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$", # Actinobacteriophage Database "AD": "^([^\ ]+)\ [^,]*,[^,]*,\ Cluster\ ([^$]+)$" } def __init__(self, raw_text, phage_finder): self.raw = raw_text.strip() self.refseq = None self.name = None self.db = None self._parsePhage(raw_text, phage_finder) def _parsePhage(self, raw_text, phage_finder): for db, regex in Phage.supported_databases.items(): match = re.search(regex, raw_text) if match is not None: if db is not "AD": self.name = match.group(2) self.refseq = match.group(1) else: short_name = match.group(1) cluster = match.group(2) self.name = "Mycobacteriophage " + short_name self.refseq = phage_finder.findByPhage(short_name, cluster) self.db = db
Fix small bugs in bundle command
#!/usr/bin/env node // Requires var _ = require('underscore'); var fs = require('fs'); var path = require('path'); // Comannder var prog = require('commander'); // etcd-dump's package.json file var pkg = require('../package.json'); // Dumper class var parser = require('../'); // General options prog .version(pkg.version); // Commands prog .command('compile [filename]') .description('Compile an *.itermcolors file to a JSON scheme') .action(function(filename, opts) { // Output JSON color array console.log(JSON.stringify( parser(fs.readFileSync(filename)), null, 4 // 4 spaces )); }); prog .command('bundle [dir]') .description('Bundle a given directory of schemes to one json file') .action(function(dir, opts) { // Merge scheme's together and add name attribute based on filename var bundle = fs.readdirSync(dir).map(function(filename) { var name = filename.split('.')[0]; var data = require('../' + path.join(dir, filename)); data.name = name; return data; }).reduce(function(bundle, data) { bundle[data.name] = data; return bundle; }, {}); // Output bundle's JSON console.log(JSON.stringify(bundle)); }); // Parse and fallback to help if no args if(_.isEmpty(prog.parse(process.argv).args)) { return prog.help(); }
#!/usr/bin/env node // Requires var _ = require('underscore'); var fs = require('fs'); var path = require('path'); // Comannder var prog = require('commander'); // etcd-dump's package.json file var pkg = require('../package.json'); // Dumper class var parser = require('../'); // General options prog .version(pkg.version); // Commands prog .command('compile [filename]') .description('Compile an *.itermcolors file to a JSON scheme') .action(function(filename, opts) { // Output JSON color array console.log(JSON.stringify( parser(fs.readFileSync(filename)), null, 4 // 4 spaces )); }); prog .command('bundle [dir]') .description('Bundle a given directory of schemes to one json file') .action(function(dir, opts) { // Merge scheme's together and add name attribute based on filename var bundle = fs.readdirSync(dir).map(function(filename) { var name = filename.split('.')[0]; var data = require(path(dir, filename)); data.name = name; return data; }).reduce(function(bundle, data) { bundle[name] = data; return bundle; }, {}); // Output bundle's JSON console.log(JSON.stringify(bundle)); }); // Parse and fallback to help if no args if(_.isEmpty(prog.parse(process.argv).args)) { return prog.help(); }
Remove temporary tarball after using it
package main import ( "fmt" "log" "os" "time" "github.com/jasonlvhit/gocron" ) func main() { scheduler := gocron.NewScheduler() scheduler.Every(1).Day().At("00:00").Do(runSchedulerTask, nil) <-scheduler.Start() } func runSchedulerTask() { archive, err := buildArchive(os.Getenv("TOGLACIER_PATH")) if err != nil { log.Fatal(err) } defer func() { archive.Close() // remove the temporary tarball os.Remove(archive.Name()) }() result, err := sendArchive(archive, os.Getenv("AWS_ACCOUNT_ID"), os.Getenv("AWS_VAULT_NAME")) if err != nil { log.Fatal(err) } auditFile, err := os.OpenFile(os.Getenv("TOGLACIER_AUDIT"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { log.Fatalf("error opening the audit file. details: %s", err) } defer auditFile.Close() audit := fmt.Sprintf("%s %s %s\n", result.time.Format(time.RFC3339), result.location, result.checksum) if _, err = auditFile.WriteString(audit); err != nil { log.Fatalf("error writing the audit file. details: %s", err) } }
package main import ( "fmt" "log" "os" "time" "github.com/jasonlvhit/gocron" ) func main() { scheduler := gocron.NewScheduler() scheduler.Every(1).Day().At("00:00").Do(runSchedulerTask, nil) <-scheduler.Start() } func runSchedulerTask() { archive, err := buildArchive(os.Getenv("TOGLACIER_PATH")) if err != nil { log.Fatal(err) } defer archive.Close() result, err := sendArchive(archive, os.Getenv("AWS_ACCOUNT_ID"), os.Getenv("AWS_VAULT_NAME")) if err != nil { log.Fatal(err) } auditFile, err := os.OpenFile(os.Getenv("TOGLACIER_AUDIT"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { log.Fatalf("error opening the audit file. details: %s", err) } defer auditFile.Close() audit := fmt.Sprintf("%s %s %s\n", result.time.Format(time.RFC3339), result.location, result.checksum) if _, err = auditFile.WriteString(audit); err != nil { log.Fatalf("error writing the audit file. details: %s", err) } }
Remove comment that is no longer relevant.
var ConversationV1 = require('watson-developer-cloud/conversation/v1'); var method = ConversationBot.prototype; function ConversationBot(room) { this.room = room; this.conversation = new ConversationV1({ "username": "a43eee8f-6a96-40fb-a297-f99365f2c202", "password": "uX8MIl44vAmx", "version_date": '2017-02-03' }); } // Send a message to the bot. method.send = function(message) { // Always responds. var bot = this; var room = bot.room; setTimeout(function() { var answer = bot.conversation.message({ workspace_id: 'd4c1a5ce-0485-4c20-b593-2e62b1bc5319', input: {'text': message}, context: {} }, function(err, response) { bot.respond(err, response); }) }, 2000); } method.respond = function(err, response) { if (err) { console.log('error:', err); } else { message = JSON.stringify(response.output.text).slice(2, -2); this.room.broadcast(message, this); } } module.exports = ConversationBot;
var ConversationV1 = require('watson-developer-cloud/conversation/v1'); var method = ConversationBot.prototype; function ConversationBot(room) { this.room = room; this.conversation = new ConversationV1({ "username": "a43eee8f-6a96-40fb-a297-f99365f2c202", "password": "uX8MIl44vAmx", "version_date": '2017-02-03' }); } // Send a message to the bot. method.send = function(message) { // Always responds. var bot = this; var room = bot.room; setTimeout(function() { var answer = bot.conversation.message({ workspace_id: 'd4c1a5ce-0485-4c20-b593-2e62b1bc5319', input: {'text': message}, context: {} }, function(err, response) { bot.respond(err, response); }) }, 2000); } method.respond = function(err, response) { // As far as I know, I need to pass in the bot explicitly because "this" // is a different object for whatever reason. if (err) { console.log('error:', err); } else { message = JSON.stringify(response.output.text).slice(2, -2); this.room.broadcast(message, this); } } module.exports = ConversationBot;
Remove an obsolete method extension This method hasn't existed in a while, and its purpose (including the related tags when loading a discussion via API) has already been achieved by extending the backend.
import { extend } from 'flarum/extend'; import DiscussionListItem from 'flarum/components/DiscussionListItem'; import DiscussionHero from 'flarum/components/DiscussionHero'; import tagsLabel from '../common/helpers/tagsLabel'; import sortTags from '../common/utils/sortTags'; export default function() { // Add tag labels to each discussion in the discussion list. extend(DiscussionListItem.prototype, 'infoItems', function(items) { const tags = this.props.discussion.tags(); if (tags && tags.length) { items.add('tags', tagsLabel(tags), 10); } }); // Restyle a discussion's hero to use its first tag's color. extend(DiscussionHero.prototype, 'view', function(view) { const tags = sortTags(this.props.discussion.tags()); if (tags && tags.length) { const color = tags[0].color(); if (color) { view.attrs.style = {backgroundColor: color}; view.attrs.className += ' DiscussionHero--colored'; } } }); // Add a list of a discussion's tags to the discussion hero, displayed // before the title. Put the title on its own line. extend(DiscussionHero.prototype, 'items', function(items) { const tags = this.props.discussion.tags(); if (tags && tags.length) { items.add('tags', tagsLabel(tags, {link: true}), 5); } }); }
import { extend } from 'flarum/extend'; import DiscussionListItem from 'flarum/components/DiscussionListItem'; import DiscussionPage from 'flarum/components/DiscussionPage'; import DiscussionHero from 'flarum/components/DiscussionHero'; import tagsLabel from '../common/helpers/tagsLabel'; import sortTags from '../common/utils/sortTags'; export default function() { // Add tag labels to each discussion in the discussion list. extend(DiscussionListItem.prototype, 'infoItems', function(items) { const tags = this.props.discussion.tags(); if (tags && tags.length) { items.add('tags', tagsLabel(tags), 10); } }); // Include a discussion's tags when fetching it. extend(DiscussionPage.prototype, 'params', function(params) { params.include.push('tags'); }); // Restyle a discussion's hero to use its first tag's color. extend(DiscussionHero.prototype, 'view', function(view) { const tags = sortTags(this.props.discussion.tags()); if (tags && tags.length) { const color = tags[0].color(); if (color) { view.attrs.style = {backgroundColor: color}; view.attrs.className += ' DiscussionHero--colored'; } } }); // Add a list of a discussion's tags to the discussion hero, displayed // before the title. Put the title on its own line. extend(DiscussionHero.prototype, 'items', function(items) { const tags = this.props.discussion.tags(); if (tags && tags.length) { items.add('tags', tagsLabel(tags, {link: true}), 5); } }); }
Update the setup method of the abstract base test. After updating the error checking routine a new exception surfaced (at least I guess this was the reason) pertaining to authentications. (I thought logging into the admin database grants rights to every database by default, but it seems I was wrong.)
package com.github.kohanyirobert.mongoroid; import org.junit.After; import org.junit.Before; public abstract class AbstractMongoConnectionSimpleSingleTest { protected MongoConnection connection; protected AbstractMongoConnectionSimpleSingleTest() {} // @do-not-check DesignForExtension @Before public void setUp() throws MongoException { connection = MongoConnections.builder() .config(MongoConfigs.builder() .poolSize(1) .build()) .seed(MongoSeeds.builder() // @do-not-check MagicNumber .address(27018) .address(27019) .address(27020) .build()) .build(); connection.database("admin").login("admin", "admin"); // there's a very vague issue with logins and sockets because as I've // noticed that if a communication goes through a socket which is // resolved as "127.0.0.1" mongodb grants read-write permission for every // database with an admin login, but not otherwise (not confirmed tho') connection.database("test").login("test", "test"); } // @do-not-check DesignForExtension @After public void tearDown() throws MongoException { connection.database("test").collection("test").remove(MongoRemoves.get()); connection.close(); } }
package com.github.kohanyirobert.mongoroid; import org.junit.After; import org.junit.Before; public abstract class AbstractMongoConnectionSimpleSingleTest { protected MongoConnection connection; protected AbstractMongoConnectionSimpleSingleTest() {} // @do-not-check DesignForExtension @Before public void setUp() throws MongoException { connection = MongoConnections.builder() .config(MongoConfigs.builder() .poolSize(1) .build()) .seed(MongoSeeds.builder() // @do-not-check MagicNumber .address(27018) .address(27019) .address(27020) .build()) .build(); connection.database("admin").login("admin", "admin"); } // @do-not-check DesignForExtension @After public void tearDown() throws MongoException { connection.database("test").collection("test").remove(MongoRemoves.get()); connection.close(); } }
Add simple test for store 'subscribe' function
'use strict'; import counterReducer from '../reducers/counterReducer'; import simpleActionCreator from '../actions/simpleActionCreators'; function createStore( reducer, initialState ) { let state = initialState; let subscribers = [ ]; function dispatch( action ) { state = reducer( state, action ); subscribers.forEach( subscriber => subscriber() ); } function getState() { return state; } function subscribe( callback ) { subscribers.push( callback ); } return { dispatch, getState, subscribe }; } let startingValue = 0; let incrementAction = simpleActionCreator.increment(); let store = createStore( counterReducer, startingValue ); store.subscribe( () => { console.log( 'State: ' + store.getState() ); } ); store.dispatch( incrementAction ); store.dispatch( incrementAction ); store.dispatch( incrementAction );
'use strict'; import counterReducer from '../reducers/counterReducer'; import simpleActionCreator from '../actions/simpleActionCreators'; function createStore( reducer, initialState ) { let state = initialState; let subscribers = [ ]; function dispatch( action ) { state = reducer( state, action ); subscribers.forEach( subscriber => subscriber() ); } function getState() { return state; } function subscribe( callback ) { subscribers.push( callback ); } return { dispatch, getState, subscribe }; } let startingValue = 0; let incrementAction = simpleActionCreator.increment(); let store = createStore( counterReducer, startingValue ); console.log( store.getState() ); store.dispatch( incrementAction ); console.log( store.getState() ); store.dispatch( incrementAction ); console.log( store.getState() ); store.dispatch( incrementAction ); console.log( store.getState() );
Update to use Turbolinks events
$(document).on('ready turbolinks:load', function() { $("#red-button").on("click", function() { var flagsEnabled = $(this).is(":checked"); $.ajax({ 'type': 'POST', 'url': '/flagging/preferences/enable', 'data': { 'enable': flagsEnabled } }) .done(function(data) { console.log("Saved :)"); }) .error(function(xhr, textStatus, errorThrown) { console.error(xhr.responseText); }); }); });
$(document).ready(function() { $("#red-button").on("click", function() { var flagsEnabled = $(this).is(":checked"); $.ajax({ 'type': 'POST', 'url': '/flagging/preferences/enable', 'data': { 'enable': flagsEnabled } }) .done(function(data) { console.log("Saved :)"); }) .error(function(xhr, textStatus, errorThrown) { console.error(xhr.responseText); }); }); });
Add __float__ operator to TimeOnce
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt) def __float__(self): return self.dt
import time class TimeOnce: """Time a sequence of code, allowing access to the time difference in seconds. Example without exception: elapsed = TimeOnce() with elapsed: print('sleeping ...') time.sleep(3) print("elapsed", elapsed) Example with exception: elapsed = TimeOnce() try: with elapsed: print('sleeping ...') time.sleep(3) raise ValueError('foo') print("elapsed inner", elapsed) finally: print("elapsed outer", elapsed) """ def __init__(self): self.t0 = None # An invalid value. def __enter__(self): self.t0 = time.time() def __exit__(self, type, value, traceback): self.dt = time.time() - self.t0 def get_elapsed(self): return self.dt def __str__(self): return str(self.dt)
Add constant defined no op on press
/* eslint-disable react/forbid-prop-types */ /* eslint-disable import/prefer-default-export */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import { View, TouchableWithoutFeedback } from 'react-native'; import PropTypes from 'prop-types'; /** * TouchableWithoutFeedback doesn't have a style prop. View doesn't have an onPress * Prop. This hack ensures events don't propogate to the parent, styling stays consistent * and no feedback (i.e. gesture echo) is given to the user. */ const onPressNoOp = () => {}; const TouchableNoFeedback = ({ children, style, ...touchableProps }) => ( <TouchableWithoutFeedback onPress={onPressNoOp} {...touchableProps}> <View style={style}>{children}</View> </TouchableWithoutFeedback> ); TouchableNoFeedback.defaultProps = { style: null, }; TouchableNoFeedback.propTypes = { children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired, style: PropTypes.object, }; export default TouchableNoFeedback;
/* eslint-disable react/forbid-prop-types */ /* eslint-disable import/prefer-default-export */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React from 'react'; import { View, TouchableWithoutFeedback } from 'react-native'; import PropTypes from 'prop-types'; /** * TouchableWithoutFeedback doesn't have a style prop. View doesn't have an onPress * Prop. This hack ensures events don't propogate to the parent, styling stays consistent * and no feedback (i.e. gesture echo) is given to the user. */ const TouchableNoFeedback = ({ children, style }) => ( <TouchableWithoutFeedback onPress={() => {}}> <View style={style}>{children}</View> </TouchableWithoutFeedback> ); TouchableNoFeedback.defaultProps = { style: null, }; TouchableNoFeedback.propTypes = { children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired, style: PropTypes.object, }; export default TouchableNoFeedback;
Remove 1000ms wait for page load
/* eslint-env phantomjs */ var system = require('system'); var webpage = require('webpage'); var page = webpage.create(); var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) ' + 'AppleWebKit/537.36 (KHTML, like Gecko) ' + 'Chrome/56.0.2924.87 Safari/537.36'; var args = JSON.parse(system.args[1]); var url = args.url; var viewSize = args.viewSize; function complete(msg) { system.stdout.write(JSON.stringify(msg)); phantom.exit(); } function renderComplete() { var render = page.renderBase64('PNG'); var msg = { status: 'ok', body: render, }; complete(msg); } function uponPageOpen(status) { if (status !== 'success') { var msg = { status: 'error', body: status, }; complete(msg); return; } renderComplete(); } page.settings.userAgent = ua; page.viewportSize = viewSize; page.open(url, uponPageOpen);
/* eslint-env phantomjs */ var system = require('system'); var webpage = require('webpage'); var page = webpage.create(); var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) ' + 'AppleWebKit/537.36 (KHTML, like Gecko) ' + 'Chrome/56.0.2924.87 Safari/537.36'; var args = JSON.parse(system.args[1]); var url = args.url; var viewSize = args.viewSize; function complete(msg) { system.stdout.write(JSON.stringify(msg)); phantom.exit(); } function uponWindowLoad() { var render = page.renderBase64('PNG'); var msg = { status: 'ok', body: render, }; complete(msg); } function uponPageOpen(status) { if (status !== 'success') { var msg = { status: 'error', body: status, }; complete(msg); return; } // Wait an extra second for anything else to load window.setTimeout(uponWindowLoad, 1000); } page.settings.userAgent = ua; page.viewportSize = viewSize; page.open(url, uponPageOpen);
:bug: Fix `AlminLogger is not constructor`
// @flow import React from 'react' import ReactDOM from 'react-dom' import { Dispatcher, Context } from 'almin' import AlminLogger from 'almin-logger' import AppStoreGroup from './store/AppStoreGroup' import SearchApp from './SearchApp' import LazyLoadApp from './LazyLoadApp' import { registerWorkers } from './ServiceWorker' import swPrecacheConfig from '../../sw-precache-config' // --- Init SearchApp const dispatcher = new Dispatcher() const appContext = new Context({ dispatcher, store: AppStoreGroup.create() }) if (process.env.NODE_ENV !== 'production') { const logger = new AlminLogger() logger.startLogging(appContext) } ReactDOM.render(<SearchApp appContext={appContext} />, document.getElementById('search')) // --- Init LazyLoadApp LazyLoadApp(document.querySelectorAll('.markdown img')) // --- Init ServiceWorker registerWorkers([ swPrecacheConfig.swFile ])
// @flow import React from 'react' import ReactDOM from 'react-dom' import { Dispatcher, Context } from 'almin' import AppStoreGroup from './store/AppStoreGroup' import SearchApp from './SearchApp' import LazyLoadApp from './LazyLoadApp' import { registerWorkers } from './ServiceWorker' import swPrecacheConfig from '../../sw-precache-config' // --- Init SearchApp const dispatcher = new Dispatcher() const appContext = new Context({ dispatcher, store: AppStoreGroup.create() }) if (process.env.NODE_ENV !== 'production') { const { AlminLogger } = require('almin-logger') const logger = new AlminLogger() logger.startLogging(appContext) } ReactDOM.render(<SearchApp appContext={appContext} />, document.getElementById('search')) // --- Init LazyLoadApp LazyLoadApp(document.querySelectorAll('.markdown img')) // --- Init ServiceWorker registerWorkers([ swPrecacheConfig.swFile ])
Change property name in PublicKey class
// telegram.link // // Copyright 2014 Enrico Stara 'enrico.stara@gmail.com' // Released under the MIT license // http://telegram.link // PublicKey class // // This class represents a Public Key // The constructor requires the fingerprint, the modulus and the exponent function PublicKey(params) { this._fingerprint = params.fingerprint; this._modulus = params.modulus; this._exponent = params.exponent; } PublicKey.prototype.getFingerprint = function () { return this._fingerprint; }; PublicKey.prototype.getModulus = function () { return this._modulus; }; PublicKey.prototype.getExponent = function () { return this._exponent; }; // The key store var keyStore = {}; // Add a key to key store, it requires the fingerprint, the key and the exponent: // // PublicKey.addKey{fingerprint: '...', modulus: '...', exponent: '...'}); // PublicKey.addKey = function (params) { var newKey = new PublicKey(params); keyStore[newKey.getFingerprint()] = newKey; }; // Retrieve a key with the fingerprint PublicKey.retrieveKey = function (fingerprint) { return keyStore[fingerprint]; }; // Export the class module.exports = exports = PublicKey;
// telegram.link // // Copyright 2014 Enrico Stara 'enrico.stara@gmail.com' // Released under the MIT license // http://telegram.link // PublicKey class // // This class represents a Public Key // The constructor requires the fingerprint, the key and the exponent function PublicKey(params) { this._fingerprint = params.fingerprint; this._key = params.key; this._exponent = params.exponent; } PublicKey.prototype.getFingerprint = function () { return this._fingerprint; }; PublicKey.prototype.getKey = function () { return this._key; }; PublicKey.prototype.getExponent = function () { return this._exponent; }; // The key store var keyStore = {}; // Add a key to key store, it requires the fingerprint, the key and the exponent: // // PublicKey.addKey{fingerprint: '...', key: '...', exponent: '...'}); // PublicKey.addKey = function (params) { var newKey = new PublicKey(params); keyStore[newKey.getFingerprint()] = newKey; }; // Retrieve a key with the fingerprint PublicKey.retrieveKey = function (fingerprint) { return keyStore[fingerprint]; }; // Export the class module.exports = exports = PublicKey;
Add virtualenvwrapper to dev requirements
from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/polygraph-python/polygraph', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', install_requires=[ 'graphql-core>=1.0.1', ], extras_require={ 'dev': [ 'flake8', 'ipython', 'autopep8', 'isort', 'pudb==2017.1.2', 'twine==1.8.1', 'coverage', 'virtualenvwrapper', ], 'test': [ 'coverage', 'coveralls', ] } )
from setuptools import setup setup( name='polygraph', version='0.1.0', description='Python library for defining GraphQL schemas', url='https://github.com/polygraph-python/polygraph', author='Wei Yen, Lee', author_email='hello@weiyen.net', license='MIT', install_requires=[ 'graphql-core>=1.0.1', ], extras_require={ 'dev': [ 'flake8', 'ipython', 'autopep8', 'isort', 'pudb==2017.1.2', 'twine==1.8.1', 'coverage', ], 'test': [ 'coverage', 'coveralls', ] } )
Fix spec for Symfony4 and type hinting in Response
<?php namespace spec\Hexanet\Common\MonologExtraBundle\Logger\Response; use Hexanet\Common\MonologExtraBundle\Logger\Response\ResponseLogger; use Hexanet\Common\MonologExtraBundle\Logger\Response\ResponseLoggerInterface; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ParameterBag; class ResponseLoggerSpec extends ObjectBehavior { function let(LoggerInterface $logger) { $this->beConstructedWith($logger); } function it_is_initializable() { $this->shouldHaveType(ResponseLogger::class); } function it_implements_response_logger_interface() { $this->shouldImplement(ResponseLoggerInterface::class); } function it_logs_request(LoggerInterface $logger) { $logger ->info(Argument::type('string'), Argument::type('array')) ->shouldBeCalled(); $request = new Request(); $response = new Response(); $this->logResponse($response, $request); } }
<?php namespace spec\Hexanet\Common\MonologExtraBundle\Logger\Response; use Hexanet\Common\MonologExtraBundle\Logger\Response\ResponseLogger; use Hexanet\Common\MonologExtraBundle\Logger\Response\ResponseLoggerInterface; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ParameterBag; class ResponseLoggerSpec extends ObjectBehavior { function let(LoggerInterface $logger) { $this->beConstructedWith($logger); } function it_is_initializable() { $this->shouldHaveType(ResponseLogger::class); } function it_implements_response_logger_interface() { $this->shouldImplement(ResponseLoggerInterface::class); } function it_logs_request(LoggerInterface $logger, Response $response, Request $request, ParameterBag $parameterBag) { $logger ->info(Argument::type('string'), Argument::type('array')) ->shouldBeCalled(); $request->attributes = $parameterBag; $this->logResponse($response, $request); } }
Add Data Hub header colours
/** * Convert a color hex to an rgb value * * Note that this currently only works with 6 digit hexes. */ export const hexToRgb = (colorHex) => { const colorValue = parseInt(colorHex.replace('#', ''), 16) return [ (colorValue >> 16) & 255, (colorValue >> 8) & 255, colorValue & 255, ].join() } /** * Convert a color hex and alpha to an rgba value * * Note that this currently only works with 6 digit hexes. */ export const rgba = (colorHex, alpha) => `rgba(${hexToRgb(colorHex)},${alpha})` // The following colours are not included in either: // - https://github.com/penx/govuk-colours or // - https://github.com/govuk-react/govuk-react (which references govuk-colours) // Instead, the colours below have been taken from: // - https://github.com/alphagov/govuk-frontend (referenced by GOV.UK Design System) // Taken from the legacy palette, we're unable to choose a colour // from the modern palette as it's either too light or too dark // for the Data Hub header nav element which sits in between a // darker and lighter shade of grey forming a natural gradient. export const LIGHT_GREY = '#dee0e2' // We require this specific blue for the navigation hover/selection. // This blue has to match the colour of both 'Find Exporters' and 'Market Access'. export const DARK_BLUE = '#005ea5' export const DARK_GREY = '#505a5f' export const MID_GREY = '#b1b4b6' export const FOCUS_COLOUR = '#ffdd00'
/** * Convert a color hex to an rgb value * * Note that this currently only works with 6 digit hexes. */ export const hexToRgb = (colorHex) => { const colorValue = parseInt(colorHex.replace('#', ''), 16) return [ (colorValue >> 16) & 255, (colorValue >> 8) & 255, colorValue & 255, ].join() } /** * Convert a color hex and alpha to an rgba value * * Note that this currently only works with 6 digit hexes. */ export const rgba = (colorHex, alpha) => `rgba(${hexToRgb(colorHex)},${alpha})` // The following colours are not included in either: // - https://github.com/penx/govuk-colours or // - https://github.com/govuk-react/govuk-react (which references govuk-colours) // Instead, the colours have been taken from: // - https://github.com/alphagov/govuk-frontend (referenced by GOV.UK Design System) export const DARK_GREY = '#505a5f' export const MID_GREY = '#b1b4b6' export const FOCUS_COLOUR = '#ffdd00'
Make the example to work with Safari
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import moment from 'moment'; import { withKnobs, number, object, boolean, text, select, date } from '../../src'; storiesOf('Example of Knobs', module) .addDecorator(withKnobs) .add('simple example', () => ( <button>{text('Label', 'Hello Button')}</button> )) .add('with all knobs', () => { const name = text('Name', 'Tom Cary'); const dob = date('DOB', new Date('January 20 1887')); const bold = boolean('Bold', false); const color = select('Color', { red: 'Red', green: 'Green', black: 'Black' }, 'black'); const customStyle = object('Style', { fontFamily: 'Arial', padding: 20, }); const style = { ...customStyle, fontWeight: bold ? 800: 400, color }; return ( <div style={style}> I'm {name} and I born on "{moment(dob).format("DD MMM YYYY")}" </div> ); }) .add('without any knob', () => ( <button>This is a button</button> ));
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import moment from 'moment'; import { withKnobs, number, object, boolean, text, select, date } from '../../src'; storiesOf('Example of Knobs', module) .addDecorator(withKnobs) .add('simple example', () => ( <button>{text('Label', 'Hello Button')}</button> )) .add('with all knobs', () => { const name = text('Name', 'Tom Cary'); const dob = date('DOB', new Date('1889 Jan 20')); const bold = boolean('Bold', false); const color = select('Color', { red: 'Red', green: 'Green', black: 'Black' }, 'black'); const customStyle = object('Style', { fontFamily: 'Arial', padding: 20, }); const style = { ...customStyle, fontWeight: bold ? 800: 400, color }; return ( <div style={style}> I'm {name} and I born on "{moment(dob).format("DD MMM YYYY")}" </div> ); }) .add('without any knob', () => ( <button>This is a button</button> ));
Update consolidate dataset task settings
const Promise = require('bluebird'); const { jobs } = require('../kue'); const defaults = require('lodash/object/defaults'); const taskOptions = { 'process-record': { removeOnComplete: true, attempts: 5 }, 'dataset:consolidate': { removeOnComplete: true, attempts: 2, ttl: 30000, backoff: { delay: 10 * 1000, type: 'fixed' } }, 'dgv:publish': { removeOnComplete: true }, 'udata:synchronizeOne': { removeOnComplete: true } }; module.exports = function (taskName, taskData, options = {}) { if (taskName in taskOptions) { defaults(options, taskOptions[taskName]); } const job = jobs.create(taskName, taskData); /* Pass options to kue */ if (options.removeOnComplete) job.removeOnComplete(true); if (options.attempts) job.attempts(options.attempts); if (options.priority) job.priority(options.priority); if (options.ttl) job.ttl(options.ttl); if (options.backoff) job.backoff(options.backoff); /* Return a promise */ return new Promise((resolve, reject) => { job.save(err => { if (err) return reject(err); resolve(job); }); }); };
const Promise = require('bluebird'); const { jobs } = require('../kue'); const defaults = require('lodash/object/defaults'); const taskOptions = { 'process-record': { removeOnComplete: true, attempts: 5 }, 'dataset:consolidate': { removeOnComplete: true, attempts: 5, ttl: 30000 }, 'dgv:publish': { removeOnComplete: true }, 'udata:synchronizeOne': { removeOnComplete: true } }; module.exports = function (taskName, taskData, options = {}) { if (taskName in taskOptions) { defaults(options, taskOptions[taskName]); } const job = jobs.create(taskName, taskData); /* Pass options to kue */ if (options.removeOnComplete) job.removeOnComplete(true); if (options.attempts) job.attempts(options.attempts); if (options.priority) job.priority(options.priority); if (options.ttl) job.ttl(options.ttl); /* Return a promise */ return new Promise((resolve, reject) => { job.save(err => { if (err) return reject(err); resolve(job); }); }); };
Allow "reverse:fieldname" for a descending sort Closes #42
export default function argsToFindOptions(args, target) { var result = {} , targetAttributes = Object.keys(target.rawAttributes); if (args) { Object.keys(args).forEach(function (key) { if (~targetAttributes.indexOf(key)) { result.where = result.where || {}; result.where[key] = args[key]; } if (key === 'limit' && args[key]) { result.limit = args[key]; } if (key === 'offset' && args[key]) { result.offset = args[key]; } if (key === 'order' && args[key]) { var order; if (args[key].indexOf('reverse:') === 0) { order = [args[key].substring(8), 'DESC']; } else { order = [args[key], 'ASC']; } result.order = [ order ]; } }); } return result; }
export default function argsToFindOptions(args, target) { var result = {} , targetAttributes = Object.keys(target.rawAttributes); if (args) { Object.keys(args).forEach(function (key) { if (~targetAttributes.indexOf(key)) { result.where = result.where || {}; result.where[key] = args[key]; } if (key === 'limit' && args[key]) { result.limit = args[key]; } if (key === 'offset' && args[key]) { result.offset = args[key]; } if (key === 'order' && args[key]) { result.order = [ [args[key]] ]; } }); } return result; }
Fix naming bug that was bombing out lineitem autopopulate
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Objectid = mongoose.Schema.Types.ObjectId; var Organisation = require("./organisation_model"); var Sageitem = require("./sageitem_model"); var SageAnalysisCategory = require("./sageanalysiscategory_model"); var LineItemSchema = new Schema({ description: String, organisation_id: { type: Objectid, ref: 'Organisation' }, item: { type: Objectid, ref: 'Sageitem' }, amount: { type: Number, validate: function(v) { return (v > 0); }, required: true }, price: { type: Number, validate: function(v) { return (v >= 0); }, required: true }, tax_type: String, comment: String, discount: { type: Number, default: 0 }, date_created: { type: Date, default: Date.now }, sage_id: Number, is_quote: Boolean, analysiscategory: { type: Objectid, ref: 'Sageanalysiscategory' }, _owner_id: Objectid, _deleted: { type: Boolean, default: false, index: true }, }); LineItemSchema.set("_perms", { admin: "crud", owner: "cr", user: "", all: "" }); module.exports = mongoose.model('LineItem', LineItemSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Objectid = mongoose.Schema.Types.ObjectId; var Organisation = require("./organisation_model"); var SageItem = require("./sageitem_model"); var SageAnalysisCategory = require("./sageanalysiscategory_model"); var LineItemSchema = new Schema({ description: String, organisation_id: { type: Objectid, ref: 'Organisation' }, item: { type: Objectid, ref: 'SageItem' }, amount: { type: Number, validate: function(v) { return (v > 0); }, required: true }, price: { type: Number, validate: function(v) { return (v >= 0); }, required: true }, tax_type: String, comment: String, discount: { type: Number, default: 0 }, date_created: { type: Date, default: Date.now }, sage_id: Number, is_quote: Boolean, analysiscategory: { type: Objectid, ref: 'SageAnalysisCategory' }, _owner_id: Objectid, _deleted: { type: Boolean, default: false, index: true }, }); LineItemSchema.set("_perms", { admin: "crud", owner: "cr", user: "", all: "" }); module.exports = mongoose.model('LineItem', LineItemSchema);
Change default SimpleMeterRegistry step to 1 minute
/** * Copyright 2017 Pivotal Software, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.micrometer.core.instrument.simple; import io.micrometer.core.instrument.step.StepRegistryConfig; import java.time.Duration; public interface SimpleConfig extends StepRegistryConfig { SimpleConfig DEFAULT = k -> null; // Useful in tests Duration DEFAULT_STEP = Duration.ofMinutes(1); @Override default String prefix() { return "simple"; } /** * Returns the step size (reporting frequency) to use. The default is 10 seconds. */ default Duration step() { String v = get(prefix() + ".step"); return v == null ? DEFAULT_STEP : Duration.parse(v); } }
/** * Copyright 2017 Pivotal Software, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.micrometer.core.instrument.simple; import io.micrometer.core.instrument.step.StepRegistryConfig; import java.time.Duration; public interface SimpleConfig extends StepRegistryConfig { SimpleConfig DEFAULT = k -> null; // Useful in tests Duration DEFAULT_STEP = Duration.ofSeconds(10); @Override default String prefix() { return "simple"; } /** * Returns the step size (reporting frequency) to use. The default is 10 seconds. */ default Duration step() { String v = get(prefix() + ".step"); return v == null ? DEFAULT_STEP : Duration.parse(v); } }
Remove broken contribution to Compatibility service
// Copyright 2012 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.services.compatibility; import org.apache.tapestry5.internal.services.compatibility.CompatibilityImpl; import org.apache.tapestry5.internal.services.compatibility.DeprecationWarningImpl; import org.apache.tapestry5.ioc.ServiceBinder; /** * Defines services for managing compatibility across releases. * * @since 5.4 */ public class CompatibilityModule { public static void bind(ServiceBinder binder) { binder.bind(Compatibility.class, CompatibilityImpl.class); binder.bind(DeprecationWarning.class, DeprecationWarningImpl.class); } }
// Copyright 2012 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.services.compatibility; import org.apache.tapestry5.internal.services.compatibility.CompatibilityImpl; import org.apache.tapestry5.internal.services.compatibility.DeprecationWarningImpl; import org.apache.tapestry5.ioc.Configuration; import org.apache.tapestry5.ioc.ServiceBinder; import org.apache.tapestry5.ioc.annotations.Contribute; /** * Defines services for managing compatibility across releases. * * @since 5.4 */ public class CompatibilityModule { public static void bind(ServiceBinder binder) { binder.bind(Compatibility.class, CompatibilityImpl.class); binder.bind(DeprecationWarning.class, DeprecationWarningImpl.class); } @Contribute(Compatibility.class) public void enableAllCompatibilityTemporarily(Configuration<Trait> configuration) { for (Trait t : Trait.values()) { configuration.add(t); } } }
Fix multiple chat buttons when relaunching the bookmarklet
require('./main.css'); var d = document, _queryS = d.querySelector.bind(d); d.body.classList.add('naugtur'); setInterval(function () { var input = _queryS('.bc-chat-input[disabled]'); if (input) { input.removeAttribute('disabled'); } }, 2000); var _chatButtonId = 'naugtur-chat', _chatButtonMissing = !_queryS('#' + _chatButtonId); if (_chatButtonMissing) { var mybt = d.createElement('i'); mybt.setAttribute('id', _chatButtonId); mybt.setAttribute('class', 'btn btn-large btn-l-gray btn-successz'); mybt.setAttribute('title', 'https://naugtur.github.io/gs-is-for-chat/'); mybt.innerHTML = 'chat'; mybt.addEventListener('click', function () { d.body.classList.toggle('naugtur'); mybt.classList.toggle('btn-success'); }); _queryS('#queue-btns .btn-group').appendChild(mybt); }
require('./main.css'); var d = document, _queryS = d.querySelector.bind(d); var mybt = d.createElement('i'); mybt.setAttribute('class', 'btn btn-large btn-l-gray btn-success'); mybt.setAttribute('title', 'https://naugtur.github.io/gs-is-for-chat/'); mybt.innerHTML = 'chat'; mybt.addEventListener('click', function () { d.body.classList.toggle('naugtur'); mybt.classList.toggle('btn-success'); }); d.body.classList.add('naugtur'); setInterval(function () { var input = _queryS('.bc-chat-input[disabled]'); if (input) { input.removeAttribute('disabled'); } }, 2000); _queryS('#queue-btns .btn-group').appendChild(mybt);
[REFACTOR] Remove "final" keyword on getItems and getDefaultId methods in dynamic list services.
<?php class zone_ListPublishedcountriesService extends BaseService { /** * @var customer_ListTitleService */ private static $instance; private $items = null; /** * @return customer_ListTitleService */ public static function getInstance() { if (is_null(self::$instance)) { self::$instance = self::getServiceClassInstance(get_class()); } return self::$instance; } /** * @return array<list_Item> */ public function getItems() { if ($this->items === null) { $query = zone_CountryService::getInstance()->createQuery(); $query->add(Restrictions::published()); $countries = $query->find(); $ok = array(); foreach ($countries as $country) { $ok[$country->getLabel()] = $country->getId(); } ksort($ok, SORT_LOCALE_STRING); $results = array(); foreach ($ok as $name => $id) { $results[$id] = new list_Item($name, $id); } $this->items = $results; } return $this->items; } /** * @return String */ public function getDefaultId() { $items = $this->getItems(); return f_util_ArrayUtils::firstElement($items)->getValue(); } }
<?php class zone_ListPublishedcountriesService extends BaseService { /** * @var customer_ListTitleService */ private static $instance; private $items = null; /** * @return customer_ListTitleService */ public static function getInstance() { if (is_null(self::$instance)) { self::$instance = self::getServiceClassInstance(get_class()); } return self::$instance; } /** * @return array<list_Item> */ public final function getItems() { if($this->items === null) { $query = zone_CountryService::getInstance()->createQuery(); $query->add(Restrictions::published()); $countries = $query->find(); $ok = array(); foreach ($countries as $country) { $ok[$country->getLabel()] = $country->getId(); } ksort($ok, SORT_LOCALE_STRING); $results = array(); foreach ($ok as $name => $id) { $results[$id] = new list_Item($name, $id); } $this->items = $results; } return $this->items; } /** * @return String */ public final function getDefaultId() { $items = $this->getItems(); return f_util_ArrayUtils::firstElement($items)->getValue(); } }
Fix animation prefix to work with multiple keyframes in one animation
var postcss = require('postcss'); module.exports = postcss.plugin('postcss-prefixer-keyframes', function (opts) { opts = opts || {}; var prefix = opts.prefix || ''; var usedKeyframes = []; return function (css, result) { /* Keyframes */ css.walkAtRules(/keyframes$/, function (keyframes) { usedKeyframes.push(keyframes.params); keyframes.params = String(prefix+keyframes.params); }); css.walkDecls(/animation/, function (decl) { var animations = decl.value.split(','); for (var i=0; i<animations.length; i++) { var animationName = animations[i].trim().split(' '); console.log(animationName[0]); if (usedKeyframes.indexOf(animationName[0]) > -1) { animationName[0] = String(prefix + animationName[0]); } animations[i] = animationName.join(' '); } decl.value = animations.join(','); }); }; });
var postcss = require('postcss'); module.exports = postcss.plugin('postcss-prefixer-keyframes', function (opts) { opts = opts || {}; var prefix = opts.prefix || ''; var usedKeyframes = []; return function (css, result) { /* Keyframes */ css.walkAtRules(/keyframes$/, function (keyframes) { usedKeyframes.push(keyframes.params); keyframes.params = String(prefix+keyframes.params); }); css.walkDecls(/animation/, function (decl) { var animationName = decl.value.split(' '); if (usedKeyframes.indexOf(animationName[0]) > -1) { animationName[0] = String(prefix + animationName[0]); decl.value = animationName.join(' '); } }); }; });
Fix unrelated coding style issue
<?php namespace Nord\Lumen\Elasticsearch\Tests\Search; use Nord\Lumen\Elasticsearch\Search\Sort; use Nord\Lumen\Elasticsearch\Tests\TestCase; /** * Class SortTest * @package Nord\Lumen\Elasticsearch\Tests\Search */ class SortTest extends TestCase { public function testConstructor() { $sort = new Sort([new Sort\ScoreSort()]); $this->assertInstanceOf(Sort\ScoreSort::class, $sort->getSorts()[0]); } /** * Tests setters & getters. */ public function testSetterGetter() { $sort = new Sort(); $sort->setSorts([ (new Sort\FieldSort())->setField('f'), new Sort\ScoreSort(), ]); $this->assertCount(2, $sort->getSorts()); $sort->addSort(new Sort\ScoreSort()); $this->assertCount(3, $sort->getSorts()); } }
<?php namespace Nord\Lumen\Elasticsearch\Tests\Search; use Nord\Lumen\Elasticsearch\Search\Sort; use Nord\Lumen\Elasticsearch\Tests\TestCase; /** * Class SortTest * @package Nord\Lumen\Elasticsearch\Tests\Search */ class SortTest extends TestCase { public function testConstructor() { $sort = new Sort([new Sort\ScoreSort()]); $this->assertInstanceOf(Sort\ScoreSort::class, $sort->getSorts()[0]); } /** * Tests setters & getters. */ public function testSetterGetter() { $sort = new Sort(); $sort->setSorts([ (new Sort\FieldSort())->setField('f'), new Sort\ScoreSort(), ]); $this->assertCount(2, $sort->getSorts()); $sort->addSort(new Sort\ScoreSort()); $this->assertCount(3, $sort->getSorts()); } }
Remove py modules causing GUI lag
""" Distutils script for building cython .c and .so files. Call it with: python setup.py build_ext --inplace """ from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True cy_modules = [ 'board_strip.pyx', 'length_lookup_table.pyx', ] if False: cy_modules.extend([ 'priority_filter.py', 'budget_searcher.py', 'utility_calculator.py', 'utility_stats.py', 'direction_strips.py', 'alpha_beta.py', 'ab_state.py', 'game_state.py', 'board.py', 'ai_player.py', ]) setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
""" Distutils script for building cython .c and .so files. Call it with: python setup.py build_ext --inplace """ from distutils.core import setup from Cython.Build import cythonize #from Cython.Compiler.Options import directive_defaults #directive_defaults['profile'] = True setup( name = "Pentacular", ext_modules = cythonize( [ 'board_strip.pyx', 'length_lookup_table.pyx', 'priority_filter.py', 'budget_searcher.py', 'utility_calculator.py', 'utility_stats.py', 'direction_strips.py', 'alpha_beta.py', 'ab_state.py', 'game_state.py', 'board.py', 'ai_player.py', ], # extra_compile_args=["-O3"], # Is this doing anything? ) )
Add refresh token service method
angular.module('fleetonrails.controllers.login-controller', []) .controller('LoginController', ['$scope', 'LoginService', function ($scope, LoginService) { $scope.login = function () { LoginService.loginWithPassword($scope.user.email, $scope.user.password) .success(function (data, status) { localStorage.setItem("access_token", data.access_token); localStorage.setItem("refresh_token", data.refresh_token); console.log("access_token", localStorage.getItem("access_token")); console.log("refresh_token", localStorage.getItem("refresh_token")); }).error(function (data, status) { console.log('fail', data, status) }); } }]);
angular.module('fleetonrails.controllers.login-controller', []) .controller('LoginController', ['$scope', 'LoginService', function ($scope, LoginService) { $scope.login = function () { LoginService.loginWithPassword($scope.user.email, $scope.user.password) .success(function (data, status) { localStorage.setItem("access_token", data.access_token); localStorage.setItem("refresh_token", data.refresh_token); console.log("access_token", localStorage.getItem("access_token")); console.log("refresh_token", localStorage.getItem("refresh_token")); }).error(function (data, status) { console.log('fail', data, status) });; } }]);
Use new header style in TOC page
@extends('layouts.master') @section('title') Claw &amp; Quill: No. {{ $issue->volnum() }} @endsection @section('content') <header id="header"> <div><a class="image" href="/"><img src="/img/cnq-logo.png" alt="Claw &amp; Quill"></a></div> <h1>No. {{ $issue->volnum() }} &middot; {{ $issue->pub_date->toFormattedDateString() }}</h1> </header> <article class="toc"> @if ($issue->title) <h1>{{ $issue->title }}</h1> @endif @foreach ($issue->storiesSorted() as $story) <h2>{{ HTML::linkAction('IssueController@showStory', $story->title, [$issue->id, $story->slug]) }} <span class="author">{{ $story->author->getPreferredName() }}</span></h2> {{ $story->getBlurb() }} @endforeach </article> <footer class="toc"> <p>{{ HTML::link('/', 'Home') }} &middot; {{ HTML::linkAction('IssueController@getIndex', 'Issue Index') }}</p> <p>Copyright 2013 Claw &amp; Quill</p> </footer> @endsection
@extends('layouts.master') @section('title') Claw &amp; Quill: No. {{ $issue->volnum() }} @endsection @section('content') <header id="header"> <div><a class="image" href="/"><img src="/img/cnq-logo.png" alt="Claw &amp; Quill"></a></div> <h1>No. {{ $issue->volnum() }} &middot; {{ $issue->pub_date->toFormattedDateString() }} @if ($issue->title) <br><span>{{ $issue->title }}</span> @endif </h1> </header> <article class="toc"> @foreach ($issue->storiesSorted() as $story) <h2>{{ HTML::linkAction('IssueController@showStory', $story->title, [$issue->id, $story->slug]) }} <span class="author">{{ $story->author->getPreferredName() }}</span></h2> {{ $story->getBlurb() }} @endforeach </article> <footer class="toc"> <p>{{ HTML::link('/', 'Home') }} &middot; {{ HTML::linkAction('IssueController@getIndex', 'Issue Index') }}</p> <p>Copyright 2013 Claw &amp; Quill</p> </footer> @endsection
Add comments to GenericsPlugin, refactor GenericsPlugin.getSettings to getDataNode
package com.jcwhatever.bukkit.tpregions; import com.jcwhatever.bukkit.generic.GenericsPlugin; import org.bukkit.ChatColor; import org.bukkit.plugin.PluginManager; import com.jcwhatever.bukkit.tpregions.commands.CommandHandler; import com.jcwhatever.bukkit.tpregions.regions.TPRegionManager; public class TPRegions extends GenericsPlugin { private static TPRegions _instance; private TPRegionManager _regionManager; public static TPRegions getInstance() { return _instance; } public TPRegions() { super(); } @Override protected void init() { _instance = this; } @Override protected void onEnablePlugin() { registerListeners(); _regionManager = new TPRegionManager(getDataNode().getNode("regions")); } @Override protected void onDisablePlugin() { } @Override public String getChatPrefix() { return ChatColor.GRAY + "[TPR] " + ChatColor.RESET; } @Override public String getConsolePrefix() { return "[TPR] "; } public TPRegionManager getRegionManager() { return _regionManager; } private void registerListeners() { CommandHandler handler = new CommandHandler(); getCommand("tpr").setExecutor(handler); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new EventListener(), this); } }
package com.jcwhatever.bukkit.tpregions; import com.jcwhatever.bukkit.generic.GenericsPlugin; import org.bukkit.ChatColor; import org.bukkit.plugin.PluginManager; import com.jcwhatever.bukkit.tpregions.commands.CommandHandler; import com.jcwhatever.bukkit.tpregions.regions.TPRegionManager; public class TPRegions extends GenericsPlugin { private static TPRegions _instance; private TPRegionManager _regionManager; public static TPRegions getInstance() { return _instance; } public TPRegions() { super(); } @Override protected void init() { _instance = this; } @Override protected void onEnablePlugin() { registerListeners(); _regionManager = new TPRegionManager(getSettings().getNode("regions")); } @Override protected void onDisablePlugin() { } @Override public String getChatPrefix() { return ChatColor.GRAY + "[TPR] " + ChatColor.RESET; } @Override public String getConsolePrefix() { return "[TPR] "; } public TPRegionManager getRegionManager() { return _regionManager; } private void registerListeners() { CommandHandler handler = new CommandHandler(); getCommand("tpr").setExecutor(handler); PluginManager pm = getServer().getPluginManager(); pm.registerEvents(new EventListener(), this); } }
CAMEL-9723: Move spring-boot-starter-sample to examples so we can collapse the camel-spring-boot-starter module
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.camel; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * A bean that returns a message when you call the {@link #saySomething()} method. * <p/> * Uses <tt>@Component("myBean")</tt> to register this bean with the name <tt>myBean</tt> * that we use in the Camel route to lookup this bean. */ @Component("myBean") public class SampleBean { @Value("${greeting}") private String say; public String saySomething() { return say; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.camel; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * A bean that returns a message when you call the {@link #saySomething()} method. * <p/> * Uses <tt>@Component("myBean")</tt> to register this bean with the name <tt>myBean</tt> * that we use in the Camel route to lookup this bean. */ @Component("myBean") public class SampleBean { @Value("greeting") private String say; public String saySomething() { return say; } }
Comment about the hex part
import glob import os import subprocess """This is used to decompress the news.bin files.""" def decompress(file): with open(file, "rb") as source_file: read = source_file.read() tail = read[320:] with open(file + ".2", "w+") as dest_file: dest_file.write(tail) FNULL = open(os.devnull, "w+") decompress = subprocess.call(["mono", "--runtime=v4.0.30319", "DSDecmp.exe", "-d", file + ".2", file + ".3"], stdout=FNULL, stderr=subprocess.STDOUT) remove = os.remove(file + ".2") move = subprocess.call(["mv", file + ".3", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) open_hex = subprocess.call(["open", "-a", "Hex Fiend", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) // This is to open the news files in the Mac hex editor I use called Hex Fiend. for file in glob.glob("news.bin.*"): if os.path.exists(file): decompress(file) for file in glob.glob("*.bin"): if os.path.exists(file): decompress(file)
import glob import os import subprocess """This is used to decompress the news.bin files.""" def decompress(file): with open(file, "rb") as source_file: read = source_file.read() tail = read[320:] with open(file + ".2", "w+") as dest_file: dest_file.write(tail) FNULL = open(os.devnull, "w+") decompress = subprocess.call(["mono", "--runtime=v4.0.30319", "DSDecmp.exe", "-d", file + ".2", file + ".3"], stdout=FNULL, stderr=subprocess.STDOUT) remove = os.remove(file + ".2") move = subprocess.call(["mv", file + ".3", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) open_hex = subprocess.call(["open", "-a", "Hex Fiend", file + ".2"], stdout=FNULL, stderr=subprocess.STDOUT) for file in glob.glob("news.bin.*"): if os.path.exists(file): decompress(file) for file in glob.glob("*.bin"): if os.path.exists(file): decompress(file)
Add additional spacing to improve readability
#!/usr/bin/python # # Copyright 2016 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import sys import time from log_utils import follow if __name__ == '__main__': # We are expecting two arguments # The first is the name of the script # The second is a path to a log file if len(sys.argv) == 2: # Open our file for reading log_file = open(sys.argv[1], "r") # Create our iterable function log_lines = follow(log_file) # Process the lines as they are appended for line in log_lines: # Strip out the new line an print the line print("{0}".format(line.strip())) else: # Incorrect number of arguments # Output usage to standard out sys.stderr.write("usage: {0} <path>\n".format(os.path.basename(sys.argv[0])))
#!/usr/bin/python # # Copyright 2016 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import sys import time from log_utils import follow if __name__ == '__main__': # We are expecting two arguments # The first is the name of the script # The second is a path to a log file if len(sys.argv) == 2: # Open our file for reading log_file = open(sys.argv[1], "r") # Create our iterable function log_lines = follow(log_file) # Process the lines as they are appended for line in log_lines: # Strip out the new line an print the line print("{0}".format(line.strip())) else: # Incorrect number of arguments # Output usage to standard out sys.stderr.write("usage: {0} <path>\n".format(os.path.basename(sys.argv[0])))
Make translatable text "Supprimier" in image fieldset template
<div class="fieldset-media fieldset-image"> @if($model->$field) <div class="fieldset-preview"> {!! $model->present()->thumb(150, 150, ['resize'], $field) !!} <small class="text-danger delete-attachment" data-table="{{ $model->getTable() }}" data-id="{{ $model->id }}" data-field="{{ $field }}">@lang('global.Delete')</small> </div> @endif <div class="fieldset-field"> {!! BootForm::file(trans('validation.attributes.'.$field), $field) !!} </div> </div>
<div class="fieldset-media fieldset-image"> @if($model->$field) <div class="fieldset-preview"> {!! $model->present()->thumb(150, 150, ['resize'], $field) !!} <small class="text-danger delete-attachment" data-table="{{ $model->getTable() }}" data-id="{{ $model->id }}" data-field="{{ $field }}">Supprimer</small> </div> @endif <div class="fieldset-field"> {!! BootForm::file(trans('validation.attributes.'.$field), $field) !!} </div> </div>
Set iframe styles more easily
/* global tabID */ "use strict"; const existingIframe = document.querySelector("iframe#dom-distiller-result-iframe"); if(existingIframe) { existingIframe.remove(); } else { const iframe = document.createElement("iframe"); iframe.src = chrome.runtime.getURL("dom-distiller/html/dom_distiller_viewer.html") + "#" + tabID; const style = { zIndex: 100000000, position: "fixed", left: 0, right: 0, top: 0, bottom: 0, margin: "auto", width: "100vw", height: "100vh", background: "white", border: "none" }; Object.keys(style).forEach(property => { iframe.style[property] = style[property]; }); document.documentElement.appendChild(iframe); }
/* global tabID */ "use strict"; const existingIframe = document.querySelector("iframe#dom-distiller-result-iframe"); if(existingIframe) { existingIframe.remove(); } else { const iframe = document.createElement("iframe"); iframe.src = chrome.runtime.getURL("dom-distiller/html/dom_distiller_viewer.html") + "#" + tabID; iframe.style.zIndex = 100000000; iframe.style.position = "fixed"; iframe.style.left = 0; iframe.style.right = 0; iframe.style.top = 0; iframe.style.bottom = 0; iframe.style.margin = "auto"; iframe.style.width = "100vw"; iframe.style.height = "100vh"; iframe.style.background = "white"; iframe.style.border = "none"; document.documentElement.appendChild(iframe); }
Fix bug when the input field can't access value
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'input', setupBootstrapDatepicker: function() { var self = this, element = this.$(), value = this.get('value'); element. datepicker({ autoclose: this.get('autoclose') || true, format: this.get('format') || 'dd.mm.yyyy', weekStart: this.get('weekStart') || 1, todayHighlight: this.get('todayHighlight') || false, todayBtn: this.get('todayBtn') || false }). on('changeDate', function(event) { Ember.run(function() { self.didSelectDate(event); }); }); if (value) { element.datepicker('setDate', new Date(value)); }; }.on('didInsertElement'), teardownBootstrapDatepicker: function() { // no-op }.on('willDestroyElement'), didSelectDate: function(event) { var date = this.$().datepicker('getUTCDate'); this.set('value', date.toISOString()); } });
import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'input', setupBootstrapDatepicker: function() { var self = this, element = this.$(); element. datepicker({ autoclose: this.get('autoclose') || true, format: this.get('format') || 'dd.mm.yyyy', weekStart: this.get('weekStart') || 1, todayHighlight: this.get('todayHighlight') || false, todayBtn: this.get('todayBtn') || false }). on('changeDate', function(event) { Ember.run(function() { self.didSelectDate(event); }); }); if (value) { element.datepicker('setDate', new Date(this.get('value'))); }; }.on('didInsertElement'), teardownBootstrapDatepicker: function() { // no-op }.on('willDestroyElement'), didSelectDate: function(event) { var date = this.$().datepicker('getUTCDate'); this.set('value', date.toISOString()); } });
Create EReader object using EClientSocket.createReader()
'''Unit test package for module "tws._EReader".''' __copyright__ = "Copyright (c) 2008 Kevin J Bluck" __version__ = "$Id$" import unittest from StringIO import StringIO from tws import EClientSocket, EReader from test_tws import mock_wrapper class test_EReader(unittest.TestCase): '''Test class "tws.EReader"''' def setUp(self): self.wrapper = mock_wrapper() self.parent = EClientSocket(self.wrapper) self.stream = StringIO() self.reader = self.parent.createReader(self.parent, self.stream) def test_init(self): self.assertTrue(EReader(self.parent, self.stream)) if __debug__: self.assertRaises(AssertionError, EReader, 1, self.stream) self.assertRaises(AssertionError, EReader, self.parent, 1)
'''Unit test package for module "tws._EReader".''' __copyright__ = "Copyright (c) 2008 Kevin J Bluck" __version__ = "$Id$" import unittest from StringIO import StringIO from tws import EClientSocket, EReader from test_tws import mock_wrapper class test_EReader(unittest.TestCase): '''Test class "tws.EReader"''' def setUp(self): self.wrapper = mock_wrapper() self.parent = EClientSocket(self.wrapper) self.stream = StringIO() self.reader = EReader(self.parent, self.stream) def test_init(self): self.assertTrue(EReader(self.parent, self.stream)) if __debug__: self.assertRaises(AssertionError, EReader, 1, self.stream) self.assertRaises(AssertionError, EReader, self.parent, 1)
Test messages created from data arrays
<?php namespace Alchemy\Queue\Tests; use Alchemy\Queue\Message; class MessageTest extends \PHPUnit_Framework_TestCase { public function testMessageHasBody() { $message = new Message('mock-body'); $this->assertEquals('mock-body', $message->getBody()); } public function testMessageHasDefaultCorrelationId() { $message = new Message('mock-body'); $this->assertNotEmpty($message->getCorrelationId(), 'Message should have default correlation ID'); } public function testMessageCorrelationIdCanBeOverridden() { $message = new Message('mock-body', 'mock-correlation-id'); $this->assertEquals('mock-correlation-id', $message->getCorrelationId()); } public function testMessageCreatedFromArrayHasJsonEncodedBody() { $data = ['mock-key'=>'mock-value']; $message = Message::fromArray($data, 'mock-id'); $this->assertEquals('mock-id', $message->getCorrelationId()); $this->assertEquals($data, json_decode($message->getBody(), true)); } }
<?php namespace Alchemy\Queue\Tests; use Alchemy\Queue\Message; class MessageTest extends \PHPUnit_Framework_TestCase { public function testMessageHasBody() { $message = new Message('mock-body'); $this->assertEquals('mock-body', $message->getBody()); } public function testMessageHasDefaultCorrelationId() { $message = new Message('mock-body'); $this->assertNotEmpty($message->getCorrelationId(), 'Message should have default correlation ID'); } public function testMessageCorrelationIdCanBeOverridden() { $message = new Message('mock-body', 'mock-correlation-id'); $this->assertEquals('mock-correlation-id', $message->getCorrelationId()); } }
Use Constants service instead of hardcoded apiRoot
'use strict'; angular.module('scegratooApp') .service('Project', function Project($resource, $http, Constants) { // AngularJS will instantiate a singleton by calling "new" on this function var route = Constants.apiRoot + '/projects/:project.:format' var resource = $resource(route, {format: 'json'}) return { get: function(params, fn) { if (params.file) { var url = [ Constants.apiRoot, 'projects', encodeURI(params.project), encodeURI(params.file) ].join('/') var res = $resource(url, {}, { get: {method: 'GET', transformResponse: function(data) { return {data: data} }} }) return res.get(fn) } else { return resource.get(params, fn) } }, query: resource.query // getFile: function(params) { // var url = [ // apiRoot, // 'projects', // encodeURI(params.project), // encodeURI(params.file) // ].join('/') // return $http.get(url) // } } })
'use strict'; angular.module('scegratooApp') .service('Project', function Project($resource, $http) { // AngularJS will instantiate a singleton by calling "new" on this function var apiRoot = 'api/v1' var route = apiRoot + '/projects/:project.:format' var resource = $resource(route, {format: 'json'}) return { get: function(params, fn) { if (params.file) { var url = [ apiRoot, 'projects', encodeURI(params.project), encodeURI(params.file) ].join('/') var res = $resource(url, {}, { get: {method: 'GET', transformResponse: function(data) { return {data: data} }} }) return res.get(fn) } else { return resource.get(params, fn) } }, query: resource.query // getFile: function(params) { // var url = [ // apiRoot, // 'projects', // encodeURI(params.project), // encodeURI(params.file) // ].join('/') // return $http.get(url) // } } })
Check generated build program is compilable
/* * Bach - Java Shell Builder * Copyright (C) 2020 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach.execution; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import de.sormuras.bach.api.Projects; import org.junit.jupiter.api.Test; import test.base.jdk.Compilation; class BuildTaskGeneratorTests { @Test void checkBuildTaskGenerationForMultiModuleProjectWithTests() { var project = Projects.newProjectWithAllBellsAndWhistles(); var generator = new BuildTaskGenerator(project, true); assertSame(project, generator.project()); assertTrue(generator.verbose()); var program = Snippet.program(generator.get()); try { assertDoesNotThrow(() -> Compilation.compile(program)); } catch (AssertionError e) { program.forEach(System.err::println); throw e; } } }
/* * Bach - Java Shell Builder * Copyright (C) 2020 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach.execution; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import de.sormuras.bach.api.Projects; import org.junit.jupiter.api.Test; class BuildTaskGeneratorTests { @Test void checkBuildTaskGenerationForMultiModuleProjectWithTests() { var project = Projects.newProjectWithAllBellsAndWhistles(); var generator = new BuildTaskGenerator(project, true); assertSame(project, generator.project()); assertTrue(generator.verbose()); var root = generator.get(); var program = Snippet.program(root); assertTrue(program.size() > 10); // program.forEach(System.out::println); } }
Add update API call for classes
classes.$inject = ['$http']; function classes($http) { var url = 'http://fiasps.unitec.edu:' + PORT + '/api/Classes'; var service = { postClass: postClass, update: update, get: get }; return service; function postClass(data, successCallback, errorCallback) { $http.post(url, JSON.stringify(data)) .then(successCallback) .catch(errorCallback); } function get (page, size, success, error) { $http.get(url + '?$top=' + size + '&$skip=' + (page * size) + '&$orderby=Id desc').then(success) .catch(error); } function update (id, data, success, error) { $http.put(url + '/' + id, data) .then(success) .catch(error); } } module.exports = { name: 'classes', srvc: classes };
classes.$inject = ['$http']; function classes($http) { var url = 'http://fiasps.unitec.edu:' + PORT + '/api/Classes'; var service = { postClass: postClass, get: get }; return service; function postClass(data, successCallback, errorCallback) { $http.post(url, JSON.stringify(data)) .then(successCallback) .catch(errorCallback); } function get (page, size, success, error) { $http.get(url + '?$top=' + size + '&$skip=' + (page * size) + '&$orderby=Id desc').then(success) .catch(error); } } module.exports = { name: 'classes', srvc: classes };
Update logic to check for emulator
package com.twotoasters.servos.util; import android.os.Build; public final class DeviceUtils { private DeviceUtils() { } public static boolean isEmulator() { switch (Build.PRODUCT) { case "google_sdk": // fall through case "sdk": // fall through case "sdk_google_phone_x86": // fall through case "sdk_phone_x86": // fall through case "sdk_x86": // fall through case "vbox86p": return true; default: return false; } } }
package com.twotoasters.servos.util; import android.os.Build; public final class DeviceUtils { private DeviceUtils() { } public static boolean isEmulator() { switch (Build.PRODUCT) { case "sdk_phone_x86": // fall through case "google_sdk": // fall through case "sdk": // fall through case "sdk_x86": // fall through case "vbox86p": return true; default: return false; } } }
fix(ts2dart): Adjust to new ts2dart API.
// Transpiles JavaScript and TypeScript code to Dart using ts2dart. var ts2dart = require('ts2dart'); var rundartpackage = require('../build/rundartpackage.js'); module.exports = { 'preprocessor:ts2dart': ['factory', createTs2DartPreprocessor] }; function createTs2DartPreprocessor(logger, basePath, config, emitter) { var log = logger.create('ts2dart'); return function(content, file, done) { try { var moduleName = config.resolveModuleName(file.originalPath); file.path = config.transformPath(file.originalPath); var transpiler = new ts2dart.Transpiler( {failFast: false, generateLibraryName: true, generateSourceMap: true}); var transpiledContent = transpiler.translateFile(file.originalPath, moduleName); // TODO(martinprobst): Source maps. done(null, transpiledContent); } catch (errors) { var errorString; if (errors.forEach) { errors.forEach(function(error) { log.error(error); }); errorString = errors.join('\n'); } else { log.error(errors); errorString = errors; } done(new Error('ts2dart compile errors:\n' + errorString)); } }; } createTs2DartPreprocessor .$inject = ['logger', 'config.basePath', 'config.ts2dartPreprocessor', 'emitter'];
// Transpiles JavaScript and TypeScript code to Dart using ts2dart. var ts2dart = require('ts2dart'); var rundartpackage = require('../build/rundartpackage.js'); module.exports = { 'preprocessor:ts2dart': ['factory', createTs2DartPreprocessor] }; function createTs2DartPreprocessor(logger, basePath, config, emitter) { var log = logger.create('ts2dart'); return function(content, file, done) { try { var moduleName = config.resolveModuleName(file.originalPath); file.path = config.transformPath(file.originalPath); var transpiler = new ts2dart.Transpiler(); var transpiledContent = transpiler.translateFile(file.originalPath, moduleName); // TODO(martinprobst): Source maps. done(null, transpiledContent); } catch (errors) { var errorString; if (errors.forEach) { errors.forEach(function(error) { log.error(error); }); errorString = errors.join('\n'); } else { log.error(errors); errorString = errors; } done(new Error('ts2dart compile errors:\n' + errorString)); } }; } createTs2DartPreprocessor .$inject = ['logger', 'config.basePath', 'config.ts2dartPreprocessor', 'emitter'];
Refactor the Google sna callback since the Facebook one is almost the same
import datetime from pyramid.httpexceptions import HTTPFound from pyramid.security import remember def create_or_update(request, provider, provider_user_id, attributes): provider_key = '%s_id' % provider # Create or update the user user = request.db.users.find_one({provider_key: provider_user_id}) if user is None: # first time user_id = request.db.registered.insert({ provider_key: provider_user_id, "email": attributes["email"], "date": datetime.datetime.utcnow(), "verified": True, "screen_name": attributes["screen_name"], "first_name": attributes["first_name"], "last_name": attributes["last_name"], }, safe=True) else: user_id = user['_id'] # Create an authenticated session and send the user to the # success screeen remember_headers = remember(request, str(user_id)) return HTTPFound(request.route_url('success'), headers=remember_headers) def google_callback(request, user_id, attributes): return create_or_update(request, 'google', user_id, attributes) def facebook_callback(request, user_id, attributes): return create_or_update(request, 'facebook', user_id, attributes)
import datetime from pyramid.httpexceptions import HTTPFound from pyramid.security import remember def google_callback(request, user_id, attributes): """pyramid_sna calls this function aftera successfull authentication flow""" # Create or update the user user = request.db.users.find_one({'google_id': user_id}) if user is None: # first time user_id = request.db.registered.insert({ "email": attributes["email"], "date": datetime.datetime.utcnow(), "verified": True, "screen_name": attributes["screen_name"], "first_name": attributes["first_name"], "last_name": attributes["last_name"], }, safe=True) else: user_id = user['_id'] # Create an authenticated session and send the user to the # success screeen remember_headers = remember(request, str(user_id)) return HTTPFound(request.route_url('success'), headers=remember_headers) def facebook_callback(request, user_id, attributes): pass
Change 'mob' to 'mobs' to comply with PGM docs
package in.twizmwaz.cardinal.module.modules.mob; import in.twizmwaz.cardinal.match.Match; import in.twizmwaz.cardinal.module.ModuleBuilder; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.modules.filter.FilterModuleBuilder; public class MobModuleBuilder implements ModuleBuilder { @Override public ModuleCollection load(Match match) { ModuleCollection<MobModule> results = new ModuleCollection<MobModule>(); if (match.getDocument().getRootElement().getChild("mobs") != null) { results.add(new MobModule(FilterModuleBuilder.getFilter(match.getDocument().getRootElement().getChild("mobs").getChild("filter")))); } else results.add(new MobModule(FilterModuleBuilder.getFilter("deny-all"))); return results; } }
package in.twizmwaz.cardinal.module.modules.mob; import in.twizmwaz.cardinal.match.Match; import in.twizmwaz.cardinal.module.ModuleBuilder; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.modules.filter.FilterModuleBuilder; public class MobModuleBuilder implements ModuleBuilder { @Override public ModuleCollection load(Match match) { ModuleCollection<MobModule> results = new ModuleCollection<MobModule>(); if (match.getDocument().getRootElement().getChild("mob") != null) { results.add(new MobModule(FilterModuleBuilder.getFilter(match.getDocument().getRootElement().getChild("mob").getChild("filter")))); } else results.add(new MobModule(FilterModuleBuilder.getFilter("deny-all"))); return results; } }
Fix case sensitivity issue in test @bug W-3021252@ @rev cheng@
({ testPropertiesExposed: function(cmp) { var testUtils = cmp.get("v.testUtils"); ["appCodeName", "appName", "appVersion", "cookieEnabled", "geolocation", "language", "onLine", "platform", "product", "userAgent"].forEach(function(name) { testUtils.assertTrue(name in window.navigator, "Expected window.navigator." + name + " to be exposed as a property"); }); }, testLanguage: function(cmp) { var testUtils = cmp.get("v.testUtils"); testUtils.assertEquals("en-us", window.navigator.language.toLowerCase(), "Unexpected window.navigator.language value"); } })
({ testPropertiesExposed: function(cmp) { var testUtils = cmp.get("v.testUtils"); ["appCodeName", "appName", "appVersion", "cookieEnabled", "geolocation", "language", "onLine", "platform", "product", "userAgent"].forEach(function(name) { testUtils.assertTrue(name in window.navigator, "Expected window.navigator." + name + " to be exposed as a property"); }); }, testLanguage: function(cmp) { var testUtils = cmp.get("v.testUtils"); testUtils.assertEquals(window.navigator.language, "en-US", "Expect window.navigator.language to be 'en-US'"); } })
Set argv and execPath, gets past web-fs getFile stat undefined
window.staticReadFileSync = function(path) { console.log('readFileSync', path); if (path.match(/^\/file:.*template.js$/)) { // Workaround getting '/file:/Users/admin/games/voxeljs/webnpm/template.js' TODO: underlying bug path = '/node_modules/browserify/node_modules/umd/template.js'; } if (path in window.preloadedReadFileSyncs) { return window.preloadedReadFileSyncs[path]; } console.log('file not found (add to preloadedFilenames list): ',path); return path }; var browserify = require('browserify'); console.log('browserify=',browserify); var Writable = require('stream').Writable; process.stdout = new Writable(); process.stderr = new Writable(); process.stdout.write = function() { console.log.apply(console, arguments); }; process.stderr.write = function() { console.warn.apply(console, arguments); }; process.binding = function() { return {fs: ''} }; process.argv = ['/']; // our executable, because it exists process.execPath = '/'; // matches argv[0] var npm = require('npm'); console.log('npm=',npm); npm.load(); npm.commands.install();
window.staticReadFileSync = function(path) { console.log('readFileSync', path); if (path.match(/^\/file:.*template.js$/)) { // Workaround getting '/file:/Users/admin/games/voxeljs/webnpm/template.js' TODO: underlying bug path = '/node_modules/browserify/node_modules/umd/template.js'; } if (path in window.preloadedReadFileSyncs) { return window.preloadedReadFileSyncs[path]; } console.log('file not found (add to preloadedFilenames list): ',path); return path }; var browserify = require('browserify'); console.log('browserify=',browserify); var Writable = require('stream').Writable; process.stdout = new Writable(); process.stderr = new Writable(); process.stdout.write = function() { console.log.apply(console, arguments); }; process.stderr.write = function() { console.warn.apply(console, arguments); }; process.binding = function() { return {fs: ''} }; process.argv = ['npm']; var npm = require('npm'); console.log('npm=',npm); npm.load(); npm.commands.install();
Revert page filtering by namespace.
package wikipedia; import org.junit.Test; import org.xml.sax.InputSource; import wikipedia.schemas.PageMetadata; import wikipedia.schemas.RevisionContent; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; /** * wikipedia.Wiki2AvroXmlParserTest */ public class Wiki2AvroXmlParserTest { @Test public void test1() throws Wiki2AvroException { String testFile = "/test1.xml"; List<PageMetadata> pages = new ArrayList<>(); List<RevisionContent> revisions = new ArrayList<>(); runTest(testFile, pages, revisions); assertEquals(3, pages.size()); assertEquals(7, revisions.size()); } private void runTest(String testFile, List<PageMetadata> pages, List<RevisionContent> revisions) throws Wiki2AvroException { InputStream inputStream = this.getClass().getResourceAsStream(testFile); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); InputSource inputSource = new InputSource(inputStreamReader); Wiki2AvroOutputStream<PageMetadata> metadataOutputStream = new Wiki2AvroMockOutputStream<>(pages); Wiki2AvroOutputStream<RevisionContent> contentOutputStream = new Wiki2AvroMockOutputStream<>(revisions); Wiki2AvroXmlParser.parse(inputSource, metadataOutputStream, contentOutputStream); } }
package wikipedia; import org.junit.Test; import org.xml.sax.InputSource; import wikipedia.schemas.PageMetadata; import wikipedia.schemas.RevisionContent; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; /** * wikipedia.Wiki2AvroXmlParserTest */ public class Wiki2AvroXmlParserTest { @Test public void test1() throws Wiki2AvroException { String testFile = "/test1.xml"; List<PageMetadata> pages = new ArrayList<>(); List<RevisionContent> revisions = new ArrayList<>(); runTest(testFile, pages, revisions); assertEquals(2, pages.size()); assertEquals(6, revisions.size()); } private void runTest(String testFile, List<PageMetadata> pages, List<RevisionContent> revisions) throws Wiki2AvroException { InputStream inputStream = this.getClass().getResourceAsStream(testFile); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); InputSource inputSource = new InputSource(inputStreamReader); Wiki2AvroOutputStream<PageMetadata> metadataOutputStream = new Wiki2AvroMockOutputStream<>(pages); Wiki2AvroOutputStream<RevisionContent> contentOutputStream = new Wiki2AvroMockOutputStream<>(revisions); Wiki2AvroXmlParser.parse(inputSource, metadataOutputStream, contentOutputStream); } }
Fix typo. when safemode is enabled we experienced the problem with ini_get arguments number
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class Git { public function cleanEnv() { if (ini_get('safe_mode') && false === strpos(ini_get('safe_mode_allowed_env_vars'), 'GIT_ASKPASS')) { throw new \RuntimeException('safe_mode is enabled and safe_mode_allowed_env_vars does not contain GIT_ASKPASS, can not set env var. You can disable safe_mode with "-dsafe_mode=0" when running composer'); } // added in git 1.7.1, prevents prompting the user for username/password if (getenv('GIT_ASKPASS') !== 'echo') { putenv('GIT_ASKPASS=echo'); } // clean up rogue git env vars in case this is running in a git hook if (getenv('GIT_DIR')) { putenv('GIT_DIR'); } if (getenv('GIT_WORK_TREE')) { putenv('GIT_WORK_TREE'); } } }
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class Git { public function cleanEnv() { if (ini_get('safe_mode') && false === strpos(ini_get('safe_mode_allowed_env_vars', 'GIT_ASKPASS'))) { throw new \RuntimeException('safe_mode is enabled and safe_mode_allowed_env_vars does not contain GIT_ASKPASS, can not set env var. You can disable safe_mode with "-dsafe_mode=0" when running composer'); } // added in git 1.7.1, prevents prompting the user for username/password if (getenv('GIT_ASKPASS') !== 'echo') { putenv('GIT_ASKPASS=echo'); } // clean up rogue git env vars in case this is running in a git hook if (getenv('GIT_DIR')) { putenv('GIT_DIR'); } if (getenv('GIT_WORK_TREE')) { putenv('GIT_WORK_TREE'); } } }
Fix code style to fix travis build
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import re version = re.search( r'__version__\s*=\s*[\'"]([^\'"]+)[\'"]', open('wdmapper/version.py').read() ).group(1) setup( name='wdmapper', version=version, description='Wikidata authority file mapping tool', author='Jakob Voß', author_email='jakob.voss@gbv.de', license='MIT', url='http://github.com/gbv/wdmapper', packages=find_packages(), install_requires=['pywikibot'], setup_requires=['pytest-runner'], tests_require=['pytest', 'pytest-pep8', 'pytest-cov'], download_url='https://github.com/gbv/wdmapper/tarball/' + version, keywords=['wikidata', 'beacon', 'identifier'], entry_points={ 'console_scripts': [ 'wdmapper=wdmapper.cli:main' ] } )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import re version = re.search( r'__version__\s*=\s*[\'"]([^\'"]+)[\'"]', open('wdmapper/version.py').read() ).group(1) setup( name='wdmapper', version=version, description='Wikidata authority file mapping tool', author='Jakob Voß', author_email='jakob.voss@gbv.de', license='MIT', url='http://github.com/gbv/wdmapper', packages=find_packages(), install_requires=['pywikibot'], setup_requires=['pytest-runner'], tests_require=['pytest', 'pytest-pep8', 'pytest-cov'], download_url = 'https://github.com/gbv/wdmapper/tarball/' + version, keywords = ['wikidata', 'beacon', 'identifier'], entry_points={ 'console_scripts': [ 'wdmapper=wdmapper.cli:main' ] } )
Update DB to use PHP MySQLi extensions class.db.php has been updated to utilise MySQLi extenstions (as I should be using)
<?php // RadioPanel - Database class // (C) Matt Ribbins - matt@mattyribbo.co.uk // class Database { var $conn; var $database; protected $_config; public function __construct($config) { $this->_config = $config; } public function connect() { $this->conn = new mysqli($this->_config['host'], $this->_config['username'], $this->_config['password'], $this->_config['database']); if ($this->conn->connect_error) { trigger_error('Database connection failed: ' . $this->conn->connect_error, E_USER_ERROR); return false; } return true; } public function query($sql, $associative=false) { $result = $this->conn->query($sql); if($associative) return mysql_fetch_assoc($result); return $result; } public function disconnect() { $this->conn->close(); return; } } ?>
<?php // RadioPanel - Database class // (C) Matt Ribbins - matt@mattyribbo.co.uk // class Database { var $conn; var $database; protected $_config; public function __construct($config) { $this->_config = $config; } public function connect() { $this->conn = mysql_connect($this->_config['host'], $this->_config['username'], $this->_config['password']); if(!$this->conn) { echo "<span style=\"color: red\">Error: Cannot connect to MySQL server. ".mysql_error()."</span><br />"; return false; } mysql_select_db($this->_config['database']); return true; } public function query($sql, $associative=false) { mysql_select_db($this->database); $result = mysql_query($sql, $this->conn) or die(mysql_error()); if($associative) return mysql_fetch_assoc($result); return $result; } public function disconnect() { mysql_close($this->conn); return; } } ?>
Fix missing preventDefault on links in exam timetable
define(['backbone.marionette', 'app', 'hbs!../templates/exam'], function (Marionette, App, template) { 'use strict'; return Marionette.ItemView.extend({ tagName: 'tr', template: template, events: { 'click .remove': function (event) { event.preventDefault(); App.request('removeModule', this.model.id); }, 'click .show-hide': function (event) { event.preventDefault(); var display = !this.model.get('display'); this.model.set('display', display); App.request('displayLessons', this.model.id, display); } }, modelEvents: { change: 'render' }, onRender: function () { this.$el.addClass('color' + this.model.get('color')) .toggleClass('clash', this.model.get('clash')); } }); });
define(['backbone.marionette', 'app', 'hbs!../templates/exam'], function (Marionette, App, template) { 'use strict'; return Marionette.ItemView.extend({ tagName: 'tr', template: template, events: { 'click .remove': function () { App.request('removeModule', this.model.id); }, 'click .show-hide': function () { var display = !this.model.get('display'); this.model.set('display', display); App.request('displayLessons', this.model.id, display); } }, modelEvents: { change: 'render' }, onRender: function () { this.$el.addClass('color' + this.model.get('color')) .toggleClass('clash', this.model.get('clash')); } }); });
Add a reminder to remove Route.interface field Nova never sets the Route.interface value to anything but None which fails with an error: "ValueError: Fieldinterface' cannot be None" This looks like a carry-over from the nova.network.model.Route class which has an interface field which is set to None by default but that field is never set to anything else in Nova, neither for nova-network or Neutron. Furthermore, it looks like 'interface' is not something that's in the Route data model in Neutron either. We don't hit this in the gate because the subnets we're testing with don't have host_routes set. The ValueError was fixed in Nova by not setting the attribute: 1d57c1fd53e930b02c3ce0e9914f95ef68dd1f87 This change adds a TODO to remove it in version 2.0 of the Route object. Change-Id: Ib25a79514fe4335f4df222c02fefc9da62fe04ce Closes-Bug: #1612812
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base @base.VersionedObjectRegistry.register class Route(osv_base.VersionedObject): """Represents a route.""" # Version 1.0: Initial version VERSION = '1.0' fields = { 'cidr': fields.IPNetworkField(), 'gateway': fields.IPAddressField(), # TODO(mriedem): This field is never set by Nova, remove it in v2.0 # of this object. 'interface': fields.StringField(), } @base.VersionedObjectRegistry.register class RouteList(osv_base.VersionedObject, base.ObjectListBase): # Version 1.0: Initial version VERSION = '1.0' fields = { 'objects': fields.ListOfObjectsField('Route'), }
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_versionedobjects import base from oslo_versionedobjects import fields from os_vif.objects import base as osv_base @base.VersionedObjectRegistry.register class Route(osv_base.VersionedObject): """Represents a route.""" # Version 1.0: Initial version VERSION = '1.0' fields = { 'cidr': fields.IPNetworkField(), 'gateway': fields.IPAddressField(), 'interface': fields.StringField(), } @base.VersionedObjectRegistry.register class RouteList(osv_base.VersionedObject, base.ObjectListBase): # Version 1.0: Initial version VERSION = '1.0' fields = { 'objects': fields.ListOfObjectsField('Route'), }
Add javadoc for configuration factory
package com.google.configuration; /** Retrieves the project configuration details. */ public final class ConfigurationFactory { private enum ProjectStatus { DEVELOPMENT, TEST, PRODUCTION } private static final ProjectStatus projectStatus = ProjectStatus.DEVELOPMENT; /** * Gets the configuration of the cloud firestore. * * @return Configuration details * @throws UnsupportedOperationException Cloud Firestore database is not created yet. */ public static final FireStoreConfiguration getFireStoreConfiguration() throws UnsupportedOperationException { FireStoreConfiguration fireStoreConfiguration = null; switch (projectStatus) { case PRODUCTION: case TEST: throw new UnsupportedOperationException("Not implemented"); case DEVELOPMENT: fireStoreConfiguration = DevelopmentFireStoreConfiguration.getFireStoreConfiguration(); break; } return fireStoreConfiguration; } }
package com.google.configuration; /** Retrieves the project configuration details. */ public final class ConfigurationFactory { private enum ProjectStatus { DEVELOPMENT, TEST, PRODUCTION } private static final ProjectStatus projectStatus = ProjectStatus.DEVELOPMENT; /** * * @return * @throws UnsupportedOperationException */ public static final FireStoreConfiguration getFireStoreConfiguration() throws UnsupportedOperationException { FireStoreConfiguration fireStoreConfiguration = null; switch (projectStatus) { case PRODUCTION: case TEST: throw new UnsupportedOperationException("Not implemented"); case DEVELOPMENT: fireStoreConfiguration = DevelopmentFireStoreConfiguration.getFireStoreConfiguration(); break; } return fireStoreConfiguration; } }
Add static builder taking port and path
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.container.component; /** * A {@link BindingPattern} which is implicitly constructed by the model, e.g for built-in handlers and filter chains. * * @author bjorncs */ public class SystemBindingPattern extends BindingPattern { private SystemBindingPattern(String scheme, String host, String port, String path) { super(scheme, host, port, path); } private SystemBindingPattern(String binding) { super(binding); } public static SystemBindingPattern fromHttpPath(String path) { return new SystemBindingPattern("http", "*", null, path);} public static SystemBindingPattern fromPattern(String binding) { return new SystemBindingPattern(binding);} public static SystemBindingPattern fromPortAndPath(String port, String path) { return new SystemBindingPattern("http", "*", port, path); } @Override public String toString() { return "SystemBindingPattern{" + "scheme='" + scheme() + '\'' + ", host='" + host() + '\'' + ", port='" + port().orElse(null) + '\'' + ", path='" + path() + '\'' + '}'; } }
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.container.component; /** * A {@link BindingPattern} which is implicitly constructed by the model, e.g for built-in handlers and filter chains. * * @author bjorncs */ public class SystemBindingPattern extends BindingPattern { private SystemBindingPattern(String scheme, String host, String port, String path) { super(scheme, host, port, path); } private SystemBindingPattern(String binding) { super(binding); } public static SystemBindingPattern fromHttpPath(String path) { return new SystemBindingPattern("http", "*", null, path);} public static SystemBindingPattern fromPattern(String binding) { return new SystemBindingPattern(binding);} @Override public String toString() { return "SystemBindingPattern{" + "scheme='" + scheme() + '\'' + ", host='" + host() + '\'' + ", port='" + port().orElse(null) + '\'' + ", path='" + path() + '\'' + '}'; } }
Update the PyPI version to 0.2.22.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.22', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.21', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Select chosen stylesheet on load
/* * style-select.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/style-select.js * * Changes the stylesheet chooser links to a <select> * * Released under the MIT license * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/style-select.js'; * */ onready(function(){ var stylesDiv = $('div.styles'); var stylesSelect = $('<select></select>'); var i = 1; stylesDiv.children().each(function() { var opt = $('<option></option>') .text(this.innerText.replace(/(^\[|\]$)/g, '')) .val(i); if ($(this).hasClass('selected')) opt.attr('selected', true); stylesSelect.append(opt); $(this).attr('id', 'style-select-' + i); i++; }); stylesSelect.change(function() { $('#style-select-' + $(this).val()).click(); }); stylesDiv.hide(); stylesDiv.after( $('<div style="float:right;margin-bottom:10px"></div>') .text(_('Style: ')) .append(stylesSelect) ); });
/* * style-select.js * https://github.com/savetheinternet/Tinyboard/blob/master/js/style-select.js * * Changes the stylesheet chooser links to a <select> * * Released under the MIT license * Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org> * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/style-select.js'; * */ onready(function(){ var stylesDiv = $('div.styles'); var stylesSelect = $('<select></select>'); var i = 1; stylesDiv.children().each(function() { stylesSelect.append( $('<option></option>') .text(this.innerText.replace(/(^\[|\]$)/g, '')) .val(i) ); $(this).attr('id', 'style-select-' + i); i++; }); stylesSelect.change(function() { $('#style-select-' + $(this).val()).click(); }); stylesDiv.hide(); stylesDiv.after( $('<div style="float:right;margin-bottom:10px"></div>') .text(_('Style: ')) .append(stylesSelect) ); });
Change email to mail in LDAP
from django.contrib.auth import get_user_model import ldap User = get_user_model() class UChicagoLDAPBackend(object): LDAP_SERVER = "ldaps://ldap.uchicago.edu:636" def authenticate(self, cnetid=None, password=None): if cnetid and password: cnetid = ldap.filter.escape_filter_chars(cnetid) try: conn.simple_bind_s("uid=%s,ou=people,dc=uchicago,dc=edu" % cnetid, password) except ldap.INVALID_CREDENTIALS: return None try: user = User.objects.get(username=cnetid) except User.DoesNotExist: query = "(&(uid=%s)(objectclass=inetOrgPerson))" % (cnetid) result = conn.search_ext_s("dc=uchicago,dc=edu", ldap.SCOPE_SUBTREE, query) if result: user_data = result[0] user = User.objects.create_user(username=cnetid, email=user_data['mail'], first_name=user_data['givenName'], last_name=user_data['sn']) return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
from django.contrib.auth import get_user_model import ldap User = get_user_model() class UChicagoLDAPBackend(object): LDAP_SERVER = "ldaps://ldap.uchicago.edu:636" def authenticate(self, cnetid=None, password=None): if cnetid and password: cnetid = ldap.filter.escape_filter_chars(cnetid) try: conn.simple_bind_s("uid=%s,ou=people,dc=uchicago,dc=edu" % cnetid, password) except ldap.INVALID_CREDENTIALS: return None try: user = User.objects.get(username=cnetid) except User.DoesNotExist: query = "(&(uid=%s)(objectclass=inetOrgPerson))" % (cnetid) result = conn.search_ext_s("dc=uchicago,dc=edu", ldap.SCOPE_SUBTREE, query) if result: user_data = result[0] user = User.objects.create_user(username=cnetid, email=user_data['email'], first_name=user_data['givenName'], last_name=user_data['sn']) return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
Replace dependency to PSR container.
<?php namespace Limoncello\Application\Contracts; /** * Copyright 2015-2017 info@neomerx.com * * 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. */ use Closure; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * @package Limoncello\Application */ interface MiddlewareInterface { /** * Configurator's method name. */ const METHOD_NAME = 'handle'; /** * @param ServerRequestInterface $request * @param Closure $next * @param ContainerInterface $container * * @return ResponseInterface */ public static function handle( ServerRequestInterface $request, Closure $next, ContainerInterface $container ): ResponseInterface; }
<?php namespace Limoncello\Application\Contracts; /** * Copyright 2015-2017 info@neomerx.com * * 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. */ use Closure; use Limoncello\Contracts\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * @package Limoncello\Application */ interface MiddlewareInterface { /** * Configurator's method name. */ const METHOD_NAME = 'handle'; /** * @param ServerRequestInterface $request * @param Closure $next * @param ContainerInterface $container * * @return ResponseInterface */ public static function handle( ServerRequestInterface $request, Closure $next, ContainerInterface $container ): ResponseInterface; }
Add url and baseUrl to error messages Add the url and baseUrl to the error messages inside `parseUrl`. This should help debug where these errors originated.
/** * Exports `parseUrl` for, well, parsing URLs! */ import urlParse from 'url-parse'; const schemeMatcher = /^([a-zA-Z]*\:)?\/\//; const hasScheme = url => { if (typeof url !== 'string') { return false; } return schemeMatcher.test(url); }; const parseUrl = (url = '', baseUrl) => { if (!hasScheme(url)) { if (!hasScheme(baseUrl)) { throw new Error( `Must provide scheme in url or baseUrl to parse. \`url\` provided: ${url}. \`baseUrl\` provided: ${baseUrl}.` ); } } if (!hasScheme(url)) { if (url[0] !== '/') { throw new Error( `Only absolute URLs are currently supported. \`url\` provided: ${url}` ); } } const urlObj = urlParse(url, baseUrl); return { protocol: urlObj.protocol, host: urlObj.host, hostname: urlObj.hostname, port: urlObj.port, pathname: urlObj.pathname, hash: urlObj.hash, search: urlObj.query, origin: urlObj.host ? (urlObj.protocol + '//' + urlObj.host) : '', href: urlObj.href }; }; export default parseUrl;
/** * Exports `parseUrl` for, well, parsing URLs! */ import urlParse from 'url-parse'; const schemeMatcher = /^([a-zA-Z]*\:)?\/\//; const hasScheme = url => { if (typeof url !== 'string') { return false; } return schemeMatcher.test(url); }; const parseUrl = (url = '', baseUrl) => { if (!hasScheme(url)) { if (!hasScheme(baseUrl)) { throw new Error('Must provide scheme in url or baseUrl to parse.'); } } if (!hasScheme(url)) { if (url[0] !== '/') { throw new Error('Only absolute URLs are currently supported.'); } } const urlObj = urlParse(url, baseUrl); return { protocol: urlObj.protocol, host: urlObj.host, hostname: urlObj.hostname, port: urlObj.port, pathname: urlObj.pathname, hash: urlObj.hash, search: urlObj.query, origin: urlObj.host ? (urlObj.protocol + '//' + urlObj.host) : '', href: urlObj.href }; }; export default parseUrl;
Handle error if file not exists
package com.hivedi.statfscompat; import android.os.Build; import android.os.StatFs; import java.io.File; /** * Created by Hivedi2 on 2015-11-24. * */ public class StatFsCompat { public static final long STAT_FS_ERROR = -1L; @SuppressWarnings("deprecation") public static long getStatFsTotal(File f) { try { StatFs statFs = new StatFs(f.getAbsolutePath()); if (Build.VERSION.SDK_INT >= 18) { return statFs.getTotalBytes(); } else { return statFs.getBlockCount() * statFs.getBlockSize(); } } catch (IllegalArgumentException e) { return STAT_FS_ERROR; } } @SuppressWarnings("deprecation") public static long getStatFsFree(File f) { try { StatFs statFs = new StatFs(f.getAbsolutePath()); if (Build.VERSION.SDK_INT >= 18) { return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong(); } else { return statFs.getAvailableBlocks() * (long) statFs.getBlockSize(); } } catch (IllegalArgumentException e) { return STAT_FS_ERROR; } } }
package com.hivedi.statfscompat; import android.os.Build; import android.os.StatFs; import java.io.File; /** * Created by Hivedi2 on 2015-11-24. * */ public class StatFsCompat { @SuppressWarnings("deprecation") public static long getStatFsTotal(File f) { StatFs statFs = new StatFs(f.getAbsolutePath()); if (Build.VERSION.SDK_INT >= 18) { return statFs.getTotalBytes(); } else { return statFs.getBlockCount() * statFs.getBlockSize(); } } @SuppressWarnings("deprecation") public static long getStatFsFree(File f) { StatFs statFs = new StatFs(f.getAbsolutePath()); if (Build.VERSION.SDK_INT >= 18) { return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong(); } else { return statFs.getAvailableBlocks() * (long) statFs.getBlockSize(); } } }
Remove unused injected $interval service
angular.module("hyperContentFor", []) .value("HYPER_CONTENT_FOR_IDS", { }) .directive("hyperContent", function () { return { scope: { "for": "@" }, restrict: "E", transclude: true, controller: function ($scope, $transclude, HYPER_CONTENT_FOR_IDS) { HYPER_CONTENT_FOR_IDS[$scope["for"]] = $transclude(); } }; }) .directive("hyperYield", function (HYPER_CONTENT_FOR_IDS) { return { scope: { to: "@" }, restrict: "E", link: function (scope, elem) { interval = null; watchFn = function () { return HYPER_CONTENT_FOR_IDS[scope.to]; }; scope.$watch(watchFn, function (newValue) { elem.empty(); elem.append(newValue); }); } }; });
angular.module("hyperContentFor", []) .value("HYPER_CONTENT_FOR_IDS", { }) .directive("hyperContent", function () { return { scope: { "for": "@" }, restrict: "E", transclude: true, controller: function ($scope, $transclude, HYPER_CONTENT_FOR_IDS) { HYPER_CONTENT_FOR_IDS[$scope["for"]] = $transclude(); } }; }) .directive("hyperYield", function ($interval, HYPER_CONTENT_FOR_IDS) { return { scope: { to: "@" }, restrict: "E", link: function (scope, elem) { interval = null; watchFn = function () { return HYPER_CONTENT_FOR_IDS[scope.to]; }; scope.$watch(watchFn, function (newValue) { elem.empty(); elem.append(newValue); }); } }; });
Use verbose gc logging for logserver-container
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.container.handler.ThreadpoolConfig; import com.yahoo.search.config.QrStartConfig; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.component.Handler; /** * @author hmusum */ public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> { public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) { super(parent, name, name, deployState); addDefaultHandlersWithVip(); addLogHandler(); } @Override protected void doPrepare(DeployState deployState) { } @Override public void getConfig(ThreadpoolConfig.Builder builder) { builder.maxthreads(10); } @Override public void getConfig(QrStartConfig.Builder builder) { super.getConfig(builder); builder.jvm.heapsize(384) .verbosegc(true); } protected boolean messageBusEnabled() { return false; } private void addLogHandler() { Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS); logHandler.addServerBindings("http://*/logs"); addComponent(logHandler); } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.container.handler.ThreadpoolConfig; import com.yahoo.search.config.QrStartConfig; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.component.Handler; /** * @author hmusum */ public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> { public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) { super(parent, name, name, deployState); addDefaultHandlersWithVip(); addLogHandler(); } @Override protected void doPrepare(DeployState deployState) { } @Override public void getConfig(ThreadpoolConfig.Builder builder) { builder.maxthreads(10); } @Override public void getConfig(QrStartConfig.Builder builder) { super.getConfig(builder); builder.jvm.heapsize(384); } protected boolean messageBusEnabled() { return false; } private void addLogHandler() { Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS); logHandler.addServerBindings("http://*/logs"); addComponent(logHandler); } }
Use six for correct Python2/3 compatibility
import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, six.string_types): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, })
from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, (str, bytes)): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, })
Revert "snowflake - odbc drivers update" This reverts commit 4532642aba3a1e691d4ca1d8636d9b185d50dcf9.
<?php /** * Loads test fixtures into S3 */ date_default_timezone_set('Europe/Prague'); ini_set('display_errors', true); error_reporting(E_ALL); $basedir = dirname(__DIR__); require_once $basedir . '/vendor/autoload.php'; $client = new \Aws\S3\S3Client([ 'region' => 'us-east-1', 'version' => '2006-03-01', 'credentials' => [ 'key' => getenv('AWS_ACCESS_KEY'), 'secret' => getenv('AWS_SECRET_KEY'), ], ]); $client->getObject([ 'Bucket' => 'keboola-configs', 'Key' => 'drivers/snowflake/snowflake_linux_x8664_odbc.2.12.75.tgz', 'SaveAs' => './snowflake_linux_x8664_odbc.tgz' ]);
<?php /** * Loads test fixtures into S3 */ date_default_timezone_set('Europe/Prague'); ini_set('display_errors', true); error_reporting(E_ALL); $basedir = dirname(__DIR__); require_once $basedir . '/vendor/autoload.php'; $client = new \Aws\S3\S3Client([ 'region' => 'us-east-1', 'version' => '2006-03-01', 'credentials' => [ 'key' => getenv('AWS_ACCESS_KEY'), 'secret' => getenv('AWS_SECRET_KEY'), ], ]); $client->getObject([ 'Bucket' => 'keboola-configs', 'Key' => 'drivers/snowflake/snowflake_linux_x8664_odbc.2.12.76.tgz', 'SaveAs' => './snowflake_linux_x8664_odbc.tgz' ]);
Support visiting unknown nodes in SectNumFolder and SectRefExpander
import docutils class SectNumFolder(docutils.nodes.SparseNodeVisitor): def __init__(self, document): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = {} def visit_generated(self, node): for i in node.parent.parent['ids']: self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ') def unknown_visit(self, node): pass class SectRefExpander(docutils.nodes.SparseNodeVisitor): def __init__(self, document, sectnums): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = sectnums def visit_reference(self, node): if node.get('refid', None) in self.sectnums: node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])] def unknown_visit(self, node): pass
import docutils class SectNumFolder(docutils.nodes.SparseNodeVisitor): def __init__(self, document): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = {} def visit_generated(self, node): for i in node.parent.parent['ids']: self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ') class SectRefExpander(docutils.nodes.SparseNodeVisitor): def __init__(self, document, sectnums): docutils.nodes.SparseNodeVisitor.__init__(self, document) self.sectnums = sectnums def visit_reference(self, node): if node.get('refid', None) in self.sectnums: node.children=[docutils.nodes.Text('%s '%self.sectnums[node.get('refid')])]
Use temporary var to avoid array item lookup
'use strict'; module.exports.getValidUrl = (urls) => { for (var i = 0, l = urls.length; i < l; ++i) { var url = urls[i]; if (url && typeof url === 'string' && (url.indexOf('amqp://') === 0 || url.indexOf('amqps://') === 0)) { return url; } } return 'amqp://localhost'; }; module.exports.pushIfNotExist = (array, value) => { for (var i = 0, l = array.length; i < l; ++i) { if (array[i].queue === value.queue) { return array; } } array.push(value); return array; }; module.exports.timeoutPromise = (timer) => { return new Promise((resolve) => { setTimeout(resolve, timer); }); };
'use strict'; module.exports.getValidUrl = (_urls) => { for (var i = 0, l = _urls.length; i < l; ++i) { if (_urls[i] && typeof _urls[i] === 'string' && (_urls[i].indexOf('amqp://') === 0 || _urls[i].indexOf('amqps://') === 0)) { return _urls[i]; } } return 'amqp://localhost'; }; module.exports.pushIfNotExist = (array, value) => { for (var i = 0, l = array.length; i < l; ++i) { if (array[i].queue === value.queue) { return array; } } array.push(value); return array; }; module.exports.timeoutPromise = (timer) => { return new Promise((resolve) => { setTimeout(resolve, timer); }); };
Rename variables for optimal readability The variable names in the spec are a bit cryptic.
/*! http://mths.be/array-of v0.1.0 by @mathias */ if (!Array.of) { (function() { var isConstructor = function(Constructor) { try { new Constructor(); return true; } catch(_) { return false; } }; var of = function() { var items = arguments; var length = items.length; var Me = this; var result = isConstructor(Me) ? new Me(length) : new Array(length); var index = 0; var value; while (index < length) { value = items[index]; result[index] = value; ++index; } return result; }; if (Object.defineProperty) { Object.defineProperty(Array, 'of', { 'value': of, 'configurable': true, 'writable': true }); } else { Array.of = of; } }()); }
/*! http://mths.be/array-of v0.1.0 by @mathias */ if (!Array.of) { (function() { var isConstructor = function(Constructor) { try { new Constructor(); return true; } catch(_) { return false; } }; var of = function() { var items = arguments; var len = items.length; var C = this; var A = isConstructor(C) ? new C(len) : new Array(len); var k = 0; while (k < len) { var kValue = items[k]; A[k] = kValue; ++k; } return A; }; if (Object.defineProperty) { Object.defineProperty(Array, 'of', { 'value': of, 'configurable': true, 'writable': true }); } else { Array.of = of; } }()); }
Allow user remove uploaded image
(function ($) { $(window).load(function(){ var store = window.hologram.store; window.hologram(document.getElementsByClassName('hologram-area')[0], { uploadUrl: Drupal.settings.Hologram.uploadUrl, onComplete: function(result){ var files = []; result['response'].forEach(function(response){ var result = response['text']; result = JSON.parse(result); files.push(result); }); var json = JSON.stringify(files); $('#hologram-image-data').val(json); }, config: { uploader: '/hologram/upload' }, }); //Push exist images to holgoram widget try{ var files = $('#hologram-image-data').val(); if(files){ files = JSON.parse(files); store.dispatch(window.hologram.addFiles(files)); } }catch(ex){ console.log(ex); } store.subscribe(function(){ var files = store.getState().files; var json = JSON.stringify(files); $('#hologram-image-data').val(json); }); }); })(jQuery);
(function ($) { $(window).load(function(){ var store = window.hologram.store; window.hologram(document.getElementsByClassName('hologram-area')[0], { uploadUrl: Drupal.settings.Hologram.uploadUrl, onComplete: function(result){ var json = JSON.stringify(result); $('#hologram-image-data').val(json); }, config: { uploader: '/hologram/upload' }, }); //Push exist images to holgoram widget try{ var files = $('#hologram-image-data').val(); if(files){ files = JSON.parse(files); store.dispatch(window.hologram.addFiles(files)); } }catch(ex){ console.log(ex); } store.subscribe(function(){ var files = store.getState().files; var json = JSON.stringify(files); $('#hologram-image-data').val(json); }); }); })(jQuery);
Stop direct access to the list of args, allow them to be streamed instead.
package uk.ac.ebi.quickgo.rest.search.query; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * Holds the data required to specify a filter value * * @author Tony Wardell * Date: 03/05/2016 * Time: 10:25 * Created with IntelliJ IDEA. */ public class PrototypeFilter { private static final String COMMA = ","; private String filterField; private List<String> args; private Validator<String> validator; public String getFilterField() { return filterField; } public static final PrototypeFilter create(String filterField, String argIncludingDelimiters, Validator<String> validator ){ PrototypeFilter prototypeFilter = new PrototypeFilter(); prototypeFilter.filterField = filterField; prototypeFilter.args = Arrays.asList(argIncludingDelimiters.split(COMMA)); prototypeFilter.validator = validator; return prototypeFilter; } /** * * Test each argument in the list to see if its valid */ public void validate(){ args.stream().forEach(a -> validator.validate(a)); } public Stream<String> provideStream(){ return args.stream(); } }
package uk.ac.ebi.quickgo.rest.search.query; import java.util.Arrays; import java.util.List; /** * Holds the data required to specify a filter value * * @author Tony Wardell * Date: 03/05/2016 * Time: 10:25 * Created with IntelliJ IDEA. */ public class PrototypeFilter { private static final String COMMA = ","; private String filterField; private List<String> args; private Validator<String> validator; public String getFilterField() { return filterField; } public List<String> getArgs() { return args; } public static final PrototypeFilter create(String filterField, String argIncludingDelimiters, Validator<String> validator ){ PrototypeFilter prototypeFilter = new PrototypeFilter(); prototypeFilter.filterField = filterField; prototypeFilter.args = Arrays.asList(argIncludingDelimiters.split(COMMA)); prototypeFilter.validator = validator; return prototypeFilter; } /** * * Test each argument in the list to see if its valid */ public void validate(){ args.stream().forEach(a -> validator.validate(a)); } }
Remove prototype manager controller routes
<?php namespace Mapbender\DataSourceBundle; use Mapbender\CoreBundle\Component\MapbenderBundle; /** * DataSource Bundle. * y * @author Andriy Oblivantsev */ class MapbenderDataSourceBundle extends MapbenderBundle { /** * @inheritdoc */ public function getElements() { return array( 'Mapbender\DataSourceBundle\Element\DataManagerElement', 'Mapbender\DataSourceBundle\Element\QueryBuilderElement' ); } ///** // * @inheritdoc // */ //public function getManagerControllers() //{ // $trans = $this->container->get('translator'); // return array( // array( // 'weight' => 20, // 'title' => $trans->trans("DataStores"), // 'route' => 'mapbender_datasource_datastore_index', // 'routes' => array( // 'mapbender_datasource_datastore', // ), // ) // ); //} }
<?php namespace Mapbender\DataSourceBundle; use Mapbender\CoreBundle\Component\MapbenderBundle; /** * DataSource Bundle. * y * @author Andriy Oblivantsev */ class MapbenderDataSourceBundle extends MapbenderBundle { /** * @inheritdoc */ public function getElements() { return array( 'Mapbender\DataSourceBundle\Element\DataManagerElement', 'Mapbender\DataSourceBundle\Element\QueryBuilderElement' ); } /** * @inheritdoc */ public function getManagerControllers() { $trans = $this->container->get('translator'); return array( array( 'weight' => 20, 'title' => $trans->trans("DataStores"), 'route' => 'mapbender_datasource_datastore_index', 'routes' => array( 'mapbender_datasource_datastore', ), ) ); } }
[AC-8296] Change field type for answer_text
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from django.db import models from django.utils.encoding import python_2_unicode_compatible from accelerator_abstract.models.accelerator_model import AcceleratorModel @python_2_unicode_compatible class BaseApplicationAnswer(AcceleratorModel): application = models.ForeignKey(to=swapper.get_model_name( AcceleratorModel.Meta.app_label, "Application"), on_delete=models.CASCADE) application_question = models.ForeignKey(swapper.get_model_name( AcceleratorModel.Meta.app_label, 'ApplicationQuestion'), on_delete=models.CASCADE) answer_text = models.TextField(blank=True) class Meta(AcceleratorModel.Meta): verbose_name_plural = 'Application Answers' db_table = '{}_applicationanswer'.format( AcceleratorModel.Meta.app_label) abstract = True unique_together = ('application', 'application_question') def __str__(self): return "Answer to question %s from %s" % ( self.application_question.question_number, self.application.startup.name)
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from django.db import models from django.utils.encoding import python_2_unicode_compatible from accelerator_abstract.models.accelerator_model import AcceleratorModel @python_2_unicode_compatible class BaseApplicationAnswer(AcceleratorModel): application = models.ForeignKey(to=swapper.get_model_name( AcceleratorModel.Meta.app_label, "Application"), on_delete=models.CASCADE) application_question = models.ForeignKey(swapper.get_model_name( AcceleratorModel.Meta.app_label, 'ApplicationQuestion'), on_delete=models.CASCADE) answer_text = models.CharField(max_length=2000, blank=True) class Meta(AcceleratorModel.Meta): verbose_name_plural = 'Application Answers' db_table = '{}_applicationanswer'.format( AcceleratorModel.Meta.app_label) abstract = True unique_together = ('application', 'application_question') def __str__(self): return "Answer to question %s from %s" % ( self.application_question.question_number, self.application.startup.name)
Update browser target build with new classes
import XFlow from './xflow'; import XFlowStruct from './xflow-struct'; import XFlowMutableStruct from './xflow-mutable-struct'; import XFlowDispatcher from './xflow-dispatcher-dynamic'; import XFlowFactory from './xflow-factory'; import XFlowValidator from './xflow-validator'; import XFlowRunner from './xflow-runner'; import XFlowHarness from './xflow-harness'; export default { XFlow : XFlow, XFlowStruct : XFlowStruct, XFlowMutableStruct : XFlowMutableStruct, XFlowDispatcher : XFlowDispatcher, XFlowFactory : XFlowFactory, XFlowRunner : XFlowRunner, XFlowHarness : XFlowHarness, XFlowValidator : XFlowValidator };
import XFlow from './xflow'; import XFlowStruct from './xflow-struct'; import XFlowMutableStruct from './xflow-mutable-struct'; import XFlowDispatcher from './xflow-dispatcher'; import XFlowFactory from './xflow-factory'; import XFlowValidator from './xflow-validator'; import XFlowRunner from './xflow-runner'; function getXFlowFactory() { return (new XFlowFactory( new XFlowDispatcher() )); } function getXFlowRunner() { return (new XFlowRunner( getXFlowFactory() )); } export default { XFlow : XFlow, XFlowStruct : XFlowStruct, XFlowMutableStruct : XFlowMutableStruct, XFlowDispatcher : XFlowDispatcher, XFlowFactory : XFlowFactory, XFlowValidator : XFlowValidator, getXFlowRunner : getXFlowRunner };
Fix colour preview not loading on page load The event was changed from `change` to `input`. The trigger was not updated accordingly.
(function(Modules) { "use strict"; let isSixDigitHex = value => value.match(/^#[0-9A-F]{6}$/i); let colourOrWhite = value => isSixDigitHex(value) ? value : '#FFFFFF'; Modules.ColourPreview = function() { this.start = component => { this.$input = $('input', component); $(component).append( this.$preview = $('<span class="textbox-colour-preview"></span>') ); this.$input .on('input', this.update) .trigger('input'); }; this.update = () => this.$preview.css( 'background', colourOrWhite(this.$input.val()) ); }; })(window.GOVUK.Modules);
(function(Modules) { "use strict"; let isSixDigitHex = value => value.match(/^#[0-9A-F]{6}$/i); let colourOrWhite = value => isSixDigitHex(value) ? value : '#FFFFFF'; Modules.ColourPreview = function() { this.start = component => { this.$input = $('input', component); $(component).append( this.$preview = $('<span class="textbox-colour-preview"></span>') ); this.$input .on('input', this.update) .trigger('change'); }; this.update = () => this.$preview.css( 'background', colourOrWhite(this.$input.val()) ); }; })(window.GOVUK.Modules);
Make testing function more solid
var stylus = require('stylus'), fs = require('fs'), should = require('should'); function compare(name, done) { var str = fs.readFileSync(__dirname + '/fixtures/stylus/styl/' + name + '.styl', { encoding: 'utf8' }); stylus(str) .import('stylus/jeet') .render(function(err, result) { fs.readFile(__dirname + '/fixtures/stylus/css/' + name + '.css', { encoding: 'utf8' }, function(e, expected) { done(err, expected.should.be.exactly(result)); }); }); } // Stylus Comparison Tests describe('compiling method', function() { it('should apply a translucent, light-gray background color to all elements', function(done) { compare('edit', done); }); it('should center an element horizontally', function(done) { compare('center', done); }); });
var should = require('should'), stylus = require('stylus'), fs = require('fs'); var stylusMatchTest = function() { var files = fs.readdirSync(__dirname + '/fixtures/stylus/styl/'); files.forEach(function(file) { var fileName = file.replace(/.{5}$/, ''); describe(fileName + ' method', function() { it('should match', function(done) { var str = fs.readFileSync(__dirname + '/fixtures/stylus/styl/' + fileName + '.styl', { encoding: 'utf8' }); stylus(str) .import('stylus/jeet') .render(function(err, result) { var expected = fs.readFileSync(__dirname + '/fixtures/stylus/css/' + fileName + '.css', { encoding: 'utf8' }); done(err, expected.should.be.exactly(result)); }); }); }); }); } stylusMatchTest();