text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Handle falsey children in Commands component
import React from 'react'; import PropTypes from 'prop-types'; import {DOMNodePropType} from '../prop-types'; export default class Commands extends React.Component { static propTypes = { registry: PropTypes.object.isRequired, target: PropTypes.oneOfType([ PropTypes.string, DOMNodePropType, ]).isRequired, children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element), ]).isRequired, } render() { const {registry, target} = this.props; return ( <div> {React.Children.map(this.props.children, child => { return child ? React.cloneElement(child, {registry, target}) : null; })} </div> ); } } export class Command extends React.Component { static propTypes = { registry: PropTypes.object, target: PropTypes.oneOfType([ PropTypes.string, DOMNodePropType, ]), command: PropTypes.string.isRequired, callback: PropTypes.func.isRequired, } componentDidMount() { this.registerCommand(this.props); } componentWillReceiveProps(newProps) { for (const prop of ['registry', 'target', 'command', 'callback']) { if (newProps[prop] !== this.props[prop]) { this.disposable.dispose(); this.registerCommand(newProps); } } } componentWillUnmount() { this.disposable.dispose(); } registerCommand({registry, target, command, callback}) { this.disposable = registry.add(target, command, callback); } render() { return null; } }
import React from 'react'; import PropTypes from 'prop-types'; import {DOMNodePropType} from '../prop-types'; export default class Commands extends React.Component { static propTypes = { registry: PropTypes.object.isRequired, target: PropTypes.oneOfType([ PropTypes.string, DOMNodePropType, ]).isRequired, children: PropTypes.oneOfType([ PropTypes.element, PropTypes.arrayOf(PropTypes.element), ]).isRequired, } render() { const {registry, target} = this.props; return ( <div> {React.Children.map(this.props.children, child => { return React.cloneElement(child, {registry, target}); })} </div> ); } } export class Command extends React.Component { static propTypes = { registry: PropTypes.object, target: PropTypes.oneOfType([ PropTypes.string, DOMNodePropType, ]), command: PropTypes.string.isRequired, callback: PropTypes.func.isRequired, } componentDidMount() { this.registerCommand(this.props); } componentWillReceiveProps(newProps) { for (const prop of ['registry', 'target', 'command', 'callback']) { if (newProps[prop] !== this.props[prop]) { this.disposable.dispose(); this.registerCommand(newProps); } } } componentWillUnmount() { this.disposable.dispose(); } registerCommand({registry, target, command, callback}) { this.disposable = registry.add(target, command, callback); } render() { return null; } }
Use real on message handler
'use strict'; function QueueSeeker(pool) { this.db = 5; this.channel = 'batch:hosts'; this.redisPrefix = 'batch:queues:'; this.pattern = this.redisPrefix + '*'; this.pool = pool; } module.exports = QueueSeeker; QueueSeeker.prototype.seek = function (onMessage, callback) { var initialCursor = ['0']; this.onMessage = onMessage; this._seek(initialCursor, callback); }; QueueSeeker.prototype._seek = function (cursor, callback) { var self = this; var redisParams = [cursor[0], 'MATCH', self.pattern]; this.pool.acquire(this.db, function(err, client) { if (err) { return callback(err); } client.scan(redisParams, function(err, currentCursor) { // checks if iteration has ended if (currentCursor[0] === '0') { self.pool.release(self.db, client); return callback(null); } var queues = currentCursor[1]; if (!queues) { return callback(null); } queues.forEach(function (queue) { var host = queue.substr(self.redisPrefix.length); self.onMessage(self.channel, host); }); self._seek(currentCursor, callback); }); }); };
'use strict'; function QueueSeeker(pool) { this.db = 5; this.channel = 'batch:hosts'; this.redisPrefix = 'batch:queues:'; this.pattern = this.redisPrefix + '*'; this.pool = pool; } module.exports = QueueSeeker; QueueSeeker.prototype.seek = function (onMessage, callback) { var initialCursor = ['0']; this.onMessage = console.log.bind(console); this._seek(initialCursor, callback); }; QueueSeeker.prototype._seek = function (cursor, callback) { var self = this; var redisParams = [cursor[0], 'MATCH', self.pattern]; this.pool.acquire(this.db, function(err, client) { if (err) { return callback(err); } client.scan(redisParams, function(err, currentCursor) { // checks if iteration has ended if (currentCursor[0] === '0') { self.pool.release(self.db, client); return callback(null); } var queues = currentCursor[1]; if (!queues) { return callback(null); } queues.forEach(function (queue) { var host = queue.substr(self.redisPrefix.length); self.onMessage(self.channel, host); }); self._seek(currentCursor, callback); }); }); };
Add conditions in upload method
package com.example.julian.locationservice; import android.content.Context; import com.meedamian.info.BasicData; import org.json.JSONException; import org.json.JSONObject; public class DataUploader { private Context c; private String phone; private String vanity; private String country; private String city; public DataUploader(Context context) { c = context; } public void upload() { String key = BasicData.getPrivateId(c); JSONObject jo = new JSONObject(); try { jo.put("key", key); if (phone != null) jo.put("phone", phone); else if(vanity != null) jo.put("vanity", vanity); else if(country != null) jo.put("country", country); else if(city != null) jo.put("city", city); } catch (JSONException ignored) {} finally { // send `jo` // as POST body // to https://basic-data.parseapp.com/update } } public DataUploader setLocation(String country, String city) { this.country = country; this.city = city; return this; } public DataUploader setPhone(String phone) { this.phone = phone; return this; } public DataUploader setVanity(String vanity) { this.vanity = vanity; return this; } }
package com.example.julian.locationservice; import android.content.Context; import com.meedamian.info.BasicData; import org.json.JSONException; import org.json.JSONObject; public class DataUploader { private Context c; private String phone; private String vanity; private String county; private String city; public DataUploader(Context context) { c = context; } public void upload() { String key = BasicData.getPrivateId(c); JSONObject jo = new JSONObject(); try { jo.put("key", key); if (phone != null) jo.put("phone", phone); // TODO: ifs } catch (JSONException ignored) {} finally { // send `jo` // as POST body // to https://basic-data.parseapp.com/update } } public DataUploader setLocation(String country, String city) { this.county = country; this.city = city; return this; } public DataUploader setPhone(String phone) { this.phone = phone; return this; } public DataUploader setVanity(String vanity) { this.vanity = vanity; return this; } }
Add presenter methods to retrieve books by type
package com.verybadalloc.designlib.presenters; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import com.verybadalloc.designlib.model.Book; import com.verybadalloc.designlib.network.DataCallback; import com.verybadalloc.designlib.network.DataFetcher; import com.verybadalloc.designlib.views.BooksListView; /** * Created by aambri on 15-06-09. */ public class BooksListPresenter extends MvpBasePresenter<BooksListView> { private static final String TAG = "BooksListPresenter"; public void loadBooks(final boolean pullToRefresh) { if(isViewAttached()) { getView().showLoading(pullToRefresh); } DataFetcher.getBooks(new DataCallback<Book[]>() { @Override public void onSuccess(Book[] books) { if (isViewAttached()) { getView().setData(books); getView().showContent(); } } @Override public void onFailure(String reason) { String message = "Failed to load books because " + reason; if (isViewAttached()) { getView().showError(new Throwable(message), pullToRefresh); } } }); } public void loadBooksOfType(String bookType, final boolean pullToRefresh) { if(isViewAttached()) { getView().showLoading(pullToRefresh); } DataFetcher.getBooksOfType(bookType, new DataCallback<Book[]>() { @Override public void onSuccess(Book[] books) { if (isViewAttached()) { getView().setData(books); getView().showContent(); } } @Override public void onFailure(String reason) { String message = "Failed to load books because " + reason; if (isViewAttached()) { getView().showError(new Throwable(message), pullToRefresh); } } }); } }
package com.verybadalloc.designlib.presenters; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import com.verybadalloc.designlib.model.Book; import com.verybadalloc.designlib.network.DataCallback; import com.verybadalloc.designlib.network.DataFetcher; import com.verybadalloc.designlib.views.BooksListView; /** * Created by aambri on 15-06-09. */ public class BooksListPresenter extends MvpBasePresenter<BooksListView> { private static final String TAG = "BooksListPresenter"; public void loadEateries(final boolean pullToRefresh) { if(isViewAttached()) { getView().showLoading(pullToRefresh); } DataFetcher.getBooks(new DataCallback<Book[]>() { @Override public void onSuccess(Book[] books) { if (isViewAttached()) { getView().setData(books); getView().showContent(); } } @Override public void onFailure(String reason) { String message = "Failed to load books because " + reason; if (isViewAttached()) { getView().showError(new Throwable(message), pullToRefresh); } } }); } }
Correct path if slug contains "-"
<?php namespace Caffeinated\Modules\Console; use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand; use Illuminate\Support\Str; use Module; abstract class GeneratorCommand extends LaravelGeneratorCommand { /** * Parse the name and format according to the root namespace. * * @param string $name * * @return string */ protected function qualifyClass($name) { $rootNamespace = config('modules.namespace'); if (Str::startsWith($name, $rootNamespace)) { return $name; } $name = str_replace('/', '\\', $name); return $this->qualifyClass( $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name ); } /** * Get the destination class path. * * @param string $name * * @return string */ protected function getPath($name) { $slug = $this->argument('slug'); $module = Module::where('slug', $slug); // take everything after the module name in the given path (ignoring case) $key = array_search(strtolower($module['basename']), explode('\\', strtolower($name))); if ($key === false) { $newPath = str_replace('\\', '/', $name); } else { $newPath = implode('/', array_slice(explode('\\', $name), $key + 1)); } return module_path($slug, "$newPath.php"); } }
<?php namespace Caffeinated\Modules\Console; use Illuminate\Console\GeneratorCommand as LaravelGeneratorCommand; use Illuminate\Support\Str; use Module; abstract class GeneratorCommand extends LaravelGeneratorCommand { /** * Parse the name and format according to the root namespace. * * @param string $name * * @return string */ protected function qualifyClass($name) { $rootNamespace = config('modules.namespace'); if (Str::startsWith($name, $rootNamespace)) { return $name; } $name = str_replace('/', '\\', $name); return $this->qualifyClass( $this->getDefaultNamespace(trim($rootNamespace, '\\')).'\\'.$name ); } /** * Get the destination class path. * * @param string $name * * @return string */ protected function getPath($name) { $slug = $this->argument('slug'); // take everything after the module name in the given path (ignoring case) $key = array_search(strtolower($slug), explode('\\', strtolower($name))); if ($key === false) { $newPath = str_replace('\\', '/', $name); } else { $newPath = implode('/', array_slice(explode('\\', $name), $key + 1)); } return module_path($slug, "$newPath.php"); } }
Use fullpath for validator facade Added fullpath import for the validator facade.
<?php namespace App\Http\Controllers\Auth; use App\User; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; /** * Where to redirect users after login / registration. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } }
<?php namespace App\Http\Controllers\Auth; use App\User; use Validator; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\RegistersUsers; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; /** * Where to redirect users after login / registration. * * @var string */ protected $redirectTo = '/home'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|min:6|confirmed', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } }
Add bildge water event map name my app was crashing and it may come in handy later if the event repeats.
package com.robrua.orianna.type.core.common; import java.util.HashMap; import java.util.Map; public enum GameMap { BUTCHERS_BRIDGE(14), HOWLING_ABYSS(12), SUMMONERS_RIFT(11), SUMMONERS_RIFT_AUTUMN(2), SUMMONERS_RIFT_SUMMER(1), THE_CRYSTAL_SCAR(8), THE_PROVING_GROUNDS(3), TWISTED_TREELINE(10), TWISTED_TREELINE_ORIGINAL( 4); private static final Map<Long, GameMap> IDs = new HashMap<>(); static { for(final GameMap m : GameMap.values()) { IDs.put(m.ID, m); } } /** * Gets the map for a specified ID * * @param ID * the map ID * @return the map type */ public static GameMap forID(final long ID) { return IDs.get(ID); } private final Long ID; /** * @param ID */ private GameMap(final long ID) { this.ID = ID; } /** * Gets the ID for this map * * @return the ID for this map */ public long getID() { return ID; } }
package com.robrua.orianna.type.core.common; import java.util.HashMap; import java.util.Map; public enum GameMap { HOWLING_ABYSS(12), SUMMONERS_RIFT(11), SUMMONERS_RIFT_AUTUMN(2), SUMMONERS_RIFT_SUMMER(1), THE_CRYSTAL_SCAR(8), THE_PROVING_GROUNDS(3), TWISTED_TREELINE(10), TWISTED_TREELINE_ORIGINAL( 4); private static final Map<Long, GameMap> IDs = new HashMap<>(); static { for(final GameMap m : GameMap.values()) { IDs.put(m.ID, m); } } /** * Gets the map for a specified ID * * @param ID * the map ID * @return the map type */ public static GameMap forID(final long ID) { return IDs.get(ID); } private final Long ID; /** * @param ID */ private GameMap(final long ID) { this.ID = ID; } /** * Gets the ID for this map * * @return the ID for this map */ public long getID() { return ID; } }
Improve how child hooks are run in FeedForward
from .model import Model from ... import describe def _run_child_hooks(model, X, y): for layer in model._layers: for hook in layer.on_data_hooks: hook(layer, X, y) @describe.on_data(_run_child_hooks) class FeedForward(Model): '''A feed-forward network, that chains multiple Model instances together.''' def __init__(self, layers, **kwargs): Model.__init__(self, **kwargs) self._layers.extend(layers) @property def input_shape(self): return self._layers[0].input_shape @property def output_shape(self): return self._layers[-1].output_shape def begin_update(self, X, drop=0.): callbacks = [] for layer in self.layers: X = self.ops.xp.ascontiguousarray(X, dtype='float32') X, inc_layer_grad = layer.begin_update(X, drop=drop) callbacks.append(inc_layer_grad) def continue_update(gradient, sgd=None): for callback in reversed(callbacks): gradient = self.ops.xp.ascontiguousarray(gradient, dtype='float32') gradient = callback(gradient, sgd) return gradient return X, continue_update
from .model import Model class FeedForward(Model): '''A feed-forward network, that chains multiple Model instances together.''' def __init__(self, layers, **kwargs): Model.__init__(self, **kwargs) self.layers.extend(layers) if self.layers: nO = self.layers[0].output_shape[1] for layer in self.layers[1:]: if nO is not None and layer.nI is None: layer.nI = nO nO = layer.nO @property def input_shape(self): return self.layers[0].input_shape @property def output_shape(self): return self.layers[-1].output_shape def begin_update(self, X, drop=0.): callbacks = [] for layer in self.layers: assert layer.W is not None assert layer.b is not None X = self.ops.xp.ascontiguousarray(X, dtype='float32') X, inc_layer_grad = layer.begin_update(X, drop=drop) callbacks.append(inc_layer_grad) def continue_update(gradient, sgd=None): for callback in reversed(callbacks): gradient = self.ops.xp.ascontiguousarray(gradient, dtype='float32') gradient = callback(gradient, sgd) return gradient return X, continue_update
Bump vers for square Aramaic Unicode #975 from @D-K-E
"""Config for PyPI.""" from setuptools import find_packages from setuptools import setup setup( author='Kyle P. Johnson', author_email='[email protected]', classifiers=[ 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: Chinese (Traditional)', 'Natural Language :: English', 'Natural Language :: Greek', 'Natural Language :: Latin', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.7', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Text Processing', 'Topic :: Text Processing :: General', 'Topic :: Text Processing :: Linguistic', ], description='NLP for the ancient world', install_requires=['gitpython', 'nltk', 'python-crfsuite', 'pyuca', 'pyyaml', 'regex', 'whoosh'], keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan', 'arabic', "germanic"], license='MIT', long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.', # pylint: disable=C0301, name='cltk', packages=find_packages(), url='https://github.com/cltk/cltk', version='0.1.117', zip_safe=True, test_suite='cltk.tests.test_cltk', )
"""Config for PyPI.""" from setuptools import find_packages from setuptools import setup setup( author='Kyle P. Johnson', author_email='[email protected]', classifiers=[ 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: Chinese (Traditional)', 'Natural Language :: English', 'Natural Language :: Greek', 'Natural Language :: Latin', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.7', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Text Processing', 'Topic :: Text Processing :: General', 'Topic :: Text Processing :: Linguistic', ], description='NLP for the ancient world', install_requires=['gitpython', 'nltk', 'python-crfsuite', 'pyuca', 'pyyaml', 'regex', 'whoosh'], keywords=['nlp', 'nltk', 'greek', 'latin', 'chinese', 'sanskrit', 'pali', 'tibetan', 'arabic', "germanic"], license='MIT', long_description='The Classical Language Toolkit (CLTK) is a framework for natural language processing for Classical languages.', # pylint: disable=C0301, name='cltk', packages=find_packages(), url='https://github.com/cltk/cltk', version='0.1.116', zip_safe=True, test_suite='cltk.tests.test_cltk', )
Add key to selection rows
import React from 'react'; import PropTypes from 'prop-types'; import { Button } from 'react-bootstrap'; import FontAwesome from 'react-fontawesome'; import ContentContainer from '../../../components/applayout/ContentContainer'; import TopUtilizersSelectionRowContainer from '../containers/TopUtilizersSelectionRowContainer'; import styles from '../styles.module.css'; const getChildren = (rowData) => { return rowData.map((row) => { return <TopUtilizersSelectionRowContainer key={row.id} />; }); }; const TopUtilizersForm = ({ handleClick, rowData, onSubmit }) => { return ( <ContentContainer> <form className={styles.formWrapper} onSubmit={onSubmit}> <div className={styles.labelsRow}> Select search parameters </div> <div className={styles.rowsWrapper}> {getChildren(rowData)} </div> <div className={styles.addLink}> <a href="#" className={styles.addLink} onClick={handleClick}> <FontAwesome className={styles.plusIcon} name="plus" />Add search parameter </a> </div> <div className={styles.buttonWrapper}> <Button type="submit" className={styles.submitButton}>Find top utilizers</Button> </div> </form> </ContentContainer> ); }; TopUtilizersForm.propTypes = { handleClick: PropTypes.func.isRequired, rowData: PropTypes.array.isRequired, onSubmit: PropTypes.func.isRequired }; export default TopUtilizersForm;
import React from 'react'; import PropTypes from 'prop-types'; import { Button } from 'react-bootstrap'; import FontAwesome from 'react-fontawesome'; import ContentContainer from '../../../components/applayout/ContentContainer'; import TopUtilizersSelectionRowContainer from '../containers/TopUtilizersSelectionRowContainer'; import styles from '../styles.module.css'; const getChildren = (rowData) => { return rowData.map((row) => { return <TopUtilizersSelectionRowContainer id={row.id} />; }); }; const TopUtilizersForm = ({ handleClick, rowData, onSubmit }) => { return ( <ContentContainer> <form className={styles.formWrapper} onSubmit={onSubmit}> <div className={styles.labelsRow}> Select search parameters </div> <div className={styles.rowsWrapper}> {getChildren(rowData)} </div> <div className={styles.addLink}> <a href="#" className={styles.addLink} onClick={handleClick}> <FontAwesome className={styles.plusIcon} name="plus" />Add search parameter </a> </div> <div className={styles.buttonWrapper}> <Button type="submit" className={styles.submitButton}>Find top utilizers</Button> </div> </form> </ContentContainer> ); }; TopUtilizersForm.propTypes = { handleClick: PropTypes.func.isRequired, rowData: PropTypes.array.isRequired, onSubmit: PropTypes.func.isRequired }; export default TopUtilizersForm;
Comment out fix_fee_product_index from migration
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): try: schema_editor.execute( 'ALTER TABLE IF EXISTS cfpb.ratechecker_fee ' 'DROP CONSTRAINT IF EXISTS idx_16977_product_id;' 'ALTER TABLE IF EXISTS cfpb.ratechecker_fee ' 'ADD CONSTRAINT idx_16977_product_id ' 'UNIQUE (product_id, state_id, lender, single_family, condo, coop);' ) except (ProgrammingError, OperationalError): pass class Migration(migrations.Migration): dependencies = [ ('ratechecker', '0001_initial'), ] operations = [ #migrations.RunPython(fix_fee_product_index), migrations.AlterUniqueTogether( name='fee', unique_together=set([]), ), migrations.RemoveField( model_name='fee', name='plan', ), migrations.DeleteModel( name='Fee', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): try: schema_editor.execute( 'ALTER TABLE IF EXISTS cfpb.ratechecker_fee ' 'DROP CONSTRAINT IF EXISTS idx_16977_product_id;' 'ALTER TABLE IF EXISTS cfpb.ratechecker_fee ' 'ADD CONSTRAINT idx_16977_product_id ' 'UNIQUE (product_id, state_id, lender, single_family, condo, coop);' ) except (ProgrammingError, OperationalError): pass class Migration(migrations.Migration): dependencies = [ ('ratechecker', '0001_initial'), ] operations = [ migrations.RunPython(fix_fee_product_index), migrations.AlterUniqueTogether( name='fee', unique_together=set([]), ), migrations.RemoveField( model_name='fee', name='plan', ), migrations.DeleteModel( name='Fee', ), ]
Remove console log and rework vars.
document.getElementById('generate').onclick = genPassword; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function genPassword() { var pass = ""; for (i = 0; i < document.getElementById('length').value; i++) { var a = []; if (document.getElementById('d').checked) { a.push([48, 57]); } if (document.getElementById('u').checked) { a.push([65, 90]); } if (document.getElementById('l').checked) { a.push([97, 122]); } if (document.getElementById('un').checked) { a.push([161, 9999]); } if (document.getElementById('s').checked) { a.push([33, 47]); } if (document.getElementById('sp').checked) { a.push([32, 32]); } var type = getRandomInt(0, a.length - 1); var min = a[type][0]; var max = a[type][1]; var randUnicode = String.fromCharCode(getRandomInt(min, max)); pass += randUnicode; } document.getElementById('password').value = pass.toString(); }
document.getElementById('generate').onclick = genPassword; function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function genPassword() { var passLength = document.getElementById('length').value; var pass=""; for (i = 0; i < passLength; i++) { var a = []; if (document.getElementById('d').checked) { a.push([48, 57]); } if (document.getElementById('u').checked) { a.push([65, 90]); } if (document.getElementById('l').checked) { a.push([97, 122]); } if (document.getElementById('un').checked) { a.push([161, 9999]); } if (document.getElementById('s').checked) { a.push([33, 47]); } if (document.getElementById('sp').checked) { a.push([32, 32]); } var length = a.length; var type = getRandomInt(0, length - 1); console.log("a: "+(a[type][0])); var min = a[type][0]; var max = a[type][1]; var randUnicode = String.fromCharCode(getRandomInt(min, max)); pass+=randUnicode; } document.getElementById('password').value = pass.toString(); }
Handle Dash objects in to_json
from __future__ import absolute_import import plotly import plotly.graph_objs as go def validate_coerce_fig_to_dict(fig, validate, clone=True): from plotly.basedatatypes import BaseFigure if isinstance(fig, BaseFigure): fig_dict = fig.to_dict(clone=clone) elif isinstance(fig, dict): if validate: # This will raise an exception if fig is not a valid plotly figure fig_dict = plotly.graph_objs.Figure(fig).to_plotly_json() else: fig_dict = fig elif hasattr(fig, "to_plotly_json"): fig_dict = fig.to_plotly_json() else: raise ValueError( """ The fig parameter must be a dict or Figure. Received value of type {typ}: {v}""".format( typ=type(fig), v=fig ) ) return fig_dict def validate_coerce_output_type(output_type): if output_type == "Figure" or output_type == go.Figure: cls = go.Figure elif output_type == "FigureWidget" or ( hasattr(go, "FigureWidget") and output_type == go.FigureWidget ): cls = go.FigureWidget else: raise ValueError( """ Invalid output type: {output_type} Must be one of: 'Figure', 'FigureWidget'""" ) return cls
from __future__ import absolute_import import plotly import plotly.graph_objs as go def validate_coerce_fig_to_dict(fig, validate, clone=True): from plotly.basedatatypes import BaseFigure if isinstance(fig, BaseFigure): fig_dict = fig.to_dict(clone=clone) elif isinstance(fig, dict): if validate: # This will raise an exception if fig is not a valid plotly figure fig_dict = plotly.graph_objs.Figure(fig).to_plotly_json() else: fig_dict = fig else: raise ValueError( """ The fig parameter must be a dict or Figure. Received value of type {typ}: {v}""".format( typ=type(fig), v=fig ) ) return fig_dict def validate_coerce_output_type(output_type): if output_type == "Figure" or output_type == go.Figure: cls = go.Figure elif output_type == "FigureWidget" or ( hasattr(go, "FigureWidget") and output_type == go.FigureWidget ): cls = go.FigureWidget else: raise ValueError( """ Invalid output type: {output_type} Must be one of: 'Figure', 'FigureWidget'""" ) return cls
Remove stub text for deployment message
var moment = require('moment'); require('moment-duration-format'); module.exports = { willDeploy: function(context) { return Promise.resolve({ slack: { startDeployDate: new Date() } }); }, didDeploy: function(context, slack) { var startDeployDate = context.slack.startDeployDate; var endDeployDate = new Date(); var duration = moment.duration(endDeployDate - startDeployDate); return slack.notify({ attachments: [{ "fallback":"Deployment finished! New revision was successfully uploaded.", "pretext":"Deployment finished! New revision was successfully uploaded.", "color":"good", "fields":[ { "title":"Stats", "value":"Deploying revision took "+duration.format('m [min], s [s], S [ms]')+'.', "short":false } ] }] }); }, didFail: function(context, slack) { var message = "Ember-cli-deploy tried to deploy a revision but failed."; return slack.notify({ attachments: [{ "fallback": "Deployment failed!", "pretext": "Deployment failed!", "color": "danger", "fields":[ { "title": "Failure", "value": message, "short": false } ] }] }); } };
var moment = require('moment'); require('moment-duration-format'); module.exports = { willDeploy: function(context) { return Promise.resolve({ slack: { startDeployDate: new Date() } }); }, didDeploy: function(context, slack) { var startDeployDate = context.slack.startDeployDate; var endDeployDate = new Date(); var duration = moment.duration(endDeployDate - startDeployDate); return slack.notify({ attachments: [{ "fallback":"Deployment finished! Revision <http://localhost:4567?index_key=123451|123451> was successfully uploaded.", "pretext":"Deployment finished! Revision <http://localhost:4567?index_key=123451|123451> was successfully uploaded.", "color":"good", "fields":[ { "title":"Stats", "value":"Deploying revision 123451 took "+duration.format('m [min], s [s], S [ms]')+'.', "short":false } ] }] }); }, didFail: function(context, slack) { var message = "Ember-cli-deploy tried to deploy a revision but failed."; return slack.notify({ attachments: [{ "fallback": "Deployment failed!", "pretext": "Deployment failed!", "color": "danger", "fields":[ { "title": "Failure", "value": message, "short": false } ] }] }); } };
Send join message on startup
package forager.client; import java.io.IOException; import forager.events.JoinEvent; import galileo.event.EventWrapper; import galileo.net.ClientMessageRouter; import galileo.net.GalileoMessage; import galileo.net.MessageListener; import galileo.net.NetworkDestination; public class Forager implements MessageListener { private NetworkDestination overlord; private ClientMessageRouter messageRouter; public Forager(NetworkDestination overlord) { this.overlord = overlord; } public void start() throws IOException { messageRouter = new ClientMessageRouter(); messageRouter.addListener(this); messageRouter.connectTo(overlord); /* Join the network */ JoinEvent join = new JoinEvent(); messageRouter.sendMessage(overlord, EventWrapper.wrap(join)); } @Override public void onConnect(NetworkDestination endpoint) { } @Override public void onDisconnect(NetworkDestination endpoint) { //TODO: auto reconnect } @Override public void onMessage(GalileoMessage message) { } public static void main(String[] args) throws IOException { if (args.length < 2) { System.out.println("Usage: forager.client.Forager <host> <port>"); System.exit(1); } String host = args[0]; int port = Integer.parseInt(args[1]); NetworkDestination overlord = new NetworkDestination(host, port); Forager forager = new Forager(overlord); forager.start(); } }
package forager.client; import java.io.IOException; import galileo.net.ClientMessageRouter; import galileo.net.GalileoMessage; import galileo.net.MessageListener; import galileo.net.NetworkDestination; public class Forager implements MessageListener { private NetworkDestination overlord; private ClientMessageRouter messageRouter; private boolean once = false; public Forager(NetworkDestination overlord) { this.overlord = overlord; } public void start() throws IOException { messageRouter = new ClientMessageRouter(); messageRouter.addListener(this); messageRouter.connectTo(overlord); /* Join the network */ } @Override public void onConnect(NetworkDestination endpoint) { } @Override public void onDisconnect(NetworkDestination endpoint) { //TODO: auto reconnect } @Override public void onMessage(GalileoMessage message) { } public static void main(String[] args) throws IOException { if (args.length < 2) { System.out.println("Usage: forager.client.Forager <host> <port>"); System.exit(1); } String host = args[0]; int port = Integer.parseInt(args[1]); NetworkDestination overlord = new NetworkDestination(host, port); Forager forager = new Forager(overlord); forager.start(); } }
Fix locale not updated (should not mutate global locale)
import React from 'react'; import PropTypes from 'prop-types'; import getDisplayName from '../utils/getDisplayName'; import { localeShape } from '../constants/PropTypes'; export default Page => { class WithLocale extends React.Component { static displayName = getDisplayName('WithLocale', Page); static propTypes = { defaultLocale: PropTypes.string, siteLocales: PropTypes.arrayOf(PropTypes.string.isRequired), locale: localeShape, }; static async getInitialProps(ctx) { const context = (ctx.req || window.__NEXT_DATA__.props); const { defaultLocale, siteLocales } = context; let locale = context.locale; if (!ctx.req) { if (ctx.query.locale) { const [language, country] = ctx.query.locale.split('-'); if (siteLocales.indexOf(`${language}-${country}`) !== -1) { locale = { language, country, }; context.locale = locale; } } } const props = Page.getInitialProps && await Page.getInitialProps({ ...ctx, defaultLocale, siteLocales, locale, }); return { ...props, defaultLocale, siteLocales, locale, }; } render() { return <Page {...this.props} />; } } return WithLocale; };
import React from 'react'; import PropTypes from 'prop-types'; import getDisplayName from '../utils/getDisplayName'; import { localeShape } from '../constants/PropTypes'; export default Page => { class WithLocale extends React.Component { static displayName = getDisplayName('WithLocale', Page); static propTypes = { defaultLocale: PropTypes.string, siteLocales: PropTypes.arrayOf(PropTypes.string.isRequired), locale: localeShape, }; static async getInitialProps(ctx) { const { defaultLocale, siteLocales, locale } = ctx.req || window.__NEXT_DATA__.props; if (!ctx.req) { if (ctx.query.locale) { const [language, country] = ctx.query.locale.split('-'); if (siteLocales.indexOf(`${language}-${country}`) !== -1) { locale.language = language; locale.country = country; } } } const props = Page.getInitialProps && await Page.getInitialProps({ ...ctx, defaultLocale, siteLocales, locale, }); return { ...props, defaultLocale, siteLocales, locale, }; } render() { return <Page {...this.props} />; } } return WithLocale; };
Disable annoying syncdb info for volatile db
from .util import import_module import logging def init(): """ Initialize nazs environment, setup logging, processes and all needed stuff for running nazs """ from django.core import management # Sync volatile db, TODO set correct permissions management.call_command('syncdb', database='volatile', interactive=False, verbosity=0) from .sudo import set_euid set_euid() # Load all modules from django.conf import settings for app in settings.INSTALLED_APPS: import_module(app + '.module') def modules(): """ Return a list of instances of all present modules """ from .module import Module return [cls() for cls in Module.MODULES] def changed(): """ Return True if there is any change in any of the available modules """ for module in modules(): if module.changed: return True return False def save(): """ Apply configuration changes on all the modules """ from .models import ModuleInfo logger = logging.getLogger(__name__) logger.info("Saving changes") # Save + restart for module in modules(): if module.enabled: if module.changed: module.save() module.restart() module.commit() else: logger.debug("Not saving unchanged module: %s" % module.name) else: logger.debug("Not saving disabled module: %s" % module.name) # Commit ModuleInfo.commit() logger.info("Changes saved")
from .util import import_module import logging def init(): """ Initialize nazs environment, setup logging, processes and all needed stuff for running nazs """ from django.core import management # Sync volatile db, TODO set correct permissions management.call_command('syncdb', database='volatile', interactive=False) from .sudo import set_euid set_euid() # Load all modules from django.conf import settings for app in settings.INSTALLED_APPS: import_module(app + '.module') def modules(): """ Return a list of instances of all present modules """ from .module import Module return [cls() for cls in Module.MODULES] def changed(): """ Return True if there is any change in any of the available modules """ for module in modules(): if module.changed: return True return False def save(): """ Apply configuration changes on all the modules """ from .models import ModuleInfo logger = logging.getLogger(__name__) logger.info("Saving changes") # Save + restart for module in modules(): if module.enabled: if module.changed: module.save() module.restart() module.commit() else: logger.debug("Not saving unchanged module: %s" % module.name) else: logger.debug("Not saving disabled module: %s" % module.name) # Commit ModuleInfo.commit() logger.info("Changes saved")
Fix tests (needed some delay)
<?php namespace Tests\Browser; use Tests\DuskTestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use App\Trio; class SolveTest extends DuskTestCase { public function testCanSolveTrio() { $this->browse(function ($browser) { //Go to solve screen $browser->visit('/solve'); $browser->pause(500); //Get current trio answer so we can answer correctly $trioId = $browser->text('#trio-id'); sleep(1); $trio = Trio::findOrFail($trioId); $answer = $trio->answer; //Save first sentence so we can see if it changes later $sentence = $browser->value('#sentence1'); //Input answer $browser->type('#answer', $answer); //Click check $browser->click('#check-button'); sleep(1); //See if button changed $browser->assertSeeIn('#check-button', 'Correct, next trio'); //Click again $browser->click('#check-button'); //See if new trio is loaded $browser->assertDontSeeIn('#sentence1', $sentence); //See if buttons are reset //TODO }); } }
<?php namespace Tests\Browser; use Tests\DuskTestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use App\Trio; class SolveTest extends DuskTestCase { public function testCanSolveTrio() { $this->browse(function ($browser) { //Go to solve screen $browser->visit('/solve'); $browser->pause(500); //Get current trio answer so we can answer correctly $trioId = $browser->text('#trio-id'); sleep(1); $trio = Trio::findOrFail($trioId); $answer = $trio->answer; //Save first sentence so we can see if it changes later $sentence = $browser->value('#sentence1'); //Input answer $browser->type('#answer', $answer); //Click check $browser->click('#check-button'); //See if button changed $browser->assertSeeIn('#check-button', 'Correct, next trio'); //Click again $browser->click('#check-button'); //See if new trio is loaded $browser->assertDontSeeIn('#sentence1', $sentence); //See if buttons are reset //TODO }); } }
Allow for destination file in mock endpoint
package com.llnw.storage.client; import com.google.common.collect.Lists; import com.google.common.io.Files; import com.llnw.storage.client.io.ActivityCallback; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; public class MockEndpointFactory extends EndpointFactory { private final File destination; public MockEndpointFactory() { this(null); } public MockEndpointFactory(File destination) { super(null, null, null); this.destination = destination; } @Override public Endpoint create(boolean useFTP) { return new Endpoint() { @Override public void deleteDirectory(String path) throws IOException { } @Override public void deleteFile(String path) throws IOException { } @Override public void close() { } @Override public void makeDirectory(String path) throws IOException { } @Override public List<String> listFiles(String path) throws IOException { return Lists.newArrayList(); } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { if (destination != null) { Files.copy(file, destination); } } @Override public void noop() throws IOException { } @Override public boolean exists(String path) throws IOException { return false; } }; } }
package com.llnw.storage.client; import com.google.common.collect.Lists; import com.llnw.storage.client.io.ActivityCallback; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; public class MockEndpointFactory extends EndpointFactory { public MockEndpointFactory() { super(null, null, null); } @Override public Endpoint create(boolean useFTP) { return new Endpoint() { @Override public void deleteDirectory(String path) throws IOException { } @Override public void deleteFile(String path) throws IOException { } @Override public void close() { } @Override public void makeDirectory(String path) throws IOException { } @Override public List<String> listFiles(String path) throws IOException { return Lists.newArrayList(); } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { } @Override public void noop() throws IOException { } @Override public boolean exists(String path) throws IOException { return false; } }; } }
Remove scalar type hint for php56 compat
<?php /** * This file is part of the Valit package. * * @package Valit * @author Kim Ravn Hansen <[email protected]> * @copyright 2017 * @license MIT */ namespace Moccalotto\Valit\Contracts; interface CheckManager { /** * Get or create the singleton instance. * * @return CheckManager */ /** * Get the default (global) manager instance. * * If no instance is configured, a new one is created via the create() factory method. * * @return CheckManager * * @see create */ public static function instance(); /** * Factory method. * * Create a Manager with all the default providers loaded * as well as the providers defined in $additionalCheckProviders * * @param string[] $additionalCheckProviders * * @return @CheckManager */ public static function create($additionalCheckProviders = []); /** * Check if the manager can perform a given check. * * @param string $checkName * * @return bool */ public function hasCheck($checkName); /** * Execute a check. * * @param string $checkName * @param mixed $value * @param array $args * * @return \Moccalotto\Valit\Result */ public function executeCheck($checkName, $value, array $args); }
<?php /** * This file is part of the Valit package. * * @package Valit * @author Kim Ravn Hansen <[email protected]> * @copyright 2017 * @license MIT */ namespace Moccalotto\Valit\Contracts; interface CheckManager { /** * Get or create the singleton instance. * * @return CheckManager */ /** * Get the default (global) manager instance. * * If no instance is configured, a new one is created via the create() factory method. * * @return CheckManager * * @see create */ public static function instance(); /** * Factory method. * * Create a Manager with all the default providers loaded * as well as the providers defined in $additionalCheckProviders * * @param string[] $additionalCheckProviders * * @return @CheckManager */ public static function create($additionalCheckProviders = []); /** * Check if the manager can perform a given check. * * @param string $checkName * * @return bool */ public function hasCheck(string $checkName); /** * Execute a check. * * @param string $checkName * @param mixed $value * @param array $args * * @return \Moccalotto\Valit\Result */ public function executeCheck($checkName, $value, array $args); }
Use a different method for locating an existing stack Should help with cases where there are too many stacks to receive in a single listStacks request. This way, we should only ever receive a single stack.
"use strict"; const AWS = require('aws-sdk'); const Promise = require('bluebird'); const _ = require('lodash'); // // Step that fetches the existing stack, and stores it in the context // module.exports = function(context) { return new Promise(function(resolve, reject) { const CF = new AWS.CloudFormation({ apiVersion: '2010-05-15' }); const ctx = _.clone(context); ctx.stack = _.assign({}, ctx.stack, { name: `${context.project.name}-${context.project.stage}`, }); process.stdout.write(`\nChecking if CF stack '${ctx.stack.name}' exists`); // Unacceptable statuses for the stack const deletedStatuses = [ 'DELETE_IN_PROGRESS', 'DELETE_FAILED', 'DELETE_COMPLETE']; // Fetch info about the stack CF.describeStacks({ StackName: ctx.stack.name }, function(err, result) { if (err) { console.log(' ✖'.red); return reject(err); } const stacks = result.Stacks; const existingStack = stacks.find(function(stack) { return stack.StackName === ctx.stack.name && deletedStatuses.indexOf(stack.StackStatus) === -1; }); ctx.stack = _.assign({}, ctx.stack, { stack: existingStack }); console.log(' ✔'.green); resolve(ctx); }); }); };
"use strict"; const AWS = require('aws-sdk'); const Promise = require('bluebird'); const _ = require('lodash'); // // Step that fetches the existing stack, and stores it in the context // module.exports = function(context) { return new Promise(function(resolve, reject) { const CF = new AWS.CloudFormation({ apiVersion: '2010-05-15' }); const ctx = _.clone(context); ctx.stack = _.assign({}, ctx.stack, { name: `${context.project.name}-${context.project.stage}`, }); process.stdout.write(`\nChecking if CF stack '${ctx.stack.name}' exists`); // Fetch info about the stack CF.listStacks({}, function(err, result) { if (err) { console.log(' ✖'.red); return reject(err); } const stacks = result.StackSummaries; const existingStack = stacks.find(function(stack) { return stack.StackName === ctx.stack.name && stack.DeletionTime === undefined; }); ctx.stack = _.assign({}, ctx.stack, { stack: existingStack }); console.log(' ✔'.green); resolve(ctx); }); }); };
Add Zend_Db Test - fetchAll
<?php class ZendDbTest extends \PHPUnit_Framework_TestCase { public function testInstantiateDbAdapter() { $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $this->getDbAdapter()); } public function testZendDbFactoryWithZendConfig() { $config = new Zend_Config( array( 'database' => array( 'adapter' => 'Pdo_Sqlite', 'params' => array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ) ) ); $adapter = Zend_Db::factory($config->database); $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter); } public function testZendDbAdapterForcingConnection() { $this->assertInstanceOf('PDO', $this->getDbAdapter()->getConnection()); } public function testZendDbFetchAll() { $sql = 'SELECT * FROM `bugs`'; $result = $this->getDbAdapter()->fetchAll($sql); $this->assertTrue(is_array($result)); $sql = 'SELECT * FROM `bugs` WHERE id = ?'; $result = $this->getDbAdapter()->fetchAll($sql, 1); $this->assertEquals(1, $result[0]['id']); } /** * @return Zend_Db_Adapter_Abstract */ public function getDbAdapter() { return \Zend_Db::factory( 'Pdo_Sqlite', array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ); } }
<?php class ZendDbTest extends \PHPUnit_Framework_TestCase { public function testInstantiateDbAdapter() { $adapter = \Zend_Db::factory( 'Pdo_Sqlite', array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ); $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter); } public function testZendDbFactoryWithZendConfig() { $config = new Zend_Config( array( 'database' => array( 'adapter' => 'Pdo_Sqlite', 'params' => array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ) ) ); $adapter = Zend_Db::factory($config->database); $this->assertInstanceOf('\Zend_Db_Adapter_Pdo_Sqlite', $adapter); } public function testZendDbAdapterForcingConnection() { $adapter = \Zend_Db::factory( 'Pdo_Sqlite', array( 'dbname' => dirname(__FILE__) . '/../../../data/test.sqlite' ) ); $connection = $adapter->getConnection(); $this->assertInstanceOf('PDO', $connection); } }
Revert "Move build.branch-names to project settings" This reverts commit a38fc17616ae160aa41046470964034294eade1a.
import logging from flask import current_app from fnmatch import fnmatch from changes.api.build_index import BuildIndexAPIView from changes.config import db from changes.models import ItemOption logger = logging.getLogger('build_revision') def should_build_branch(revision, allowed_branches): if not revision.branches: return True for branch in revision.branches: if any(fnmatch(branch, pattern) for pattern in allowed_branches): return True return False def revision_created_handler(revision, **kwargs): options = dict( db.session.query( ItemOption.name, ItemOption.value ).filter( ItemOption.item_id == revision.repository_id, ItemOption.name.in_([ 'build.branch-names', ]) ) ) if not should_build_branch(revision, options.get('build.branch-names', '*').split(' ')): return data = { 'sha': revision.sha, 'repository': revision.repository.url, } with current_app.test_request_context('/api/0/builds/', method='POST', data=data): response = BuildIndexAPIView().post() if isinstance(response, (list, tuple)): response, status = response if status != 200: logger.error('Failed to create builds: %s' % (response,))
import logging from flask import current_app from fnmatch import fnmatch from changes.api.build_index import BuildIndexAPIView from changes.config import db from changes.models import ItemOption, Project logger = logging.getLogger('build_revision') def should_build_branch(revision, allowed_branches): if not revision.branches: return True for branch in revision.branches: if any(fnmatch(branch, pattern) for pattern in allowed_branches): return True return False def revision_created_handler(revision, **kwargs): project_list = list(Project.query.filter( Project.repository_id == revision.repository_id, )) if not project_list: return options = dict( db.session.query( ItemOption.item_id, ItemOption.value ).filter( ItemOption.item_id.in_(p.id for p in project_list), ItemOption.name.in_([ 'build.branch-names', ]) ) ) for project in project_list: branch_names = options.get('build.branch-names', '*').split(' ') if not should_build_branch(revision, branch_names): return data = { 'sha': revision.sha, 'project': project.slug, } with current_app.test_request_context('/api/0/builds/', method='POST', data=data): response = BuildIndexAPIView().post() if isinstance(response, (list, tuple)): response, status = response if status != 200: logger.error('Failed to create builds: %s' % (response,))
Check for duplicates in existing dataset. Fix reference to dump file.
import json from backend.app import app, db from backend.models import * from flask import url_for # read in json redirect dump with open('data/nid_url.json', 'r') as f: redirects = json.loads(f.read()) print len(redirects) old_urls = [] existing_redirects = Redirect.query.all() for redirect in existing_redirects: old_urls.append(redirect.old_url) error_count = 0 for i in range(len(redirects)): nid = None try: nid = int(redirects[i]['nid']) except ValueError as e: tmp = redirects[i]['nid'] if not 'user' in tmp: tmp = tmp.split('/') for item in tmp: try: nid = int(item) break except ValueError: pass url = redirects[i]['url'] if nid and not url in old_urls: redirect = Redirect(nid=nid, old_url=url) old_urls.append(url) db.session.add(redirect) else: error_count += 1 print nid, redirects[i]['url'].encode('utf8') if i % 500 == 0: print "saving 500 redirects (" + str(i) + " out of " + str(len(redirects)) + ")" db.session.commit() db.session.commit() print "Error count:", str(error_count)
import json from backend.app import app, db from backend.models import * from flask import url_for # read in json redirect dump with open('data/prod_url_alias.json', 'r') as f: redirects = json.loads(f.read()) print len(redirects) old_urls = [] error_count = 0 for i in range(len(redirects)): nid = None try: nid = int(redirects[i]['nid']) except ValueError as e: tmp = redirects[i]['nid'] if not 'user' in tmp: tmp = tmp.split('/') for item in tmp: try: nid = int(item) break except ValueError: pass url = redirects[i]['url'] if nid and not url in old_urls: redirect = Redirect(nid=nid, old_url=url) old_urls.append(url) db.session.add(redirect) else: error_count += 1 print nid, redirects[i]['url'] if i % 500 == 0: print "saving 500 redirects (" + str(i) + " out of " + str(len(redirects)) + ")" db.session.commit() db.session.commit() print "Error count:", str(error_count)
Add 'hydrate' option to the doctrine mapper
<?php namespace FOQ\ElasticaBundle\Mapper; use FOQ\ElasticaBundle\MapperInterface; use Doctrine\Common\Persistence\ObjectRepository; /** * Maps Elastica documents with Doctrine objects * This mapper assumes an exact match between * elastica documents ids and doctrine object ids */ class DoctrineMapper implements MapperInterface { /** * Repository to fetch the objects from * * @var ObjectRepository */ protected $objectRepository = null; /** * Doctrine identifier field * * @var string */ protected $identifier = null; /** * Optional parameters * * @var array */ protected $options = array( 'hydrate' => true ); /** * Instanciates a new Mapper * * @param ObjectRepository objectRepository * @param string $identifier * @param array $options */ public function __construct(ObjectRepository $objectRepository, $identifier = 'id', array $options = array()) { $this->objectRepository = $objectRepository; $this->identifier = $identifier; $this->options = array_merge($this->options, $options); } /** * Transforms an array of elastica objects into an array of * model objects fetched from the doctrine repository * * @return array **/ public function fromElasticaObjects(array $elasticaObjects) { $ids = array_map(function($elasticaObject) { return $elasticaObject->getId(); }, $elasticaObjects); return $this->objectRepository ->createQueryBuilder() ->field($this->identifier)->in($ids) ->hydrate($this->options['hydrate']) ->getQuery() ->execute(); } }
<?php namespace FOQ\ElasticaBundle\Mapper; use FOQ\ElasticaBundle\MapperInterface; use Doctrine\Common\Persistence\ObjectRepository; /** * Maps Elastica documents with Doctrine objects * This mapper assumes an exact match between * elastica documents ids and doctrine object ids */ class DoctrineMapper implements MapperInterface { /** * Repository to fetch the objects from * * @var ObjectRepository */ protected $objectRepository = null; /** * Doctrine identifier field * * @var string */ protected $identifier = null; /** * Instanciates a new Mapper * * @param ObjectRepository objectRepository * @param string $identifier */ public function __construct(ObjectRepository $objectRepository, $identifier = 'id') { $this->objectRepository = $objectRepository; $this->identifier = $identifier; } /** * Transforms an array of elastica objects into an array of * model objects fetched from the doctrine repository * * @return array **/ public function fromElasticaObjects(array $elasticaObjects) { $ids = array_map(function($elasticaObject) { return $elasticaObject->getId(); }, $elasticaObjects); return $this->objectRepository ->createQueryBuilder() ->field($this->identifier)->in($ids) ->getQuery() ->execute(); } }
Remove class active from pagination active class should be on the first page, not on the prev button
<?php include '_include/head.php'; ?> <div class="site"> <?php include '_include/header.php'; ?> <main class="main site-content"> <div class="container"> <h1 class="title">Notification</h1> <ul class="all-notif list-nostyle block"> <!-- empty state --> <!-- <li> <span class="empty-state">You have no notification.</span> </li> --> <?php for ($i=0; $i < 20; $i++) { ?> <li> <a href="#"> <span>Testing #20 on Suitmedia Project has done tested.</span> <br> <time class="text-grey">5 minutes ago</time> </a> </li> <?php } ?> </ul> <ul class="pagination"> <li> <a href="#">Prev</a> </li> <li> <a class="active" href="#">1</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">Next</a> </li> </ul> </div> </main> <?php include '_include/footer.php'; ?> </div> <?php include '_include/script.php'; ?>
<?php include '_include/head.php'; ?> <div class="site"> <?php include '_include/header.php'; ?> <main class="main site-content"> <div class="container"> <h1 class="title">Notification</h1> <ul class="all-notif list-nostyle block"> <!-- empty state --> <!-- <li> <span class="empty-state">You have no notification.</span> </li> --> <?php for ($i=0; $i < 20; $i++) { ?> <li> <a href="#"> <span>Testing #20 on Suitmedia Project has done tested.</span> <br> <time class="text-grey">5 minutes ago</time> </a> </li> <?php } ?> </ul> <ul class="pagination"> <li> <a class="active" href="#">Prev</a> </li> <li> <a href="#">1</a> </li> <li> <a href="#">2</a> </li> <li> <a href="#">3</a> </li> <li> <a href="#">Next</a> </li> </ul> </div> </main> <?php include '_include/footer.php'; ?> </div> <?php include '_include/script.php'; ?>
Disable auto links by default
<?php namespace Fenrizbes\TypographBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('fenrizbes_typograph'); $rootNode ->children() ->arrayNode('configs') ->useAttributeAsKey('name') ->prototype('array') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->defaultValue(array( 'default' => array( 'Text.paragraphs' => 'off', 'Text.breakline' => 'off', 'Text.auto_links' => 'off', 'Text.email' => 'off', 'OptAlign.oa_oquote' => 'off', 'OptAlign.oa_obracket_coma' => 'off' ) )) ->end() ->end() ; return $treeBuilder; } }
<?php namespace Fenrizbes\TypographBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('fenrizbes_typograph'); $rootNode ->children() ->arrayNode('configs') ->useAttributeAsKey('name') ->prototype('array') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->defaultValue(array( 'default' => array( 'Text.paragraphs' => 'off', 'Text.breakline' => 'off', 'OptAlign.oa_oquote' => 'off', 'OptAlign.oa_obracket_coma' => 'off' ) )) ->end() ->end() ; return $treeBuilder; } }
Allow GitHub styles not to be purged
module.exports = { siteMetadata: { title: `Neon Tsunami`, author: `Dwight Watson`, description: `A blog on Laravel & Rails.`, siteUrl: `https://www.neontsunami.com`, social: { twitter: `DwightConrad`, }, }, plugins: [ `gatsby-plugin-postcss`, { resolve: `gatsby-plugin-purgecss`, options: { tailwind: true, ignore: ['github.css'] } }, { resolve: `gatsby-source-filesystem`, options: { name: `markdown`, path: `${__dirname}/src/markdown`, }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ `gatsby-remark-prismjs`, ], }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: 'UA-23727271-4', }, }, `gatsby-plugin-feed`, { resolve: `gatsby-plugin-manifest`, options: { name: `Neon Tsunami`, short_name: `Neon Tsunami`, start_url: `/`, background_color: `#ffffff`, theme_color: `#4299e1`, display: `minimal-ui`, icon: `src/images/tsunami.png`, }, }, `gatsby-plugin-offline`, `gatsby-plugin-react-helmet`, `gatsby-plugin-netlify`, ], }
module.exports = { siteMetadata: { title: `Neon Tsunami`, author: `Dwight Watson`, description: `A blog on Laravel & Rails.`, siteUrl: `https://www.neontsunami.com`, social: { twitter: `DwightConrad`, }, }, plugins: [ `gatsby-plugin-postcss`, { resolve: `gatsby-plugin-purgecss`, options: { tailwind: true, ignore: ['prismjs/'] } }, { resolve: `gatsby-source-filesystem`, options: { name: `markdown`, path: `${__dirname}/src/markdown`, }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ `gatsby-remark-prismjs`, ], }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: 'UA-23727271-4', }, }, `gatsby-plugin-feed`, { resolve: `gatsby-plugin-manifest`, options: { name: `Neon Tsunami`, short_name: `Neon Tsunami`, start_url: `/`, background_color: `#ffffff`, theme_color: `#4299e1`, display: `minimal-ui`, icon: `src/images/tsunami.png`, }, }, `gatsby-plugin-offline`, `gatsby-plugin-react-helmet`, `gatsby-plugin-netlify`, ], }
Fix config test expected error message.
'use strict'; var expect = require('chai').expect, config = require('../../../config/config'); describe('config', function () { describe('getConfig', function () { var configDirectory = '../../../config/'; describe('existing configuration', function () { var testCases = [ { environment: 'development' }, { environment: 'integration' }, { environment: 'production' }, { environment: 'test' } ]; testCases.forEach(function (testCase) { it('should successfully load the specified configuration: ' + testCase.environment, function () { expect(config.getConfig(testCase.environment, configDirectory, require)).to.be.defined; }); }); }); describe('not existing configuration', function () { it('should throw an error if the specified configuration does not exist', function () { var environment = 'any not existing', expectedErrorMessageStaticPart = 'Config file for system environment not existing: ', expectedErrorMessage = expectedErrorMessageStaticPart + environment + ' in ' + configDirectory, getConfig = config.getConfig; expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage); }); }); }); });
'use strict'; var expect = require('chai').expect, config = require('../../../config/config'); describe('config', function () { describe('getConfig', function () { var configDirectory = '../../../config/'; describe('existing configuration', function () { var testCases = [ { environment: 'development' }, { environment: 'integration' }, { environment: 'production' }, { environment: 'test' } ]; testCases.forEach(function (testCase) { it('should successfully load the specified configuration: ' + testCase.environment, function () { expect(config.getConfig(testCase.environment, configDirectory, require)).to.be.defined; }); }); }); describe('not existing configuration', function () { it('should throw an error if the specified configuration does not exist', function () { var environment = 'any not existing', expectedErrorMessage = 'Config file for system environment not existing:' + environment, getConfig = config.getConfig; expect(getConfig.bind(null, environment, configDirectory, require)).to.throw(expectedErrorMessage); }); }); }); });
Split emitted errors into two groups: connectionError and error
var util = require('util'); var http = require('http'); function HTTPTransport() { // Opbeat currently doesn't support HTTP this.defaultPort = 80; this.transport = http; } HTTPTransport.prototype.send = function(client, message, headers) { var options = { hostname: client.dsn.host, path: client.dsn.path, headers: headers, method: 'POST', port: client.dsn.port || this.defaultPort }, req = this.transport.request(options, function(res){ res.setEncoding('utf8'); var body = []; res.on('data', function(data) { body.push(data); }); res.on('end', function(){ if(res.statusCode >= 200 && res.statusCode < 300) { client.emit('logged', res.headers.location); } else { var msg = ''; body = body.join(''); try { body = JSON.parse(body); msg = body.error_message; } catch (e) {} client.emit('error', new Error('Opbeat error (' + res.responseCode + '): ' + msg)); } }); }); req.on('error', function(e){ client.emit('connectionError', e); }); req.end(message); } var https = require('https'); function HTTPSTransport() { this.defaultPort = 443; this.transport = https; } util.inherits(HTTPSTransport, HTTPTransport); module.exports.https = new HTTPSTransport();
var util = require('util'); var http = require('http'); function HTTPTransport() { // Opbeat currently doesn't support HTTP this.defaultPort = 80; this.transport = http; } HTTPTransport.prototype.send = function(client, message, headers) { var options = { hostname: client.dsn.host, path: client.dsn.path, headers: headers, method: 'POST', port: client.dsn.port || this.defaultPort }, req = this.transport.request(options, function(res){ res.setEncoding('utf8'); var body = []; res.on('data', function(data) { body.push(data); }); res.on('end', function(){ if(res.statusCode >= 200 && res.statusCode < 300) { client.emit('logged', res.headers.location); } else { body = body.join(''); var e = new Error('HTTP Error (' + res.statusCode + '): ' + body); e.response = res; e.statusCode = res.statusCode; e.responseBody = body; client.emit('error', e); } }); }); req.on('error', function(e){ client.emit('error', e); }); req.end(message); } var https = require('https'); function HTTPSTransport() { this.defaultPort = 443; this.transport = https; } util.inherits(HTTPSTransport, HTTPTransport); module.exports.https = new HTTPSTransport();
Change build_dest default in config
<?php return [ /* |-------------------------------------------------------------------------- | CDNify CDN list. |-------------------------------------------------------------------------- | | This is a list of CDN's for cdnify to use, it will most likely be a url. | */ 'cdn' => [ 'cloudfront' => 'https://'.env('AWS_CLOUDFRONT', ''), ], /* |-------------------------------------------------------------------------- | Laravel Elixir. |-------------------------------------------------------------------------- | | This specifies if cdnify should use elixir() to wrap the path. | */ 'elixir' => true, /* |-------------------------------------------------------------------------- | Environment. |-------------------------------------------------------------------------- | | This specifies which environments require a cdn path prefixing. | */ 'environments' => [ 'staging', 'production', ], /* |-------------------------------------------------------------------------- | Round robin. |-------------------------------------------------------------------------- | | This will rotate through the list of provided CDNs each time a call | to cdn() is made. | */ 'round_robin' => false, /* |-------------------------------------------------------------------------- | Command settings. |-------------------------------------------------------------------------- | | This holds the list of defaults to be used with the metrique:cdnify | command. These options can be changed in this config and also | overridden by command line flags. | */ 'command' => [ 'build_source' => '/build', 'build_dest' => '/build', 'disk' => 's3', 'force' => false, 'manifest' => '/build/rev-manifest.json', ], ];
<?php return [ /* |-------------------------------------------------------------------------- | CDNify CDN list. |-------------------------------------------------------------------------- | | This is a list of CDN's for cdnify to use, it will most likely be a url. | */ 'cdn' => [ 'cloudfront' => 'https://'.env('AWS_CLOUDFRONT', ''), ], /* |-------------------------------------------------------------------------- | Laravel Elixir. |-------------------------------------------------------------------------- | | This specifies if cdnify should use elixir() to wrap the path. | */ 'elixir' => true, /* |-------------------------------------------------------------------------- | Environment. |-------------------------------------------------------------------------- | | This specifies which environments require a cdn path prefixing. | */ 'environments' => [ 'staging', 'production', ], /* |-------------------------------------------------------------------------- | Round robin. |-------------------------------------------------------------------------- | | This will rotate through the list of provided CDNs each time a call | to cdn() is made. | */ 'round_robin' => false, /* |-------------------------------------------------------------------------- | Command settings. |-------------------------------------------------------------------------- | | This holds the list of defaults to be used with the metrique:cdnify | command. These options can be changed in this config and also | overridden by command line flags. | */ 'command' => [ 'build_source' => '/build', 'build_dest' => '', 'disk' => 's3', 'force' => false, 'manifest' => '/build/rev-manifest.json', ], ];
Use worker_int to avoid \n being printed too late
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess. This module is not designed to be imported directly, but provided as Gunicorn's configuration file. """ import os import sys import django import gunicorn # General configs. bind = os.environ['DJANGO_ADDRPORT'] logger_class = 'djgunicorn.logging.GunicornLogger' def post_worker_init(worker): """Hook into Gunicorn to display message after launching. This mimics the behaviour of Django's stock runserver command. """ quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' sys.stdout.write( "Django version {djangover}, Gunicorn version {gunicornver}, " "using settings {settings!r}\n" "Starting development server at http://{addrport}/\n" "Quit the server with {quit_command}.\n".format( djangover=django.get_version(), gunicornver=gunicorn.__version__, settings=os.environ.get('DJANGO_SETTINGS_MODULE'), addrport=bind, quit_command=quit_command, ), ) def worker_int(worker): """Hook into Gunicorn to display message when worker gets an interruption. The purpose of this hook is purely cosmetic: we want a newline when the worker reloads. This has an unintended side effect to display an extra newline after the server quits, but it is relatively unimportant. """ sys.stdout.write('\n')
"""Gunicorn configuration file used by gunserver's Gunicorn subprocess. This module is not designed to be imported directly, but provided as Gunicorn's configuration file. """ import os import sys import django import gunicorn # General configs. bind = os.environ['DJANGO_ADDRPORT'] logger_class = 'djgunicorn.logging.GunicornLogger' def post_worker_init(worker): """Hook into Gunicorn to display message after launching. This mimics the behaviour of Django's stock runserver command. """ quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' sys.stdout.write( "Django version {djangover}, Gunicorn version {gunicornver}, " "using settings {settings!r}\n" "Starting development server at http://{addrport}/\n" "Quit the server with {quit_command}.\n".format( djangover=django.get_version(), gunicornver=gunicorn.__version__, settings=os.environ.get('DJANGO_SETTINGS_MODULE'), addrport=bind, quit_command=quit_command, ), ) def worker_exit(server, worker): """Hook into Gunicorn to display message after existing. The purpose of this hook is purely cosmetic: we want a newline after the worker reloads. This has an unintended side effect to display an extra newline after the server quits, but it is relatively unimportant. """ sys.stdout.write('\n')
Use Flask routing to allow for variables in URL
# -*- coding: utf-8 -*- from functools import wraps from flask import request def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker except ImportError: pass if 'gevent' in locals(): # Freedom-Patch logger for Gunicorn. if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class Sockets(object): def __init__(self, app=None): self.app = app def route(self, rule, **options): def decorator(f): @wraps(f) def inner(*args, **kwargs): return f(request.environ['wsgi.websocket'], *args, **kwargs) if self.app: endpoint = options.pop('endpoint', None) self.app.add_url_rule(rule, endpoint, inner, **options) return inner return decorator # CLI sugar. if 'Worker' in locals(): worker = Worker
# -*- coding: utf-8 -*- def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker except ImportError: pass if 'gevent' in locals(): # Freedom-Patch logger for Gunicorn. if hasattr(gevent, 'pywsgi'): gevent.pywsgi.WSGIHandler.log_request = log_request class SocketMiddleware(object): def __init__(self, wsgi_app, socket): self.ws = socket self.app = wsgi_app def __call__(self, environ, start_response): path = environ['PATH_INFO'] if path in self.ws.url_map: handler = self.ws.url_map[path] environment = environ['wsgi.websocket'] handler(environment) else: return self.app(environ, start_response) class Sockets(object): def __init__(self, app=None): self.url_map = {} if app: self.init_app(app) def init_app(self, app): app.wsgi_app = SocketMiddleware(app.wsgi_app, self) def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator def add_url_rule(self, rule, _, f, **options): self.url_map[rule] = f # CLI sugar. if 'Worker' in locals(): worker = Worker
Fix translation of notify slack
<?php /* * This file is part of Fixhub. * * Copyright (C) 2016 Fixhub.org * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ 'label' => 'Slack推送', 'create' => '新增', 'edit' => '编辑', 'none' => '该项目尚未设置Slack通知', 'name' => '名称', 'channel' => '频道', 'warning' => '保存失败,请检查表单信息.', 'icon' => '图标', 'bot' => 'Fixhub', 'icon_info' => '可以是表情符, 如: :ghost: 或者一个图片的URL.', 'webhook' => 'Webhook URL', 'test_message' => '发条测试消息,证明我的存在。 :+1:', 'success_message' => '%s 部署成功! :smile:', 'failed_message' => '%s 部署失败! :cry:', 'branch' => '分支', 'project' => '项目', 'commit' => '代码版本号', 'committer' => '代码提交者', 'failure_only' => '推送消息', 'notify_failure_only' => '仅失败时进行推送', 'failure_description' => '仅失败时进行推送', ];
<?php /* * This file is part of Fixhub. * * Copyright (C) 2016 Fixhub.org * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ 'label' => 'Slack推送', 'create' => '新增', 'edit' => '编辑', 'none' => '该项目尚未设置Slack通知', 'name' => '名称', 'channel' => '频道', 'warning' => '保存失败,请检查表单信息.', 'icon' => '图标', 'bot' => 'Fixhub', 'icon_info' => '可以是表情符, 如: :ghost: 或者一个图片的URL.', 'webhook' => 'Webhook URL', 'test_message' => 'This is a test to ensure the notification is setup correctly, if you ' . 'can see this it means it is! :+1:', 'success_message' => '%s 上线成功! :smile:', 'failed_message' => '%s 上线失败! :cry:', 'branch' => '分支', 'project' => '项目', 'commit' => 'Commit', 'committer' => 'Committer', 'failure_only' => '推送消息', 'notify_failure_only' => '仅失败时进行推送', 'failure_description' => '仅失败时进行推送', ];
Upgrade configparser to fix pip build issue on PyPy.
from setuptools import setup import sys REQUIREMENTS = [ 'argparse', 'GitPython>=0.3.2.RC1', 'Pillow>=2.3.0', 'requests', ] if sys.version_info <= (3,): REQUIREMENTS.append('configparser==3.5.0b2') # Using the beta for PyPy compatibility setup(name='lolologist', version='0.4.0', description='A utility that generates an image macro from your webcam whenever \ you commit to a git repository.', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Programming Language :: Python :: 2.6', 'Environment :: Console', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Topic :: Multimedia :: Graphics :: Capture', 'Topic :: Utilities', 'Topic :: Software Development :: Version Control', ], url='https://github.com/arusahni/lolologist', author='Aru Sahni', author_email='[email protected]', license='MPL 2.0', packages=['lolologist'], package_data={'lolologist':['LeagueGothic-Regular.otf', 'tranzlator.json']}, include_package_data=True, install_requires=REQUIREMENTS, entry_points = { 'console_scripts': ['lolologist=lolologist.lolologist:main'], }, zip_safe=False)
from setuptools import setup import sys REQUIREMENTS = [ 'argparse', 'GitPython>=0.3.2.RC1', 'Pillow>=2.3.0', 'requests', ] if sys.version_info <= (3,): REQUIREMENTS.append('configparser') setup(name='lolologist', version='0.4.0', description='A utility that generates an image macro from your webcam whenever \ you commit to a git repository.', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Programming Language :: Python :: 2.6', 'Environment :: Console', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Topic :: Multimedia :: Graphics :: Capture', 'Topic :: Utilities', 'Topic :: Software Development :: Version Control', ], url='https://github.com/arusahni/lolologist', author='Aru Sahni', author_email='[email protected]', license='MPL 2.0', packages=['lolologist'], package_data={'lolologist':['LeagueGothic-Regular.otf', 'tranzlator.json']}, include_package_data=True, install_requires=REQUIREMENTS, entry_points = { 'console_scripts': ['lolologist=lolologist.lolologist:main'], }, zip_safe=False)
Fix missing $ in navbar.
<?php namespace MinePlus\DesignBundle\Navbar; use Doctrine\Common\Collections\ArrayCollection; class Navbar { /* * @var string */ const COLOR_WHITE = 'white'; /* * @var string */ const COLOR_BLACK = 'black'; /* * When this is set, the color-choice is up to the template! * @var string */ const COLOR_UNDEFINED = null; /* * @var string */ const CATEGORY_ADMIN = 'admin'; /* * @var string */ const CATEGORY_DEFAULT = 'default'; protected $items; protected $color; protected $category; /* * @param array $items */ public function __construct($items = array(), $color = self::COLOR_UNDEFINED, $category = self::CATEGORY_DEFAULT) { $this->items = new ArrayCollection($items); $this->color = $color; $this->category = $category; } /* * @return Doctrine\Common\Collections\ArrayCollection */ public function getItems() { return $this->items; } /* * @return string */ public function getColor() { return $this->color; } /* * Set's the color for the navbar. * If the template doesn't know the specified color, it may be ignored. */ public function setColor($color) { $this->color = $color; return $this; // allow method chaining } /* * @return string */ public function getCategory() { return $this->category; } } ?>
<?php namespace MinePlus\DesignBundle\Navbar; use Doctrine\Common\Collections\ArrayCollection; class Navbar { /* * @var string */ const COLOR_WHITE = 'white'; /* * @var string */ const COLOR_BLACK = 'black'; /* * When this is set, the color-choice is up to the template! * @var string */ const COLOR_UNDEFINED = null; /* * @var string */ const CATEGORY_ADMIN = 'admin'; /* * @var string */ const CATEGORY_DEFAULT = 'default'; protected $items; protected $color; protected $category; /* * @param array $items */ public function __construct($items = array(), $color = self::COLOR_UNDEFINED, $category = self::CATEGORY_DEFAULT) { $this->items = new ArrayCollection($items); $this->color = $color; $this->category = $category; } /* * @return Doctrine\Common\Collections\ArrayCollection */ public function getItems() { return $this->items; } /* * @return string */ public function getColor() { return $this->color; } /* * Set's the color for the navbar. * If the template doesn't know the specified color, it may be ignored. */ public function setColor($color) { $this->color = $color; return this; // allow method chaining } /* * @return string */ public function getCategory() { return $this->category; } } ?>
Update : RangeIter args name changed
from .base import Client class RangeIter(object): def __init__(self, range_datas): self._container = range_datas if self._valid_range(range_datas) else None def _valid_range(self, range_datas): if (not isinstance(range_datas, tuple) or any(not isinstance(pair, tuple) for pair in range_datas)): raise ValueError("Range datas format not recognized") return True def __iter__(self): return self.forward() def forward(self): current_item = 0 while (current_item < len(self._container)): container = self._container[current_item] current_item += 1 yield container class Elevator(Client): def Get(self, key): return self.send(self.db_uid, 'GET', [key]) def MGet(self, keys): return self.send(self.db_uid, 'MGET', [keys]) def Put(self, key, value): return self.send(self.db_uid, 'PUT', [key, value]) def Delete(self, key): return self.send(self.db_uid, 'DELETE', [key]) def Range(self, start=None, limit=None): return self.send(self.db_uid, 'RANGE', [start, limit]) def RangeIter(self, key_from=None, key_to=None): range_datas = self.Range(key_from, key_to) return RangeIter(range_datas)
from .base import Client class RangeIter(object): def __init__(self, range_datas): self._container = range_datas if self._valid_range(range_datas) else None def _valid_range(self, range_datas): if (not isinstance(range_datas, tuple) or any(not isinstance(pair, tuple) for pair in range_datas)): raise ValueError("Range datas format not recognized") return True def __iter__(self): return self.forward() def forward(self): current_item = 0 while (current_item < len(self._container)): container = self._container[current_item] current_item += 1 yield container class Elevator(Client): def Get(self, key): return self.send(self.db_uid, 'GET', [key]) def MGet(self, keys): return self.send(self.db_uid, 'MGET', [keys]) def Put(self, key, value): return self.send(self.db_uid, 'PUT', [key, value]) def Delete(self, key): return self.send(self.db_uid, 'DELETE', [key]) def Range(self, start=None, limit=None): return self.send(self.db_uid, 'RANGE', [start, limit]) def RangeIter(self, start=None, limit=None): range_datas = self.Range(start, limit) return RangeIter(range_datas)
Move download_url and bump version
import setuptools from gitvendor.version import Version from setuptools import find_packages CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Topic :: Software Development' ] setuptools.setup(name='git-vendor', version=Version('0.0.3').number, description='Vendor tagged releases from git to $VCS', long_description=open('README.md').read().strip(), author='Charles Butler', author_email='[email protected]', url='http://github.com/chuckbutler/git-vendor', download_url='https://github.com/chuckbutler/git-vendor/releases/', py_modules=[], packages=find_packages(), entry_points={ 'console_scripts': [ 'git-vendor = gitvendor.cli:main' ], }, install_requires=['gitpython', 'jinja2', 'pyyaml', 'path.py', 'dirsync', 'six'], package_data={ 'template': ['template/vendor-rc'], }, include_package_data=True, license='MIT License', zip_safe=False, keywords='git, vendor', classifiers=CLASSIFIERS)
import setuptools from gitvendor.version import Version from setuptools import find_packages CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Topic :: Software Development' ] setuptools.setup(name='git-vendor', version=Version('0.0.1').number, description='Vendor tagged releases from git to $VCS', long_description=open('README.md').read().strip(), author='Charles Butler', author_email='[email protected]', url='http://github.com/chuckbutler/git-vendor', py_modules=[], packages=find_packages(), entry_points={ 'console_scripts': [ 'git-vendor = gitvendor.cli:main' ], }, install_requires=['gitpython', 'jinja2', 'pyyaml', 'path.py', 'dirsync', 'six'], package_data={ 'template': ['template/vendor-rc'], }, include_package_data=True, license='MIT License', zip_safe=False, keywords='git, vendor', classifiers=CLASSIFIERS)
Sort by review count by default
var app = angular.module('foodfood', ['ui.router', 'ngSanitize', 'ngStorage']); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/main'); $stateProvider .state('main', { url: '/main', views: { '': { templateUrl: './views/main.html', controller: 'inputsController' }, 'options@main': { templateUrl: './views/options.html', controller: 'optionsController' }, 'addresses@main': { templateUrl: './views/addresses.html', controller: 'addressesController' } } }) .state('main.map', { url: '/map', views: { 'restaurantList': { templateUrl: './views/places.html', controller: function($scope, RestaurantAndRoute, Auth, Addresses) { // restaurants from the server $scope.sortTerm = '-review_count'; $scope.setSortTerm = function (input) { if ($scope.sortTerm[0] === '-') { if ($scope.sortTerm.slice(1) === input) { $scope.sortTerm = input; } else { $scope.sortTerm = input; } } else { if ($scope.sortTerm === input) { $scope.sortTerm = '-' + input; } else { $scope.sortTerm = input; } } }; $scope.restaurants = RestaurantAndRoute.getRestaurants(); } } } }) }])
var app = angular.module('foodfood', ['ui.router', 'ngSanitize', 'ngStorage']); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/main'); $stateProvider .state('main', { url: '/main', views: { '': { templateUrl: './views/main.html', controller: 'inputsController' }, 'options@main': { templateUrl: './views/options.html', controller: 'optionsController' }, 'addresses@main': { templateUrl: './views/addresses.html', controller: 'addressesController' } } }) .state('main.map', { url: '/map', views: { 'restaurantList': { templateUrl: './views/places.html', controller: function($scope, RestaurantAndRoute, Auth, Addresses) { // restaurants from the server $scope.sortTerm = '-rating'; $scope.setSortTerm = function (input) { if ($scope.sortTerm[0] === '-') { if ($scope.sortTerm.slice(1) === input) { $scope.sortTerm = input; } else { $scope.sortTerm = input; } } else { if ($scope.sortTerm === input) { $scope.sortTerm = '-' + input; } else { $scope.sortTerm = input; } } }; $scope.restaurants = RestaurantAndRoute.getRestaurants(); } } } }) }])
Add placeable to javascript context
import json import rexviewer as r import naali import urllib2 from componenthandler import DynamiccomponentHandler class JavascriptHandler(DynamiccomponentHandler): GUINAME = "Javascript Handler" def __init__(self): DynamiccomponentHandler.__init__(self) self.jsloaded = False def onChanged(self): print "-----------------------------------" ent = r.getEntity(self.comp.GetParentEntityId()) datastr = self.comp.GetAttribute() #print "GetAttr got:", datastr data = json.loads(datastr) js_src = data.get('js_src', None) if not self.jsloaded and js_src is not None: jscode = self.loadjs(js_src) print jscode ctx = { #'entity'/'this': self.entity 'component': self.comp } try: ent.touchable except AttributeError: pass else: ctx['touchable'] = ent.touchable try: ent.placeable except: pass else: ctx['placeable'] = ent.placeable naali.runjs(jscode, ctx) print "-- done with js" self.jsloaded = True def loadjs(self, srcurl): print "js source url:", srcurl f = urllib2.urlopen(srcurl) return f.read()
import json import rexviewer as r import naali import urllib2 from componenthandler import DynamiccomponentHandler class JavascriptHandler(DynamiccomponentHandler): GUINAME = "Javascript Handler" def __init__(self): DynamiccomponentHandler.__init__(self) self.jsloaded = False def onChanged(self): print "-----------------------------------" ent = r.getEntity(self.comp.GetParentEntityId()) datastr = self.comp.GetAttribute() #print "GetAttr got:", datastr data = json.loads(datastr) js_src = data.get('js_src', None) if not self.jsloaded and js_src is not None: jscode = self.loadjs(js_src) print jscode ctx = { #'entity'/'this': self.entity 'component': self.comp } try: ent.touchable except AttributeError: pass else: ctx['touchable'] = ent.touchable naali.runjs(jscode, ctx) print "-- done with js" self.jsloaded = True def loadjs(self, srcurl): print "js source url:", srcurl f = urllib2.urlopen(srcurl) return f.read()
Add project as request attribute to save a little boilerplate
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): path = urlquote(request.get_full_path()) if not request.session.get("project"): return HttpResponseRedirect("/projects/list/?next=%s" % path) request.project = request.session.get("project") return func(request, *args, **kwargs) return wrapper def saves_files(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): temp = request.path.startswith(("/nodelib/")) project = request.session.get("project") output_path = None if project is None: temp = True if temp: output_path = os.path.join( settings.MEDIA_ROOT, settings.TEMP_PATH, request.user.username, datetime.now().strftime("%Y%m%d%H%M%S") ) else: output_path = os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH, project.slug ) request.__class__.output_path = output_path return func(request, *args, **kwargs) return wrapper
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): path = urlquote(request.get_full_path()) if not request.session.get("project"): return HttpResponseRedirect("/projects/list/?next=%s" % path) return func(request, *args, **kwargs) return wrapper def saves_files(func): """ Decorator function for other actions that require a project to be open in the session. """ def wrapper(request, *args, **kwargs): temp = request.path.startswith(("/nodelib/")) project = request.session.get("project") output_path = None if project is None: temp = True if temp: output_path = os.path.join( settings.MEDIA_ROOT, settings.TEMP_PATH, request.user.username, datetime.now().strftime("%Y%m%d%H%M%S") ) else: output_path = os.path.join( settings.MEDIA_ROOT, settings.USER_FILES_PATH, project.slug ) request.__class__.output_path = output_path return func(request, *args, **kwargs) return wrapper
Add viewEventSchedules function to read all schedules for an event.
var base = require('./base.js'); exports.assemble = { addSchedule: function (parameters, response) { var userEventEntry = { availability: JSON.stringify(parameters.availability), Users_id: parameters.usersid, Events_id: parameters.eventsid }; base.dbInsert('userevents', userEventEntry, response); }, viewUser: function (parameters , response) { var userReadInfo = { Users_id: parameters.usersid }; var queryString = 'SELECT * FROM Users WHERE id = ' + userReadInfo; base.dbSelect(queryString, response); }, viewEventSchedules: function (parameters, response) { var eventSchedules = { Events_id: parameters.eventsid }; var queryString = 'SELECT start_date, end_date FROM Events WHERE id = ' + eventSchedules; base.dbSelect(queryString, response); }, addEvent: function (parameters, response) { var eventEntry = { name: parameters.eventName, start_date: parameters.eventStartDate, end_date: parameters.eventEndDate, description: parameters.eventDescription }; base.dbInsert('events', eventEntry, response); } }
var base = require('./base.js'); exports.assemble = { addSchedule: function (parameters, response) { var userEventEntry = { availability: JSON.stringify(parameters.availability), Users_id: parameters.usersid, Events_id: parameters.eventsid }; base.dbInsert('userevents', userEventEntry, response); }, viewUser: function (parameters , response) { var userReadInfo = { Users_id: parameters.usersid }; var queryString = 'SELECT * FROM Users WHERE id = ' + userReadInfo; base.dbSelect(queryString, response) }, addEvent: function (parameters, response) { var eventEntry = { name: parameters.eventName, start_date: parameters.eventStartDate, end_date: parameters.eventEndDate, description: parameters.eventDescription }; base.dbInsert('events', eventEntry, response); } }
Replace the use of the list for a set to emphasize the semantics.
""" banana.maya.MFileIO ~~~~~~~~~~~~~~~~~~~ Monkey patching of the `~maya.OpenMaya.MFileIO` class. :copyright: Copyright 2014 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ import gorilla from maya import OpenMaya @gorilla.patch(OpenMaya) class MFileIO(object): @classmethod def bnn_importFile(cls, fileName, type='', preserveReferences=False, nameSpace='', ignoreVersion=False): """Import a file into the current Maya session. Parameters ---------- fileName : str File name to import. type : str, optional Type of the file to import. preserveReferences : bool, optional True if the references needs to be preserved. nameSpace : str, optional Namespace to use when importing the objects. ignoreVersion : bool, optional True to ignore the version. Returns ------- list of maya.OpenMaya.MDagPath The top level transforms imported. """ if not type: type = None if not nameSpace: nameSpace = None topLevelDagPaths = set(OpenMaya.bnn_MItDagHierarchy()) OpenMaya.MFileIO.importFile(fileName, type, preserveReferences, nameSpace, ignoreVersion) return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy() if not dagPath in topLevelDagPaths]
""" banana.maya.MFileIO ~~~~~~~~~~~~~~~~~~~ Monkey patching of the `~maya.OpenMaya.MFileIO` class. :copyright: Copyright 2014 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ import gorilla from maya import OpenMaya @gorilla.patch(OpenMaya) class MFileIO(object): @classmethod def bnn_importFile(cls, fileName, type='', preserveReferences=False, nameSpace='', ignoreVersion=False): """Import a file into the current Maya session. Parameters ---------- fileName : str File name to import. type : str, optional Type of the file to import. preserveReferences : bool, optional True if the references needs to be preserved. nameSpace : str, optional Namespace to use when importing the objects. ignoreVersion : bool, optional True to ignore the version. Returns ------- list of maya.OpenMaya.MDagPath The top level transforms imported. """ if not type: type = None if not nameSpace: nameSpace = None topLevelDagPaths = list(OpenMaya.bnn_MItDagHierarchy()) OpenMaya.MFileIO.importFile(fileName, type, preserveReferences, nameSpace, ignoreVersion) return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy() if not dagPath in topLevelDagPaths]
Configure MIDDLEWARE_CLASSES in test settings Django 1.7 complained: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. Set this setting to nothing to make Django happy.
#!/usr/bin/env python import sys import django from django.conf import settings if not settings.configured: settings.configure( AUTHENTICATION_BACKENDS=( 'django_authgroupex.auth.AuthGroupeXBackend', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django_authgroupex', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner', AUTHGROUPEX_LOGIN_REDIRECT_URL='/login-success/', MIDDLEWARE_CLASSES=() ) from django.test.utils import get_runner def runtests(): if hasattr(django, 'setup'): django.setup() apps = ['django_authgroupex', ] TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(apps) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import sys import django from django.conf import settings if not settings.configured: settings.configure( AUTHENTICATION_BACKENDS=( 'django_authgroupex.auth.AuthGroupeXBackend', ), DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django_authgroupex', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner', AUTHGROUPEX_LOGIN_REDIRECT_URL='/login-success/' ) from django.test.utils import get_runner def runtests(): if hasattr(django, 'setup'): django.setup() apps = ['django_authgroupex', ] TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(apps) sys.exit(failures) if __name__ == '__main__': runtests()
Update /signin link to /login
import React, { Component } from 'react' import { Link, IndexLink } from 'react-router' export class Nav extends Component { constructor(props) { super(props) } render() { return ( <nav className="transparent haze-background wrap navbar navbar-default" role="navigation"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="haze-background navbar-toggle collapsed" data-toggle="collapse" data-target="#navigation"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> </div> <div className="brand-centered"> <IndexLink to="/" className="navbar-brand">Journey</IndexLink> </div> <div className="navbar-collapse collapse" id="navigation"> <ul className="nav navbar-nav navbar-left"> <li><Link activeClassName="nav-active" to="/journal">Journal</Link></li> <li><Link activeClassName="nav-active" to="/dashboard">Dashboard</Link></li> </ul> <ul className="nav navbar-nav navbar-right"> <li><Link activeClassName="nav-active" to="/profile">Profile</Link></li> <li><Link activeClassName="nav-active" to="/login">Log In</Link></li> </ul> </div> </div> </nav> ) } }
import React, { Component } from 'react' import { Link, IndexLink } from 'react-router' export class Nav extends Component { constructor(props) { super(props) } render() { return ( <nav className="transparent haze-background wrap navbar navbar-default" role="navigation"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="haze-background navbar-toggle collapsed" data-toggle="collapse" data-target="#navigation"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> </div> <div className="brand-centered"> <IndexLink to="/" className="navbar-brand">Journey</IndexLink> </div> <div className="navbar-collapse collapse" id="navigation"> <ul className="nav navbar-nav navbar-left"> <li><Link activeClassName="nav-active" to="/journal">Journal</Link></li> <li><Link activeClassName="nav-active" to="/dashboard">Dashboard</Link></li> </ul> <ul className="nav navbar-nav navbar-right"> <li><Link activeClassName="nav-active" to="/profile">Profile</Link></li> <li><Link activeClassName="nav-active" to="/signin">Log In</Link></li> </ul> </div> </div> </nav> ) } }
Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index, hostname=None, source=None, sourcetype='json'): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index self.source = source self.sourcetype = sourcetype if hostname is None: self.hostname = socket.gethostname() else: self.hostname = hostname # prevent infinite recursion by silencing requests logger requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: if self.source is None: source = record.pathname else: source = self.source params = { 'host': self.hostname, 'index': self.index, 'source': source, 'sourcetype': self.sourcetype } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
Remove unused Joystick import from the main robot class.
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.edinarobotics.zephyr; import com.edinarobotics.utils.gamepad.Gamepad; import edu.wpi.first.wpilibj.SimpleRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Zephyr extends SimpleRobot { /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { Gamepad gamepad1 = new Gamepad(1); Components components = Components.getInstance(); while(this.isOperatorControl()&&this.isEnabled()){ components.leftJaguar.set(gamepad1.getLeftY()); components.rightJaguar.set(gamepad1.getRightY()); } components.leftJaguar.set(0); components.rightJaguar.set(0); } }
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.edinarobotics.zephyr; import com.edinarobotics.utils.gamepad.Gamepad; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.SimpleRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Zephyr extends SimpleRobot { /** * This function is called once each time the robot enters autonomous mode. */ public void autonomous() { } /** * This function is called once each time the robot enters operator control. */ public void operatorControl() { Gamepad gamepad1 = new Gamepad(1); Components components = Components.getInstance(); while(this.isOperatorControl()&&this.isEnabled()){ components.leftJaguar.set(gamepad1.getLeftY()); components.rightJaguar.set(gamepad1.getRightY()); } components.leftJaguar.set(0); components.rightJaguar.set(0); } }
Use the extracted method, not the original helper.
<?php namespace DoSomething\Gateway\Common; class Introspector { /** * Returns all traits used by a class, its subclasses and trait of their traits. * @see illuminate/support's `class_uses_recursive` * * @param object|string $class * @return array */ public static function getAllClassTraits($class) { $results = []; foreach (array_merge([$class => $class], class_parents($class)) as $class) { $results += self::getAllTraits($class); } return array_unique($results); } /** * Get the base name of a namespaced class string/object. * @see illuminate/support's `class_basename` * * @param $class * @return string */ public static function baseName($class) { $class = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $class)); } /** * Returns all traits used by a trait and its traits. * @see illuminate/support's `trait_uses_recursive` * * @param string $trait * @return array */ public static function getAllTraits($trait) { $traits = class_uses($trait); foreach ($traits as $trait) { $traits += self::getAllTraits($trait); } return $traits; } }
<?php namespace DoSomething\Gateway\Common; class Introspector { /** * Returns all traits used by a class, its subclasses and trait of their traits. * @see illuminate/support's `class_uses_recursive` * * @param object|string $class * @return array */ public static function getAllClassTraits($class) { $results = []; foreach (array_merge([$class => $class], class_parents($class)) as $class) { $results += self::getAllTraits($class); } return array_unique($results); } /** * Get the base name of a namespaced class string/object. * @see illuminate/support's `class_basename` * * @param $class * @return string */ public static function baseName($class) { $class = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $class)); } /** * Returns all traits used by a trait and its traits. * @see illuminate/support's `trait_uses_recursive` * * @param string $trait * @return array */ public static function getAllTraits($trait) { $traits = class_uses($trait); foreach ($traits as $trait) { $traits += trait_uses_recursive($trait); } return $traits; } }
Rename GET parameter from ?filter to ?search
export default class AutoCompleteSubjects { constructor(wrapper) { this.wrapper = wrapper; } initialize(selector) { const $input = this.wrapper.find('input[type=text]'); const $realInput = this.wrapper.find('input[type=hidden]'); const jsonUrl = this.wrapper.data("url"); $input.materialize_autocomplete({ multiple: { enable: false }, dropdown: { el: '.dropdown-content', itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>', }, getData: function (value, callback) { const url = jsonUrl + `?search=${value}`; $.ajax({ url: url, }) .then(data => { callback(value, data); }); }, onSelect: function (item) { $realInput.val(item.id); }, }); } }
export default class AutoCompleteSubjects { constructor(wrapper) { this.wrapper = wrapper; } initialize(selector) { const $input = this.wrapper.find('input[type=text]'); const $realInput = this.wrapper.find('input[type=hidden]'); const jsonUrl = this.wrapper.data("url"); $input.materialize_autocomplete({ multiple: { enable: false }, dropdown: { el: '.dropdown-content', itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>', }, getData: function (value, callback) { const url = jsonUrl + `?filter=${value}`; $.ajax({ url: url, }) .then(data => { callback(value, data); }); }, onSelect: function (item) { $realInput.val(item.id); }, }); } }
fix(Service): Fix disappearing cursor in services Workaround for disappearing cursors in webviews
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import ElectronWebView from 'react-electron-web-view'; import ServiceModel from '../../../models/Service'; @observer class ServiceWebview extends Component { static propTypes = { service: PropTypes.instanceOf(ServiceModel).isRequired, setWebviewReference: PropTypes.func.isRequired, detachService: PropTypes.func.isRequired, }; webview = null; componentWillUnmount() { const { service, detachService } = this.props; detachService({ service }); } refocusWebview = () => { const { webview } = this; if (!webview) return; webview.view.blur(); webview.view.focus(); }; render() { const { service, setWebviewReference, } = this.props; return ( <ElectronWebView ref={(webview) => { this.webview = webview; webview.view.addEventListener('did-stop-loading', this.refocusWebview); }} autosize src={service.url} preload="./webview/recipe.js" partition={`persist:service-${service.id}`} onDidAttach={() => { setWebviewReference({ serviceId: service.id, webview: this.webview.view, }); }} onUpdateTargetUrl={this.updateTargetUrl} useragent={service.userAgent} disablewebsecurity={service.recipe.disablewebsecurity} allowpopups /> ); } } export default ServiceWebview;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import ElectronWebView from 'react-electron-web-view'; import ServiceModel from '../../../models/Service'; @observer class ServiceWebview extends Component { static propTypes = { service: PropTypes.instanceOf(ServiceModel).isRequired, setWebviewReference: PropTypes.func.isRequired, detachService: PropTypes.func.isRequired, }; webview = null; componentWillUnmount() { const { service, detachService } = this.props; detachService({ service }); } render() { const { service, setWebviewReference, } = this.props; return ( <ElectronWebView ref={(webview) => { this.webview = webview; }} autosize src={service.url} preload="./webview/recipe.js" partition={`persist:service-${service.id}`} onDidAttach={() => { setWebviewReference({ serviceId: service.id, webview: this.webview.view, }); }} onUpdateTargetUrl={this.updateTargetUrl} useragent={service.userAgent} disablewebsecurity={service.recipe.disablewebsecurity} allowpopups /> ); } } export default ServiceWebview;
Insert dummy data for intercepts.
<?php declare(strict_types=1); namespace mcordingley\Regression\RegressionAlgorithm; use InvalidArgumentException; use mcordingley\LinearAlgebra\Matrix; use mcordingley\Regression\CoefficientSet; use mcordingley\Regression\DataBag; use mcordingley\Regression\RegressionAlgorithm; final class LinearLeastSquares implements RegressionAlgorithm { public function regress(DataBag $data): CoefficientSet { $dependentData = $data->getDependents(); $independentData = $data->getIndependents(); // Prepend dummies. $independentData = array_map(function ($row) { return array_merge([1], $row); }, $independentData); $design = new Matrix($independentData); $observed = (new Matrix([ $dependentData ]))->transpose(); if ($design->columns >= $design->rows) { throw new InvalidArgumentException('Not enough observations to perform regression. You need to have more observations than explanatory variables.'); } $designTranspose = $design->transpose(); $prediction = $designTranspose ->multiply($design) ->inverse() ->multiply($designTranspose->multiply($observed)); // Extract the vertical vector as a simple array. return new CoefficientSet($prediction->transpose()->toArray()[0]); } }
<?php declare(strict_types=1); namespace mcordingley\Regression\RegressionAlgorithm; use InvalidArgumentException; use mcordingley\LinearAlgebra\Matrix; use mcordingley\Regression\CoefficientSet; use mcordingley\Regression\DataBag; use mcordingley\Regression\RegressionAlgorithm; final class LinearLeastSquares implements RegressionAlgorithm { public function regress(DataBag $data): CoefficientSet { $dependentData = $data->getDependents(); $independentData = $data->getIndependents(); $design = new Matrix($independentData); $observed = (new Matrix([ $dependentData ]))->transpose(); if ($design->columns >= $design->rows) { throw new InvalidArgumentException('Not enough observations to perform regression. You need to have more observations than explanatory variables.'); } $designTranspose = $design->transpose(); $prediction = $designTranspose ->multiply($design) ->inverse() ->multiply($designTranspose->multiply($observed)); // Extract the vertical vector as a simple array. return new CoefficientSet($prediction->transpose()->toArray()[0]); } }
Fix issue where task list appears above search result
var React = require('react'), StateMixin = require('../mixins/app-StateMixin'), SearchBox = require('../components/app-SearchBox'), TaskList = require('../components/app-TaskList'); var MainCard = React.createClass({ mixins: [StateMixin], render: function () { "use strict"; return ( <div className="card"> <div className="card-main"> <div className="card-header"> <div className="card-inner-side pull-left"> <div className="card-inner"> <span>Pick Your Tasks</span> </div> </div> </div> <SearchBox items={this.state.filteredResult}/> <div> <TaskList items={this.state.activeItems} activities={this.state.activities} customFields={this.state.settings.customFields}/> </div> </div> </div> ); } }); module.exports = MainCard;
var React = require('react'), StateMixin = require('../mixins/app-StateMixin'), SearchBox = require('../components/app-SearchBox'), TaskList = require('../components/app-TaskList'); var MainCard = React.createClass({ mixins: [StateMixin], render: function () { "use strict"; return ( <div className="card"> <div className="card-main"> <div className="card-header"> <div className="card-inner-side pull-left"> <div className="card-inner"> <span>Pick Your Tasks</span> </div> </div> </div> <SearchBox items={this.state.filteredResult}/> <div className="card-inner"> <TaskList items={this.state.activeItems} activities={this.state.activities} customFields={this.state.settings.customFields}/> </div> </div> </div> ); } }); module.exports = MainCard;
Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation
from django.forms import forms from south.modelsinspector import add_introspection_rules from validatedfile.fields import ValidatedFileField class RWValidatedFileField(ValidatedFileField): """ Same as FileField, but you can specify: * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] """ def __init__(self, content_types=None, **kwargs): if content_types: self.content_types = content_types super(RWValidatedFileField, self).__init__(**kwargs) def clean(self, *args, **kwargs): # ValidatedFileField.clean will check the MIME type from the # http headers and by peeking in the file data = super(RWValidatedFileField, self).clean(*args, **kwargs) file = data.file # next scan with pyclamav tmpfile = file.file.name import pyclamav has_virus, virus_name = pyclamav.scanfile(tmpfile) if has_virus: fn = file.name raise forms.ValidationError( 'The file %s you uploaded appears to contain a virus or be' 'malware (%s).' % (fn, virus_name) ) return data add_introspection_rules([], ["^roundware\.rw\.fields\.RWValidatedFileField"])
from django.forms import forms from south.modelsinspector import add_introspection_rules from validatedfile.fields import ValidatedFileField import pyclamav class RWValidatedFileField(ValidatedFileField): """ Same as FileField, but you can specify: * content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg'] """ def __init__(self, content_types=None, **kwargs): if content_types: self.content_types = content_types super(RWValidatedFileField, self).__init__(**kwargs) def clean(self, *args, **kwargs): # ValidatedFileField.clean will check the MIME type from the # http headers and by peeking in the file data = super(RWValidatedFileField, self).clean(*args, **kwargs) file = data.file # next scan with pyclamav tmpfile = file.file.name has_virus, virus_name = pyclamav.scanfile(tmpfile) if has_virus: fn = file.name raise forms.ValidationError( 'The file %s you uploaded appears to contain a virus or be' 'malware (%s).' % (fn, virus_name) ) return data add_introspection_rules([], ["^roundware\.rw\.fields\.RWValidatedFileField"])
Integrate response factory into the deck controller."
<?php namespace MoFlashCards\DeckBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class DeckController extends Controller { /** * Lists all available decks. * * @return Response */ public function listAction() { $decks = $this->get('doctrine_mongodb') ->getRepository('DeckBundle:Deck') ->findAll(); return $this->get('utility.response.factory') ->createSerializedResponse($decks, ['list']); } /** * Loads a certain deck by it's slug. * * @param string $slug * @return Response */ public function getAction($slug) { $deck = $this->get('doctrine_mongodb') ->getRepository('DeckBundle:Deck') ->findOneBySlug($slug); if (!$deck) { throw new NotFoundHttpException(); } return $this->get('utility.response.factory') ->createSerializedResponse($deck, ['details']); } }
<?php namespace MoFlashCards\DeckBundle\Controller; use JMS\Serializer\SerializationContext; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class DeckController extends Controller { /** * Lists all available decks. * * @return Response */ public function listAction() { $decks = $this->get('doctrine_mongodb') ->getRepository('DeckBundle:Deck') ->findAll(); $context = SerializationContext::create()->setGroups(['list']); $json = $this->get('jms_serializer')->serialize($decks, 'json', $context); $response = new Response(); $response->setContent($json); $response->headers->set('Content-Type', 'application/json'); return $response; } /** * Loads a certain deck by it's slug. * * @param string $slug * @return Response */ public function getAction($slug) { $deck = $this->get('doctrine_mongodb') ->getRepository('DeckBundle:Deck') ->findOneBySlug($slug); if (!$deck) { throw new NotFoundHttpException(); } $context = SerializationContext::create()->setGroups(['details']); $json = $this->get('jms_serializer')->serialize($deck, 'json', $context); $response = new Response(); $response->setContent($json); $response->headers->set('Content-Type', 'application/json'); return $response; } }
Add missing jshint override and always use string `displayValue`.
(function () { 'use strict'; define( [ 'lodash', 'knockout' ], function (_, ko) { return function (selectedSearchTypeObservable, resultFieldsObservable, detailUrlTemplate) { return { mapType: function (searchType) { return { key: searchType.key, label: '<span class="small glyphicon glyphicon-' + searchType.glyphicon + '"></span> ' + searchType.labelText, placeholder: 'Search by ' + searchType.labelText + '...', active: ko.pureComputed(function () { return selectedSearchTypeObservable() === searchType.key; }), makeActive: function () { selectedSearchTypeObservable(searchType.key); } }; }, mapResult: function (result) { return _(result) .mapValues(function (value, key) { var field = _.find(resultFieldsObservable(), { key: key }) || {}; return { key: key, value: value, displayValue: _.isFunction(field.displayValue) ? field.displayValue(value) : '' + value }; }) .merge({ // jshint sub: true detailUrl: detailUrlTemplate.replace(':id', result['object_id']) }) .value(); } }; }; } ); }());
(function () { 'use strict'; define( [ 'lodash', 'knockout' ], function (_, ko) { return function (selectedSearchTypeObservable, resultFieldsObservable, detailUrlTemplate) { return { mapType: function (searchType) { return { key: searchType.key, label: '<span class="small glyphicon glyphicon-' + searchType.glyphicon + '"></span> ' + searchType.labelText, placeholder: 'Search by ' + searchType.labelText + '...', active: ko.pureComputed(function () { return selectedSearchTypeObservable() === searchType.key; }), makeActive: function () { selectedSearchTypeObservable(searchType.key); } }; }, mapResult: function (result) { return _(result) .mapValues(function (value, key) { var field = _.find(resultFieldsObservable(), { key: key }) || {}; return { key: key, value: value, displayValue: _.isFunction(field.displayValue) ? field.displayValue(value) : value }; }) .merge({ detailUrl: detailUrlTemplate.replace(':id', result['object_id']) }) .value(); } }; }; } ); }());
Fix getChainedByMaster if there are not additional subroots fixes test
<?php class Kwc_Chained_Start_Component extends Kwc_Abstract { public static function getSettings() { $ret = parent::getSettings(); $ret['flags']['hasAllChainedByMaster'] = true; return $ret; } public static function validateSettings($settings, $componentClass) { parent::validateSettings($settings, $componentClass); if (!isset($settings['flags']['chainedType']) || !is_string($settings['flags']['chainedType'])) { throw new Kwf_Exception("Flag 'chainedType' not set for '$componentClass'."); } } public static function getAllChainedByMasterFromChainedStart($componentClass, $master, $chainedType, $parentDataSelect = array()) { if (Kwc_Abstract::getFlag($componentClass, 'chainedType') != $chainedType) return array(); $ret = array(); foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($componentClass, $parentDataSelect) as $chainedStart) { //if additional subroots are above trl subroot (eg. domains) if ($sr = $chainedStart->parent->getSubroot()) { $masterSr = $master->getSubroot(); if ($masterSr->parent && $sr != $masterSr->parent->getSubroot()) { continue; } } $i = Kwc_Chained_Abstract_Component::getChainedByMaster($master, $chainedStart, $chainedType, $parentDataSelect); if ($i) $ret[] = $i; } return $ret; } }
<?php class Kwc_Chained_Start_Component extends Kwc_Abstract { public static function getSettings() { $ret = parent::getSettings(); $ret['flags']['hasAllChainedByMaster'] = true; return $ret; } public static function validateSettings($settings, $componentClass) { parent::validateSettings($settings, $componentClass); if (!isset($settings['flags']['chainedType']) || !is_string($settings['flags']['chainedType'])) { throw new Kwf_Exception("Flag 'chainedType' not set for '$componentClass'."); } } public static function getAllChainedByMasterFromChainedStart($componentClass, $master, $chainedType, $parentDataSelect = array()) { if (Kwc_Abstract::getFlag($componentClass, 'chainedType') != $chainedType) return array(); $ret = array(); foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($componentClass, $parentDataSelect) as $chainedStart) { //if additional subroots are above trl subroot (eg. domains) if ($sr = $chainedStart->parent->getSubroot()) { if ($sr != $master->getSubroot()->parent->getSubroot()) { continue; } } $i = Kwc_Chained_Abstract_Component::getChainedByMaster($master, $chainedStart, $chainedType, $parentDataSelect); if ($i) $ret[] = $i; } return $ret; } }
Read More module: refactoring and made regex more forgiving
<?php class ReadMore extends Modules { public function __init() { # Replace comment codes before markup modules filters them. $this->setPriority("markup_post_text", 4); } public function markup_post_text($text, $post = null) { if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches)) return $text; $route = Route::current(); $controller = $route->controller; if ($route->action == "view" or ($controller instanceof MainController and $controller->feed)) return preg_replace("/<!-- *more(.+?)?-->/i", "", $text); $more = oneof(trim(fallback($matches[1])), __("&hellip;more", "read_more")); $url = (isset($post) and !$post->no_results) ? $post->url() : "#" ; $split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY); return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>'; } public function title_from_excerpt($text) { $split = preg_split('/<a class="read_more"/', $text); return $split[0]; } }
<?php class ReadMore extends Modules { public function __init() { $this->addAlias("markup_post_text", "more", 4); # Replace "<!--more-->" before markup modules filter it. } public function more($text, $post = null) { if (!is_string($text) or preg_match("/<!--more(.+?)?-->/i", $text, $matches) === 0) return $text; $route = Route::current(); $controller = $route->controller; if ($route->action == "view" or $route->action == "preview" or ($controller instanceof MainController and $controller->feed)) return preg_replace("/<!--more(.+?)?-->/i", "", $text); $more = oneof(trim(fallback($matches[1])), __("&hellip;more", "read_more")); $url = (isset($post) and !$post->no_results) ? $post->url() : "#" ; $split = preg_split("/<!--more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY); return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>'; } public function title_from_excerpt($text) { $split = preg_split('/<a class="read_more"/', $text); return $split[0]; } }
Increase service worker cache version
var CACHE_NAME = 'buddhabrot-2017-10-12-2'; var urlsToCache = [ '.', '/', '/main.js', '/material-components-web.min.css', '/material-components-web.min.js', '/rust-logo-blk.svg', '/rustybrot.asmjs.js', '/rustybrot.wasm', '/rustybrot.wasm.js', '/worker-compositor.js', '/worker-producer.js', '/manifest.json', '/icon.png' ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); } ) ); }); this.addEventListener('activate', function(event) { var cacheWhitelist = ['buddhabrot-2017-10-12-2']; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } })); }) ); });
var CACHE_NAME = 'buddhabrot-2017-10-12-1'; var urlsToCache = [ '.', '/', '/main.js', '/material-components-web.min.css', '/material-components-web.min.js', '/rust-logo-blk.svg', '/rustybrot.asmjs.js', '/rustybrot.wasm', '/rustybrot.wasm.js', '/worker-compositor.js', '/worker-producer.js', '/manifest.json', '/icon.png' ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); } ) ); }); this.addEventListener('activate', function(event) { var cacheWhitelist = ['buddhabrot-2017-10-12-1']; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } })); }) ); });
Rename result parameter to output in CLI
'use(strict)' import {read, write} from '.' import * as argsParser from './util/args' export default function () { var args = process.argv.slice(2) let opts = argsParser .option('--type', '-t', null) .option('--base', '-b', null) .option('--expand', '-e', false) // .option('--flatten', '-f', false) // .option('--compact', '-c', false) .option('--index', '-i', false) .option('--pattern', '-p', false) .option('--output', '-o', null) .parse(args) read(opts.args[0], opts).then(async result => { if (opts.expand || opts.pattern) { const cx = await import('./jsonld/algorithm') result = cx.expand({}, result) } if (opts.index || opts.pattern) { const indexer = await import('./util/indexer') result = indexer.index(result, opts.pattern === void 0) } if (opts.pattern) { const {expandPatterns} = await import('./rdfa/copypattern') expandPatterns(result.byId) result = { '@context': result['@context'], '@graph': Object.values(result.byId) } } if (opts.output) { let rtype = opts.output await write(result, {type: rtype}) return } console.log(JSON.stringify(result, null, 2)) }) }
'use(strict)' import {read, write} from '.' import * as argsParser from './util/args' export default function () { var args = process.argv.slice(2) let opts = argsParser .option('--type', '-t', null) .option('--base', '-b', null) .option('--expand', '-e', false) // .option('--flatten', '-f', false) // .option('--compact', '-c', false) .option('--index', '-i', false) .option('--pattern', '-p', false) .option('--result', '-r', null) .parse(args) read(opts.args[0], opts).then(async result => { if (opts.expand || opts.pattern) { const cx = await import('./jsonld/algorithm') result = cx.expand({}, result) } if (opts.index || opts.pattern) { const indexer = await import('./util/indexer') result = indexer.index(result, opts.pattern === void 0) } if (opts.pattern) { const {expandPatterns} = await import('./rdfa/copypattern') expandPatterns(result.byId) result = { '@context': result['@context'], '@graph': Object.values(result.byId) } } if (opts.result) { let rtype = opts.result await write(result, {type: rtype}) return } console.log(JSON.stringify(result, null, 2)) }) }
Fix typo breaking doc popups
import re import pydoc import gtk from data_format import insert_with_tag, is_data_object BOLD_RE = re.compile("(?:(.)\b(.))+") STRIP_BOLD_RE = re.compile("(.)\b(.)") def insert_docs(buf, iter, obj, bold_tag): """Insert documentation about obj into a gtk.TextBuffer buf -- the buffer to insert the documentation into iter -- the location to insert the documentation obj -- the object to get documentation about bold_tag -- the tag to use for bold text, such as headings """ # If the routine is an instance, we get help on the type instead if is_data_object(obj): obj = type(obj) name = getattr(obj, '__name__', None) document = pydoc.text.document(obj, name) # pydoc.text.document represents boldface with overstrikes, we need to # reverse engineer this and find the spans of bold text pos = 0 while True: m = BOLD_RE.search(document, pos) if m == None: # Strip the trailing newline; this isn't very justifiable in general terms, # but matches what we need in Reinteract if document.endswith("\n"): buf.insert(iter, document[pos:-1]) else: buf.insert(iter, document[pos:]) break buf.insert(iter, document[pos:m.start()]) insert_with_tag(buf, iter, STRIP_BOLD_RE.sub(lambda m: m.group(1), m.group()), bold_tag) pos = m.end()
import re import pydoc import gtk from data_format import insert_with_tag, is_data_object BOLD_RE = re.compile("(?:(.)\b(.))+") STRIP_BOLD_RE = re.compile("(.)\b(.)") def insert_docs(buf, iter, obj, bold_tag): """Insert documentation about obj into a gtk.TextBuffer buf -- the buffer to insert the documentation into iter -- the location to insert the documentation obj -- the object to get documentation about bold_tag -- the tag to use for bold text, such as headings """ # If the routine is an instance, we get help on the type instead if not is_data_object(obj): obj = type(obj) name = getattr(obj, '__name__', None) document = pydoc.text.document(obj, name) # pydoc.text.document represents boldface with overstrikes, we need to # reverse engineer this and find the spans of bold text pos = 0 while True: m = BOLD_RE.search(document, pos) if m == None: # Strip the trailing newline; this isn't very justifiable in general terms, # but matches what we need in Reinteract if document.endswith("\n"): buf.insert(iter, document[pos:-1]) else: buf.insert(iter, document[pos:]) break buf.insert(iter, document[pos:m.start()]) insert_with_tag(buf, iter, STRIP_BOLD_RE.sub(lambda m: m.group(1), m.group()), bold_tag) pos = m.end()
Use a uuid to identify component.
package adapters; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import converters.JsonConverter; import datamodel.EventHubMessage; import datamodel.Measurement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Date; import java.util.UUID; public class EventHubAdapter implements Adapter { private static final Logger logger = LoggerFactory.getLogger(EventHubAdapter.class); public static final UUID uuid = UUID.randomUUID(); public String adaptMessage(String filteredJson, Measurement measurement) { String command = measurement.getCommand(); String usedTool = command.substring(0, command.indexOf(' ')); ObjectMapper mapper = new ObjectMapper(); JsonNode data = null; try { data = mapper.readTree(filteredJson); } catch (IOException e) { logger.error(e.getMessage(), e); } EventHubMessage eventHubMessage = new EventHubMessage(); eventHubMessage.setComponent(uuid.toString()); eventHubMessage.setObject(usedTool); eventHubMessage.setLabels(new String[]{"userId-" + measurement.getClientId()}); eventHubMessage.setType(null); eventHubMessage.setData(data); eventHubMessage.setTimestamp((new Date().getTime()) / 1000); return JsonConverter.objectToJsonString(eventHubMessage); } }
package adapters; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import converters.JsonConverter; import datamodel.EventHubMessage; import datamodel.Measurement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Date; public class EventHubAdapter implements Adapter { private static final Logger logger = LoggerFactory.getLogger(EventHubAdapter.class); public String adaptMessage(String filteredJson, Measurement measurement) { String command = measurement.getCommand(); String usedTool = command.substring(0, command.indexOf(' ')); ObjectMapper mapper = new ObjectMapper(); JsonNode data = null; try { data = mapper.readTree(filteredJson); } catch (IOException e) { logger.error(e.getMessage(), e); } EventHubMessage eventHubMessage = new EventHubMessage(); eventHubMessage.setComponent(null); eventHubMessage.setObject(usedTool); eventHubMessage.setLabels(new String[]{"userId-" + measurement.getClientId()}); eventHubMessage.setType(null); eventHubMessage.setData(data); eventHubMessage.setTimestamp(Long.toString((new Date().getTime()) / 1000)); return JsonConverter.objectToJsonString(eventHubMessage); } }
Sort titles by lower case
"use strict"; /** * Collection of spines. **/ define([ "underscore", "backbone" ], function(_, Backbone) { var SpineCollection = Backbone.Collection.extend({ filterKey: null, /** * sortBy comparator: return the title, by which BB will sort the collection. **/ comparator: function(spine) { return spine.get("title").toLowerCase(); }, url: function() { var url = "_view/spines"; if (!_.isNull(this.filterKey)) { // Get a subset of the spines, by the given key. url = url + '?key="' + this.filterKey + '"'; } return url; }, /** * Parse the returned JSON. **/ parse: function(response, options){ var parsed = []; if (_.has(response, "rows") && _.isArray(response.rows)) { _.each(response.rows, function(row) { parsed.push({ id: row.id, firstLetter: row.value.firstLetter, title: row.value.title }); }); } return parsed; } }); return SpineCollection; });
"use strict"; /** * Collection of spines. **/ define([ "underscore", "backbone" ], function(_, Backbone) { var SpineCollection = Backbone.Collection.extend({ filterKey: null, /** * sortBy comparator: return the title, by which BB will sort the collection. **/ comparator: function(spine) { return spine.get("title"); }, url: function() { var url = "_view/spines"; if (!_.isNull(this.filterKey)) { // Get a subset of the spines, by the given key. url = url + '?key="' + this.filterKey + '"'; } return url; }, /** * Parse the returned JSON. **/ parse: function(response, options){ var parsed = []; if (_.has(response, "rows") && _.isArray(response.rows)) { _.each(response.rows, function(row) { parsed.push({ id: row.id, firstLetter: row.value.firstLetter, title: row.value.title }); }); } return parsed; } }); return SpineCollection; });
Reduce allocation of hadoop configuration objects
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import org.apache.hadoop.conf.Configuration; import javax.inject.Inject; import java.net.URI; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; public class HiveHdfsConfiguration implements HdfsConfiguration { private static final Configuration DEFAULT_CONFIGURATION = new Configuration(); @SuppressWarnings("ThreadLocalNotStaticFinal") private final ThreadLocal<Configuration> hadoopConfiguration = new ThreadLocal<Configuration>() { @Override protected Configuration initialValue() { Configuration config = new Configuration(false); for (Map.Entry<String, String> entry : DEFAULT_CONFIGURATION) { config.set(entry.getKey(), entry.getValue()); } updater.updateConfiguration(config); return config; } }; private final HdfsConfigurationUpdater updater; @Inject public HiveHdfsConfiguration(HdfsConfigurationUpdater updater) { this.updater = checkNotNull(updater, "updater is null"); } @Override public Configuration getConfiguration(URI uri) { // use the same configuration for everything return hadoopConfiguration.get(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import org.apache.hadoop.conf.Configuration; import javax.inject.Inject; import java.net.URI; import static com.google.common.base.Preconditions.checkNotNull; public class HiveHdfsConfiguration implements HdfsConfiguration { @SuppressWarnings("ThreadLocalNotStaticFinal") private final ThreadLocal<Configuration> hadoopConfiguration = new ThreadLocal<Configuration>() { @Override protected Configuration initialValue() { Configuration config = new Configuration(); updater.updateConfiguration(config); return config; } }; private final HdfsConfigurationUpdater updater; @Inject public HiveHdfsConfiguration(HdfsConfigurationUpdater updater) { this.updater = checkNotNull(updater, "updater is null"); } @Override public Configuration getConfiguration(URI uri) { // use the same configuration for everything return hadoopConfiguration.get(); } }
Fix the getByUser request, the field name is userId, not user
package uk.ac.ox.oucs.oauth.dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import uk.ac.ox.oucs.oauth.domain.Accessor; import java.sql.SQLException; import java.util.Date; import java.util.List; public class HibernateAccessorDao extends HibernateDaoSupport implements AccessorDao { public void create(final Accessor accessor) { getHibernateTemplate().save(accessor); } public Accessor get(String accessorId) { return (Accessor) getHibernateTemplate().get(Accessor.class, accessorId); } public List<Accessor> getByUser(String userId) { return (List<Accessor>) getHibernateTemplate().find( "FROM Accessor a WHERE a.userId = ?", new Object[]{userId}); } public void markExpiredAccessors() { getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { session.createQuery( "UPDATE Accessor a SET a.status=? WHERE a.expirationDate < ?") .setParameter(0, Accessor.Status.EXPIRED) .setDate(1, new Date()) .executeUpdate(); return null; } }); } public Accessor update(Accessor accessor) { getHibernateTemplate().update(accessor); return accessor; } public void remove(Accessor accessor) { getHibernateTemplate().delete(accessor); } }
package uk.ac.ox.oucs.oauth.dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import uk.ac.ox.oucs.oauth.domain.Accessor; import java.sql.SQLException; import java.util.Date; import java.util.List; public class HibernateAccessorDao extends HibernateDaoSupport implements AccessorDao { public void create(final Accessor accessor) { getHibernateTemplate().save(accessor); } public Accessor get(String accessorId) { return (Accessor) getHibernateTemplate().get(Accessor.class, accessorId); } public List<Accessor> getByUser(String userId) { return (List<Accessor>) getHibernateTemplate().find( "FROM Accessor a WHERE a.user = ?", new Object[]{userId}); } public void markExpiredAccessors() { getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { session.createQuery( "UPDATE Accessor a SET a.status=? WHERE a.expirationDate < ?") .setParameter(0, Accessor.Status.EXPIRED) .setDate(1, new Date()) .executeUpdate(); return null; } }); } public Accessor update(Accessor accessor) { getHibernateTemplate().update(accessor); return accessor; } public void remove(Accessor accessor) { getHibernateTemplate().delete(accessor); } }
Test deployment to PyPI from Travis
#!/usr/bin/env python # coding: utf8 # Copyright 2013-2015 Vincent Jacques <[email protected]> import setuptools version = "0.5.1" setuptools.setup( name="MockMockMock", version=version, description="Mocking library focusing on very explicit definition of the mocks' behaviour", author="Vincent Jacques", author_email="[email protected]", url="http://pythonhosted.org/MockMockMock", packages=setuptools.find_packages(), license="MIT", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python", "Topic :: Software Development", ], test_suite="MockMockMock.tests.AllTests", use_2to3=True, command_options={ "build_sphinx": { "version": ("setup.py", version), "release": ("setup.py", version), "source_dir": ("setup.py", "doc"), }, }, )
#!/usr/bin/env python # coding: utf8 # Copyright 2013-2015 Vincent Jacques <[email protected]> import setuptools version = "0.5.0" setuptools.setup( name="MockMockMock", version=version, description="Mocking library focusing on very explicit definition of the mocks' behaviour", author="Vincent Jacques", author_email="[email protected]", url="http://pythonhosted.org/MockMockMock", packages=setuptools.find_packages(), license="MIT", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python", "Topic :: Software Development", ], test_suite="MockMockMock.tests.AllTests", use_2to3=True, command_options={ "build_sphinx": { "version": ("setup.py", version), "release": ("setup.py", version), "source_dir": ("setup.py", "doc"), }, }, )
Add taxPercentage() for Laravel Cashier 6.0 In Laravel Cashier 6.0, the function to get tax rate is now ``taxPercentage()`` instead of ``getTaxPercent()``
<?php namespace Mpociot\VatCalculator\Traits; use Mpociot\VatCalculator\Facades\VatCalculator; trait BillableWithinTheEU { /** * @var int */ protected $stripeTaxPercent = 0; /** * @var */ protected $userCountryCode; /** * @var bool */ protected $userIsCompany = false; /** * @param string $countryCode * @param bool|false $company * * @return $this */ public function setTaxForCountry($countryCode, $company = false) { $this->userCountryCode = $countryCode; $this->userIsCompany = $company; return $this; } /** * @param $countryCode * * @return $this */ public function useTaxFrom($countryCode) { $this->userCountryCode = $countryCode; return $this; } /** * @return $this */ public function asBusiness() { $this->userIsCompany = true; return $this; } /** * @return $this */ public function asIndividual() { $this->userIsCompany = false; return $this; } /** * Get the tax percentage to apply to the subscription. * * @return int */ public function getTaxPercent() { return VatCalculator::getTaxRateForCountry($this->userCountryCode, $this->userIsCompany) * 100; } /** * Get the tax percentage to apply to the subscription for Cashier > 6.0 * * @return int */ public function taxPercentage() { return $this->getTaxPercent(); } }
<?php namespace Mpociot\VatCalculator\Traits; use Mpociot\VatCalculator\Facades\VatCalculator; trait BillableWithinTheEU { /** * @var int */ protected $stripeTaxPercent = 0; /** * @var */ protected $userCountryCode; /** * @var bool */ protected $userIsCompany = false; /** * @param string $countryCode * @param bool|false $company * * @return $this */ public function setTaxForCountry($countryCode, $company = false) { $this->userCountryCode = $countryCode; $this->userIsCompany = $company; return $this; } /** * @param $countryCode * * @return $this */ public function useTaxFrom($countryCode) { $this->userCountryCode = $countryCode; return $this; } /** * @return $this */ public function asBusiness() { $this->userIsCompany = true; return $this; } /** * @return $this */ public function asIndividual() { $this->userIsCompany = false; return $this; } /** * Get the tax percentage to apply to the subscription. * * @return int */ public function getTaxPercent() { return VatCalculator::getTaxRateForCountry($this->userCountryCode, $this->userIsCompany) * 100; } }
Bug: Edit ticket attachment and show changes before update
@section('content') <div class="modal fade" id="modal-attachment-edit" tabindex="-1" role="dialog" aria-labelledby="modal-attachment-edit-Label"> <div class="modal-dialog model-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{ trans('panichd::lang.attachment-edit') }}</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">{{ trans('panichd::lang.flash-x') }}</span></button> </div> <div class="modal-body"> <!-- Div edit attachment --> <fieldset id="edit_ticket_attachment"> @include('panichd::tickets.partials.attachment_form_fields') {!! CollectiveForm::hidden(null, 'modal-attachment-edit', ['id'=>'hide_modal_id']) !!} <div class="text-right col-md-12"> {!! CollectiveForm::button( trans('panichd::lang.update'), [ 'type' => 'button', 'class' => 'btn btn-primary attachment_form_submit', 'data-back-div' => 'ticket_attached' ]) !!} </div> </fieldset> </div> </div> </div> </div> @append
@section('content') <div class="modal fade" id="modal-attachment-edit" tabindex="-1" role="dialog" aria-labelledby="modal-attachment-edit-Label"> <div class="modal-dialog model-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{ trans('panichd::lang.attachment-edit') }}</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">{{ trans('panichd::lang.flash-x') }}</span></button> </div> <div class="modal-body"> @include('panichd::tickets.partials.attachment_form_fields') {!! CollectiveForm::hidden(null, 'modal-attachment-edit', ['id'=>'hide_modal_id']) !!} <div class="text-right col-md-12"> {!! CollectiveForm::button( trans('panichd::lang.update'), [ 'type' => 'button', 'class' => 'btn btn-primary attachment_form_submit' ]) !!} </div> </div> </div> </div> </div> @append
Update regexp to detect magic comment
# -*- coding: utf-8 -*- import re __version__ = '0.1.0' class CodingChecker(object): name = 'flake8_coding' version = __version__ def __init__(self, tree, filename): self.filename = filename @classmethod def add_options(cls, parser): parser.add_option( '--accept-encodings', default='latin-1, utf-8', action='store', help="Acceptable source code encodings for `coding:` magic comment" ) parser.config_options.append('accpet-encodings') @classmethod def parse_options(cls, options): cls.encodings = [e.strip().lower() for e in options.accept_encodings.split(',')] def run(self): with open(self.filename) as f: # PEP-263 says: a magic comment must be placed into the source # files either as first or second line in the file for lineno in range(1, 3): matched = re.search('coding[:=]\s*([-\w.]+)', f.readline(), re.IGNORECASE) if matched: if matched.group(1).lower() not in self.encodings: yield lineno, 0, "C102 Unknown encoding found in coding magic comment", type(self) break else: yield 0, 0, "C101 Coding magic comment not found", type(self)
# -*- coding: utf-8 -*- import re __version__ = '0.1.0' class CodingChecker(object): name = 'flake8_coding' version = __version__ def __init__(self, tree, filename): self.filename = filename @classmethod def add_options(cls, parser): parser.add_option( '--accept-encodings', default='latin-1, utf-8', action='store', help="Acceptable source code encodings for `coding:` magic comment" ) parser.config_options.append('accpet-encodings') @classmethod def parse_options(cls, options): cls.encodings = [e.strip().lower() for e in options.accept_encodings.split(',')] def run(self): with open(self.filename) as f: # PEP-263 says: a magic comment must be placed into the source # files either as first or second line in the file for lineno in range(1, 3): matched = re.search('coding: (\S+)', f.readline(), re.IGNORECASE) if matched: if matched.group(1).lower() not in self.encodings: yield lineno, 0, "C102 Unknown encoding found in coding magic comment", type(self) break else: yield 0, 0, "C101 Coding magic comment not found", type(self)
Update authentication file for neverbounce authentiction
(function () { "use strict"; const Promise = require('bluebird'); const request = Promise.promisify(require('request')); const neverBounceApiKeys = require('./apiKeys.js').neverbounce; const apiUsername = neverBounceApiKeys.username; const apiSecretKey = neverBounceApiKeys.key; const authenticateNeverBounce = function () { return request({ method: 'POST', url: `https://api.neverbounce.com/v3/access_token`, auth: { username: apiUsername, password: apiSecretKey }, form: { grant_type: "client_credentials", scope: 'basic' // scope: 'user' } }) .then(function (response) { if (response.statusCode !== 200) { console.error(`Received a ${response.statusCode} error. \n ${response.body}`); } else { console.log("You're all set! Time to start validating emails"); console.log("Type in: \n node check.js FILENAME"); } }) .catch(console.error); }; authenticateNeverBounce(); }());
(function () { "use strict"; const Promise = require('bluebird'); const request = Promise.promisify(require('request')); const apiUsername = require('./apiKeys.js').username; const apiSecretKey = require('./apiKeys.js').key; const authenticateNeverBounce = function () { request({ method: 'POST', url: `https://api.neverbounce.com/v3/access_token`, auth: { username: apiUsername, password: apiSecretKey }, form: { grant_type: "client_credentials", scope: 'basic' // scope: 'user' } }).then(function (response) { if (response.statusCode !== 200) { console.error(`Received a ${response.statusCode} error. \n ${response.body}`); } else { console.log("You're all set! Time to start validating emails"); console.log("Type in: \n node check.js FILENAME"); } }); }; authenticateNeverBounce(); }());
Use itemID as react list key.
import React from "react"; import moment from 'moment'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import NewsItem from "./NewsItem"; import NewsCow from "./NewsCow"; // const NewsItem = ({info}) => ( // <div className="newsItem"> // {info.title} <span className="subItem">{info.sitelink}</span> // <div style={{position: 'absolute', bottom: 0, right: 0}}> // <img src={`/dist/icons/${info.sitehost}.jpg`} /> // </div> // </div> // ) export default class NewsList extends React.Component { render () { if (this.props.loading) { return <div>Loading</div> } if (this.props.newsItems.length === 0) { return ( <div id="emptyList"> </div> ); } else { var makeList = x => <li key={x.itemID} className="newsItemWrapper"><NewsItem info={x}/></li>; return ( <ReactCSSTransitionGroup component="ul" className="newsWrapper" transitionName="example" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={300}> { this.props.newsItems.map(makeList) } </ReactCSSTransitionGroup> ); } } };
import React from "react"; import moment from 'moment'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group' import NewsItem from "./NewsItem"; import NewsCow from "./NewsCow"; // const NewsItem = ({info}) => ( // <div className="newsItem"> // {info.title} <span className="subItem">{info.sitelink}</span> // <div style={{position: 'absolute', bottom: 0, right: 0}}> // <img src={`/dist/icons/${info.sitehost}.jpg`} /> // </div> // </div> // ) export default class NewsList extends React.Component { render () { if (this.props.loading) { return <div>Loading</div> } if (this.props.newsItems.length === 0) { return ( <div id="emptyList"> </div> ); } else { var makeList = x => <li key={x.guid} className="newsItemWrapper"><NewsItem info={x}/></li>; return ( <ReactCSSTransitionGroup component="ul" className="newsWrapper" transitionName="example" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={300}> { this.props.newsItems.map(makeList) } </ReactCSSTransitionGroup> ); } } };
Add dataSourceConfig to link passed datasource keys
/** * Created by XaviTorello on 30/05/18 */ import React from 'react'; import ComposedComponent from './ComposedComponent'; import AutoComplete from 'material-ui/AutoComplete'; const dataSourceConfig = { text: 'name', value: 'value', }; class TextSuggest extends React.Component { render() { // console.log('TextSuggest', this.props.form); // assign the source list to autocomplete const datasource = this.props.form.schema.enumNames || this.props.form.schema.enum || ['Loading...']; // assign the filter, by default case insensitive const filter = ((filter) => { switch (filter) { case 'fuzzy': return AutoComplete.fuzzyFilter; break; default: return AutoComplete.caseInsensitiveFilter; break; } })(this.props.form.filter) return ( <div className={this.props.form.htmlClass}> <AutoComplete type={this.props.form.type} floatingLabelText={this.props.form.title} hintText={this.props.form.placeholder} errorText={this.props.error} onChange={this.props.onChangeValidate} defaultValue={this.props.value} disabled={this.props.form.readonly} style={this.props.form.style || {width: '100%'}} dataSource={datasource} filter={filter} maxSearchResults={this.props.form.maxSearchResults || 5} /> </div> ); } } export default ComposedComponent(TextSuggest);
/** * Created by XaviTorello on 30/05/18 */ import React from 'react'; import ComposedComponent from './ComposedComponent'; import AutoComplete from 'material-ui/AutoComplete'; class TextSuggest extends React.Component { render() { // console.log('TextSuggest', this.props.form); // assign the source list to autocomplete const datasource = this.props.form.schema.enumNames || this.props.form.schema.enum || ['Loading...']; // assign the filter, by default case insensitive const filter = ((filter) => { switch (filter) { case 'fuzzy': return AutoComplete.fuzzyFilter; break; default: return AutoComplete.caseInsensitiveFilter; break; } })(this.props.form.filter) return ( <div className={this.props.form.htmlClass}> <AutoComplete type={this.props.form.type} floatingLabelText={this.props.form.title} hintText={this.props.form.placeholder} errorText={this.props.error} onChange={this.props.onChangeValidate} defaultValue={this.props.value} disabled={this.props.form.readonly} style={this.props.form.style || {width: '100%'}} dataSource={datasource} filter={filter} maxSearchResults={this.props.form.maxSearchResults || 5} /> </div> ); } } export default ComposedComponent(TextSuggest);
Remove an invalid trove classifier. * setup.py(setuptools.setup): Remove "Intended Audience :: BigDate" since it's not in pypi's list of valid trove classifiers and prevents successful upload of the package when present. Change-Id: Iee487d1737a12158bb181d21ae841d07e0820e10
import setuptools from savanna.openstack.common import setup as common_setup requires = common_setup.parse_requirements() depend_links = common_setup.parse_dependency_links() project = 'savanna' setuptools.setup( name=project, version=common_setup.get_version(project, '0.1'), description='Savanna project', author='Mirantis Inc.', author_email='[email protected]', url='http://savanna.mirantis.com', classifiers=[ 'Environment :: OpenStack', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], license='Apache Software License', cmdclass=common_setup.get_cmdclass(), packages=setuptools.find_packages(exclude=['bin']), package_data={'savanna': ['resources/*.template']}, install_requires=requires, dependency_links=depend_links, include_package_data=True, test_suite='nose.collector', scripts=[ 'bin/savanna-api', 'bin/savanna-manage', ], py_modules=[], data_files=[ ('share/savanna', [ 'etc/savanna/savanna.conf.sample', 'etc/savanna/savanna.conf.sample-full', ]), ], )
import setuptools from savanna.openstack.common import setup as common_setup requires = common_setup.parse_requirements() depend_links = common_setup.parse_dependency_links() project = 'savanna' setuptools.setup( name=project, version=common_setup.get_version(project, '0.1'), description='Savanna project', author='Mirantis Inc.', author_email='[email protected]', url='http://savanna.mirantis.com', classifiers=[ 'Environment :: OpenStack', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'Intended Audience :: BigDate', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], license='Apache Software License', cmdclass=common_setup.get_cmdclass(), packages=setuptools.find_packages(exclude=['bin']), package_data={'savanna': ['resources/*.template']}, install_requires=requires, dependency_links=depend_links, include_package_data=True, test_suite='nose.collector', scripts=[ 'bin/savanna-api', 'bin/savanna-manage', ], py_modules=[], data_files=[ ('share/savanna', [ 'etc/savanna/savanna.conf.sample', 'etc/savanna/savanna.conf.sample-full', ]), ], )
Use oslo_config new type PortOpt for port options The oslo_config library provides new type PortOpt to validate the range of port now. Change-Id: Ifbfee642309fec668e363555c2abd103c1f8c4af ref: https://github.com/openstack/oslo.config/blob/2.6.0/oslo_config/cfg.py#L1114 Depends-On: Ida294b05a85f5bef587b761fcd03c28c7a3474d8
# 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_config import cfg from neutron.i18n import _ df_opts = [ cfg.StrOpt('remote_db_ip', default='127.0.0.1', help=_('The remote db server ip address')), cfg.PortOpt('remote_db_port', default=4001, help=_('The remote db server port')), cfg.StrOpt('nb_db_class', default='dragonflow.db.drivers.etcd_db_driver.EtcdDbDriver', help=_('The driver class for the NB DB driver')), cfg.StrOpt('local_ip', default='127.0.0.1', help=_('Local host IP')), cfg.StrOpt('tunnel_type', default='geneve', help=_('The encapsulation type for the tunnel')), cfg.StrOpt('apps_list', default='l2_app.L2App,l3_app.L3App', help=_('List of openflow applications classes to load')), ]
# 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_config import cfg from neutron.i18n import _ df_opts = [ cfg.StrOpt('remote_db_ip', default='127.0.0.1', help=_('The remote db server ip address')), cfg.IntOpt('remote_db_port', default=4001, help=_('The remote db server port')), cfg.StrOpt('nb_db_class', default='dragonflow.db.drivers.etcd_db_driver.EtcdDbDriver', help=_('The driver class for the NB DB driver')), cfg.StrOpt('local_ip', default='127.0.0.1', help=_('Local host IP')), cfg.StrOpt('tunnel_type', default='geneve', help=_('The encapsulation type for the tunnel')), cfg.StrOpt('apps_list', default='l2_app.L2App,l3_app.L3App', help=_('List of openflow applications classes to load')), ]
Allow passing extra kwargs into register decorator In order to support extra key-word arguments in add_url_rule method, e.g. subdomain.
from flask import Blueprint from functools import wraps from flask_mongorest.methods import Create, Update, BulkUpdate, Fetch, List, Delete class MongoRest(object): def __init__(self, app, **kwargs): self.app = app self.url_prefix = kwargs.pop('url_prefix', '') app.register_blueprint(Blueprint(self.url_prefix, __name__, template_folder='templates')) def register(self, **kwargs): def decorator(klass): document_name = klass.resource.document.__name__.lower() name = kwargs.pop('name', document_name) url = kwargs.pop('url', '/%s/' % document_name) if self.url_prefix: url = '%s%s' % (self.url_prefix, url) pk_type = kwargs.pop('pk_type', 'string') view_func = klass.as_view(name) if List in klass.methods: self.app.add_url_rule(url, defaults={'pk': None}, view_func=view_func, methods=[List.method], **kwargs) if Create in klass.methods or BulkUpdate in klass.methods: self.app.add_url_rule(url, view_func=view_func, methods=[x.method for x in klass.methods if x in (Create, BulkUpdate)], **kwargs) self.app.add_url_rule('%s<%s:%s>/' % (url, pk_type, 'pk'), view_func=view_func, methods=[x.method for x in klass.methods], **kwargs) return klass return decorator
from flask import Blueprint from functools import wraps from flask_mongorest.methods import Create, Update, BulkUpdate, Fetch, List, Delete class MongoRest(object): def __init__(self, app, **kwargs): self.app = app self.url_prefix = kwargs.pop('url_prefix', '') app.register_blueprint(Blueprint(self.url_prefix, __name__, template_folder='templates')) def register(self, **kwargs): def decorator(klass): document_name = klass.resource.document.__name__.lower() name = kwargs.pop('name', document_name) url = kwargs.pop('url', '/%s/' % document_name) if self.url_prefix: url = '%s%s' % (self.url_prefix, url) pk_type = kwargs.pop('pk_type', 'string') view_func = klass.as_view(name) if List in klass.methods: self.app.add_url_rule(url, defaults={'pk': None}, view_func=view_func, methods=[List.method]) if Create in klass.methods or BulkUpdate in klass.methods: self.app.add_url_rule(url, view_func=view_func, methods=[x.method for x in klass.methods if x in (Create, BulkUpdate)]) self.app.add_url_rule('%s<%s:%s>/' % (url, pk_type, 'pk'), view_func=view_func, methods=[x.method for x in klass.methods]) return klass return decorator
Fix bad console output formatting
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return s
import time import sys from utils import format_duration if sys.platform == "win32": default_timer = time.clock else: default_timer = time.time class Benchmark(): def __init__(self, func, name="", repeat=5): self.func = func self.repeat = repeat self.name = name self.verbose = False def run(self, conn): self.results = [] for x in range(self.repeat): start = default_timer() self.func() end = default_timer() elapsed = end - start self.results.append(elapsed) conn.rollback() return min(self.results) def __str__(self): s = format_duration(min(self.results)) if self.verbose: s_min = format_duration(min(self.results)) s_avg = format_duration(sum(self.results) / len(self.results)) s_max = format_duration(max(self.results)) s_all = [format_duration(t) for t in self.results] s += "(min={} avg={} max={} all={})".format(s_min, s_avg, s_max, s_all) return " ".join(s)
Exclude tests package from distribution
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing except ImportError: pass setup( name='Willow', version='0.4a0', description='A Python image library that sits on top of Pillow, Wand and OpenCV', author='Karl Hobley', author_email='[email protected]', url='', packages=find_packages(exclude=['tests']), include_package_data=True, license='BSD', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[], zip_safe=False, )
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing except ImportError: pass setup( name='Willow', version='0.4a0', description='A Python image library that sits on top of Pillow, Wand and OpenCV', author='Karl Hobley', author_email='[email protected]', url='', packages=find_packages(), include_package_data=True, license='BSD', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[], zip_safe=False, )
Add express to externals list in demand-express
const {join, resolve} = require('path'); const {CheckerPlugin} = require('awesome-typescript-loader'); const loaders = require('./webpack/loaders'); module.exports = { target: 'node', entry: { server: ['./server/index.ts'], }, output: { filename: 'index.js', path: resolve(join(__dirname, 'dist-server')), libraryTarget: 'commonjs2', }, devtool: 'source-map', resolve: { extensions: ['.ts', '.js', '.json'], }, module: { rules: [ loaders.tsjit, loaders.html, loaders.css ] }, plugins: [ new CheckerPlugin(), ], externals: [ '@angular/cli', '@angular/common', '@angular/compiler', '@angular/compiler-cli', '@angular/core', '@angular/forms', '@angular/http', '@angular/platform-browser', '@angular/router', '@angular/tsc-wrapped', '@angular/service-worker', 'angular-ssr', 'express', function(context, request, callback) { const exclusions = [/\@ngrx/, /rxjs/, /zone\.js/, /reflect-metadata/]; if (exclusions.some(expr => expr.test(request))) { callback(null, `commonjs ${request.replace(/^.*?(\\|\/)node_modules(\\|\/)/, String())}`); } else { callback(); } }, ], node: { __dirname: true, __filename: true } };
const {join, resolve} = require('path'); const {CheckerPlugin} = require('awesome-typescript-loader'); const loaders = require('./webpack/loaders'); module.exports = { target: 'node', entry: { server: ['./server/index.ts'], }, output: { filename: 'index.js', path: resolve(join(__dirname, 'dist-server')), libraryTarget: 'commonjs2', }, devtool: 'source-map', resolve: { extensions: ['.ts', '.js', '.json'], }, module: { rules: [ loaders.tsjit, loaders.html, loaders.css ] }, plugins: [ new CheckerPlugin(), ], externals: [ '@angular/cli', '@angular/common', '@angular/compiler', '@angular/compiler-cli', '@angular/core', '@angular/forms', '@angular/http', '@angular/platform-browser', '@angular/router', '@angular/tsc-wrapped', '@angular/service-worker', 'angular-ssr', function(context, request, callback) { const exclusions = [/\@ngrx/, /rxjs/, /zone\.js/, /reflect-metadata/]; if (exclusions.some(expr => expr.test(request))) { callback(null, `commonjs ${request.replace(/^.*?(\\|\/)node_modules(\\|\/)/, String())}`); } else { callback(); } }, ], node: { __dirname: true, __filename: true } };
Allow files to be exlcuded
/*jslint node:true */ var RequireAll = (function () { 'use strict'; var fs = require('fs'), exclude = function (excludeRegexp, name) { return excludeRegexp && name.match(excludeRegexp); }, loadAllModules = function (options) { var files = fs.readdirSync(options.dirname), modules = {}; files.forEach(function (file) { if (exclude(options.excludeRegexp, file)) { return; } var filepath = options.dirname + '/' + file; if (fs.statSync(filepath).isDirectory()) { modules[file] = loadAllModules({ dirname : filepath, filter : options.filter, excludeRegexp : options.excludeRegexp, dependencies : options.dependencies }); } else { if (file.match(options.filter)) { modules[file.split('.')[0]] = require(filepath).apply(this, options.dependencies); } } }); }; return { loadAllModules : loadAllModules }; }()); module.exports = RequireAll;
/*jslint node:true */ var RequireAll = (function () { 'use strict'; var fs = require('fs'), exclude = function (excludeRegexp, name) { return excludeRegexp && name.match(excludeRegexp); }, loadAllModules = function (options) { var files = fs.readdirSync(options.dirname), modules = {}; files.forEach(function (file) { if (exclude(options.exclude, file)) { return; } var filepath = options.dirname + '/' + file; if (fs.statSync(filepath).isDirectory()) { modules[file] = loadAllModules({ dirname : filepath, filter : options.filter, exclude : options.exclude, dependencies : options.dependencies }); } else { if (file.match(options.filter)) { modules[file.split('.')[0]] = require(filepath).apply(this, options.dependencies); } } }); }; return { loadAllModules : loadAllModules }; }()); module.exports = RequireAll;
Change authentication header of restapi service to prevent login popups
package ubic.gemma.web.services.rest.util; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response; import java.io.IOException; public class RestAuthEntryPoint extends BasicAuthenticationEntryPoint { private static final String MESSAGE_401 = "Provided authentication credentials are invalid."; @Override public void afterPropertiesSet() { setRealmName( "Gemma rest api" ); } @Override public void commence( final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException ) { response.setStatus( HttpServletResponse.SC_UNAUTHORIZED ); // using 'xBasic' instead of 'basic' to prevent default browser login popup response.addHeader( "WWW-Authenticate", "xBasic realm=" + getRealmName() + "" ); response.setContentType( "application/json" ); WellComposedErrorBody errorBody = new WellComposedErrorBody( Response.Status.UNAUTHORIZED, MESSAGE_401 ); ResponseErrorObject errorObject = new ResponseErrorObject( errorBody ); ObjectMapper mapperObj = new ObjectMapper(); try { String jsonStr = mapperObj.writeValueAsString( errorObject ); response.getWriter().println( jsonStr ); } catch ( IOException e ) { e.printStackTrace(); } } }
package ubic.gemma.web.services.rest.util; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Response; import java.io.IOException; public class RestAuthEntryPoint extends BasicAuthenticationEntryPoint { private static final String MESSAGE_401 = "Provided authentication credentials are invalid."; @Override public void commence( final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException ) { response.setStatus( HttpServletResponse.SC_UNAUTHORIZED ); response.addHeader( "WWW-Authenticate", "Basic realm=" + getRealmName() + "" ); response.setContentType( "application/json" ); WellComposedErrorBody errorBody = new WellComposedErrorBody( Response.Status.UNAUTHORIZED, MESSAGE_401 ); ResponseErrorObject errorObject = new ResponseErrorObject(errorBody); ObjectMapper mapperObj = new ObjectMapper(); try { String jsonStr = mapperObj.writeValueAsString( errorObject ); response.getWriter().println( jsonStr ); } catch ( IOException e ) { e.printStackTrace(); } } @Override public void afterPropertiesSet() { setRealmName("Gemma rest api"); } }
Use bigger AC icon for mobile support
<?php function slack_get_user_by_email($email) { static $users; if (defined('SLACK_API_TOKEN')) { if (!$users) { // @todo cache users.list $slack = new Slack(SLACK_API_TOKEN); $response = $slack->call('users.list'); if ($response['ok']) { $users = $response['members']; } } foreach ($users as $user) { if ($user['profile']['email'] == $email) { return $user; } } } } function slack_post_message($channel, $message) { $slack = new Slack(SLACK_API_TOKEN); $slack->call('chat.postMessage', array( 'channel' => $channel, 'text' => $message, 'username' => 'ActiveCollab', 'as_user' => FALSE, 'icon_url' => defined('ASSETS_URL') ? ASSETS_URL . '/images/system/default/application-branding/logo.80x80.png' : '', 'link_names' => 1 )); }
<?php function slack_get_user_by_email($email) { static $users; if (defined('SLACK_API_TOKEN')) { if (!$users) { // @todo cache users.list $slack = new Slack(SLACK_API_TOKEN); $response = $slack->call('users.list'); if ($response['ok']) { $users = $response['members']; } } foreach ($users as $user) { if ($user['profile']['email'] == $email) { return $user; } } } } function slack_post_message($channel, $message) { $slack = new Slack(SLACK_API_TOKEN); $slack->call('chat.postMessage', array( 'channel' => $channel, 'text' => $message, 'username' => 'ActiveCollab', 'as_user' => FALSE, 'icon_url' => defined('ASSETS_URL') ? ASSETS_URL . '/images/system/default/application-branding/logo.40x40.png' : '', 'link_names' => 1 )); }
Fix modal when there's no options available
<?php if (isset($meta) && is_object($meta)) { $_title = $meta->label; $_key = $meta->key; $tipo = $meta->type; $options = []; if (array_key_exists('options',$meta->config)) { $options = $meta->config['options']; } ?> <div class="<?php echo $class; ?>"> <?php $this->part("modal/title", ['title' => $_title]); if ($tipo === "select" && is_array($meta->config)) { $this->part("modal/entity-dropdown", ['attr' => $_key, 'options' => $options]); } else if ($tipo === "string" || $tipo === "int") { ?> <input type='text' name='<?php echo $_key; ?>' placeholder='<?php \MapasCulturais\i::esc_attr_e('Campo obrigatório')?>' required /> <?php } else if ($tipo === "text") { ?> <textarea name='<?php echo $_key; ?>' maxlength='400'></textarea> <br> <?php } else if ($tipo === "multiselect" && is_array($meta->config)) { foreach ($options as $option) { ?> <label for='<?php echo $_key; ?>'> <?php echo $option; ?> </label> <input type='checkbox' name='<?php echo $_key; ?>' value='<?php echo $option; ?>'> <br> <?php } } ?> </div> <?php }
<?php if (isset($meta) && is_object($meta)) { $_title = $meta->label; $_key = $meta->key; $tipo = $meta->type; $options = $meta->config['options']; ?> <div class="<?php echo $class; ?>"> <?php $this->part("modal/title", ['title' => $_title]); if ($tipo === "select" && is_array($meta->config)) { $this->part("modal/entity-dropdown", ['attr' => $_key, 'options' => $options]); } else if ($tipo === "string" || $tipo === "int") { ?> <input type='text' name='<?php echo $_key; ?>' placeholder='<?php \MapasCulturais\i::esc_attr_e('Campo obrigatório')?>' required /> <?php } else if ($tipo === "text") { ?> <textarea name='<?php echo $_key; ?>' maxlength='400'></textarea> <br> <?php } else if ($tipo === "multiselect" && is_array($meta->config)) { foreach ($options as $option) { ?> <label for='<?php echo $_key; ?>'> <?php echo $option; ?> </label> <input type='checkbox' name='<?php echo $_key; ?>' value='<?php echo $option; ?>'> <br> <?php } } ?> </div> <?php }
Add missing id in initial state
import { SEEK, SET_DURATION, SET_CURRENT_SONG, CHANGE_VOLUME, CHANGE_CURRENT_SECONDS, PLAY, PAUSE } from './../actions/actionTypes' const initialState = { isPlaying: false, playFromSeconds: 0, totalSeconds: 0, currentSeconds: 0, currentSong: { id: '', title: '', artist: '', album: '', albumArt: '', src: '' }, volume: 1 } const player = (state = initialState, action) => { switch (action.type) { case PLAY: return { ...state, isPlaying: true } case PAUSE: return { ...state, isPlaying: false } case SEEK: return { ...state, playFromSeconds: action.playFromSeconds } case SET_CURRENT_SONG: return { ...state, currentSong: { id: action.id, title: action.title, artist: action.artist, album: action.album, albumArt: action.albumArt, src: action.src } } case SET_DURATION: return { ...state, totalSeconds: action.totalSeconds } case CHANGE_VOLUME: return { ...state, volume: action.volume } case CHANGE_CURRENT_SECONDS: return { ...state, currentSeconds: action.currentSeconds } default: return state } } export default player
import { SEEK, SET_DURATION, SET_CURRENT_SONG, CHANGE_VOLUME, CHANGE_CURRENT_SECONDS, PLAY, PAUSE } from './../actions/actionTypes' const initialState = { isPlaying: false, playFromSeconds: 0, totalSeconds: 0, currentSeconds: 0, currentSong: { title: '', artist: '', album: '', albumArt: '', src: '' }, volume: 1 } const player = (state = initialState, action) => { switch (action.type) { case PLAY: return { ...state, isPlaying: true } case PAUSE: return { ...state, isPlaying: false } case SEEK: return { ...state, playFromSeconds: action.playFromSeconds } case SET_CURRENT_SONG: return { ...state, currentSong: { id: action.id, title: action.title, artist: action.artist, album: action.album, albumArt: action.albumArt, src: action.src } } case SET_DURATION: return { ...state, totalSeconds: action.totalSeconds } case CHANGE_VOLUME: return { ...state, volume: action.volume } case CHANGE_CURRENT_SECONDS: return { ...state, currentSeconds: action.currentSeconds } default: return state } } export default player
Add easing function to auto-scroll
'use strict'; angular.module('arethusaTranslateGuiApp').directive('containers', [ '$timeout', function($timeout) { return { restrict: 'A', scope: true, link: function(scope, element) { scope.$on('dataLoaded', function() { // When new data is loaded the DOM will take a while to update // itself. Let's hide this fact by pushing the content out of the // viewport and show a loading message instead. // Once we are done, we move the DOM elements into the users sight. scope.rendering = true; $timeout(function() { scope.rendering = false; }, 2000); }); scope.$watch('showIndex', function(newVal) { if (newVal) { scope.itemClass = 'small-12'; scope.containerClass = 'small-9 large-10'; } else { scope.containerClass = 'small-12'; scope.itemClass = 'small-6'; } scope.cloak = true; $timeout(function() { scope.cloak = false; }, 600); }); function easeInOutCubic(t) { return t<0.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1; } function autoScroll(ev, item) { element.find('#scroller').scrollTo(item, 0, 1200, easeInOutCubic); } scope.$on('scrollToItem', autoScroll); }, templateUrl: 'app/i18n/containers.directive.html' }; } ]);
'use strict'; angular.module('arethusaTranslateGuiApp').directive('containers', [ '$timeout', function($timeout) { return { restrict: 'A', scope: true, link: function(scope, element) { scope.$on('dataLoaded', function() { // When new data is loaded the DOM will take a while to update // itself. Let's hide this fact by pushing the content out of the // viewport and show a loading message instead. // Once we are done, we move the DOM elements into the users sight. scope.rendering = true; $timeout(function() { scope.rendering = false; }, 2000); }); scope.$watch('showIndex', function(newVal) { if (newVal) { scope.itemClass = 'small-12'; scope.containerClass = 'small-9 large-10'; } else { scope.containerClass = 'small-12'; scope.itemClass = 'small-6'; } scope.cloak = true; $timeout(function() { scope.cloak = false; }, 600); }); function autoScroll(ev, item) { element.find('#scroller').scrollTo(item, 0, 500); } scope.$on('scrollToItem', autoScroll); }, templateUrl: 'app/i18n/containers.directive.html' }; } ]);
Fix tests when username has a ' character in it Laravel HTML entity encodes the username, so we need to do the same thing in the test so the HTML output will match.
<?php namespace Tests\Functional; use App\Models\User; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class NavigationTest extends \Tests\TestCase { use DatabaseMigrations; public function testGuestNavigation() { $this->get('/') ->assertSee('Log In') ->assertSee('href="/login"') ->assertDontSee('My List') ->assertDontSee('/list'); } public function testUserListNavigation() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('My List') ->assertSee('/list') ->assertDontSee('Login') ->assertDontSee('href="/login"'); } public function testUserAccountNavigation() { $user = factory(User::class)->create(); $encodedUsername = htmlentities( $user->username, ENT_COMPAT | ENT_HTML401 | ENT_QUOTES ); $this->actingAs($user) ->get('/') ->assertSee($encodedUsername) ->assertSee('href="/account"'); } public function testUserAccountLogOut() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('Log Out') ->assertSee('href="/logout"'); } }
<?php namespace Tests\Functional; use App\Models\User; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class NavigationTest extends \Tests\TestCase { use DatabaseMigrations; public function testGuestNavigation() { $this->get('/') ->assertSee('Log In') ->assertSee('href="/login"') ->assertDontSee('My List') ->assertDontSee('/list'); } public function testUserListNavigation() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('My List') ->assertSee('/list') ->assertDontSee('Login') ->assertDontSee('href="/login"'); } public function testUserAccountNavigation() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee($user->username) ->assertSee('href="/account"'); } public function testUserAccountLogOut() { $user = factory(User::class)->create(); $this->actingAs($user) ->get('/') ->assertSee('Log Out') ->assertSee('href="/logout"'); } }
Add rc as prerelease name
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bump: { options: { files: ['package.json'], updateConfigs: ['pkg'], commit: true, commitMessage: 'Release v%VERSION%', createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', prereleaseName: 'rc', push: true, pushTo: 'origin', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' } }, cucumberjs: { options: { format: 'html', output: 'reports/my_report.html', theme: 'bootstrap' }, features: ['features/**/*.feature'] }, jshint: { options: { esversion: 6, reporter: require('jshint-stylish') }, build: ['*.js', 'features/**/*.js', 'public/**/*.js', '!public/lib/**/*.js', '!public/reports/**/*.js'] }, karma: { unit: { configFile: 'karma.conf.js' } } }); // ALIAS TASKS grunt.registerTask('test', ['jshint', 'karma', 'cucumberjs']); // LOAD GRUNT PACKAGES grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-cucumberjs'); grunt.loadNpmTasks('grunt-karma'); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bump: { options: { files: ['package.json'], updateConfigs: ['pkg'], commit: true, commitMessage: 'Release v%VERSION%', createTag: true, tagName: 'v%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'origin', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' } }, cucumberjs: { options: { format: 'html', output: 'reports/my_report.html', theme: 'bootstrap' }, features: ['features/**/*.feature'] }, jshint: { options: { esversion: 6, reporter: require('jshint-stylish') }, build: ['*.js', 'features/**/*.js', 'public/**/*.js', '!public/lib/**/*.js', '!public/reports/**/*.js'] }, karma: { unit: { configFile: 'karma.conf.js' } } }); // ALIAS TASKS grunt.registerTask('test', ['jshint', 'karma', 'cucumberjs']); // LOAD GRUNT PACKAGES grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-cucumberjs'); grunt.loadNpmTasks('grunt-karma'); };
Check that the priority order is respected if QT_API or USE_QT_API are not specified.
import os from qtpy import QtCore, QtGui, QtWidgets, QtWebEngineWidgets def assert_pyside(): import PySide assert QtCore.QEvent is PySide.QtCore.QEvent assert QtGui.QPainter is PySide.QtGui.QPainter assert QtWidgets.QWidget is PySide.QtGui.QWidget assert QtWebEngineWidgets.QWebEnginePage is PySide.QtWebKit.QWebPage def assert_pyqt4(): import PyQt4 assert QtCore.QEvent is PyQt4.QtCore.QEvent assert QtGui.QPainter is PyQt4.QtGui.QPainter assert QtWidgets.QWidget is PyQt4.QtGui.QWidget assert QtWebEngineWidgets.QWebEnginePage is PyQt4.QtWebKit.QWebPage def assert_pyqt5(): import PyQt5 assert QtCore.QEvent is PyQt5.QtCore.QEvent assert QtGui.QPainter is PyQt5.QtGui.QPainter assert QtWidgets.QWidget is PyQt5.QtWidgets.QWidget assert QtWebEngineWidgets.QWebEnginePage is PyQt5.QtWebEngineWidgets.QWebEnginePage def test_qt_api(): """ If QT_API is specified, we check that the correct Qt wrapper was used """ QT_API = os.environ.get('QT_API', None) if QT_API == 'pyside': assert_pyside() elif QT_API in ('pyqt', 'pyqt4'): assert_pyqt4() elif QT_API == 'pyqt5': assert_pyqt5() else: # We should then be loading, in order of decreasing preference, PyQt5, # PyQt4, and PySide. try: import PyQt5 except ImportError: try: import PyQt4 except ImportError: import PySide assert_pyside() else: assert_pyqt4() else: assert_pyqt5()
import os def test_qt_api(): """ If QT_API is specified, we check that the correct Qt wrapper was used """ from qtpy import QtCore, QtGui, QtWidgets, QtWebEngineWidgets QT_API = os.environ.get('QT_API', None) if QT_API == 'pyside': import PySide assert QtCore.QEvent is PySide.QtCore.QEvent assert QtGui.QPainter is PySide.QtGui.QPainter assert QtWidgets.QWidget is PySide.QtGui.QWidget assert QtWebEngineWidgets.QWebEnginePage is PySide.QtWebKit.QWebPage elif QT_API in ('pyqt', 'pyqt4'): import PyQt4 assert QtCore.QEvent is PyQt4.QtCore.QEvent assert QtGui.QPainter is PyQt4.QtGui.QPainter assert QtWidgets.QWidget is PyQt4.QtGui.QWidget assert QtWebEngineWidgets.QWebEnginePage is PyQt4.QtWebKit.QWebPage elif QT_API == 'pyqt5': import PyQt5 assert QtCore.QEvent is PyQt5.QtCore.QEvent assert QtGui.QPainter is PyQt5.QtGui.QPainter assert QtWidgets.QWidget is PyQt5.QtWidgets.QWidget assert QtWebEngineWidgets.QWebEnginePage is PyQt5.QtWebEngineWidgets.QWebEnginePage else: pass
Fix for conformance statement error
package uk.nhs.careconnect.ri.gatewaylib.camel.interceptor; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class GatewayPostProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { if (exchange.getIn().getHeader("X-Request-ID") == null || exchange.getIn().getHeader("X-Request-ID").toString().isEmpty()) { exchange.getIn().removeHeader("X-Request-ID"); } if (exchange.getIn().getHeader("X-Forwarded-For") == null || exchange.getIn().getHeader("X-Forwarded-For").toString().isEmpty()) { exchange.getIn().removeHeader("X-Forwarded-For"); } if (exchange.getIn().getHeader("X-Forwarded-Host") == null || exchange.getIn().getHeader("X-Forwarded-Host").toString().isEmpty()) { exchange.getIn().removeHeader("X-Forwarded-Host"); } // Remove cors headers removeHeader(exchange,"Access-Control-Allow-Methods"); removeHeader(exchange,"Access-Control-Allow-Origin"); removeHeader(exchange,"Access-Control-Max-Age"); removeHeader(exchange,"action"); } private void removeHeader(Exchange exchange, String header) { if (exchange.getIn().getHeader(header) != null ) { exchange.getIn().removeHeader(header); } } }
package uk.nhs.careconnect.ri.gatewaylib.camel.interceptor; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class GatewayPostProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { if (exchange.getIn().getHeader("X-Request-ID") == null || exchange.getIn().getHeader("X-Request-ID").toString().isEmpty()) { exchange.getIn().removeHeader("X-Request-ID"); } if (exchange.getIn().getHeader("X-Forwarded-For") == null || exchange.getIn().getHeader("X-Forwarded-For").toString().isEmpty()) { exchange.getIn().removeHeader("X-Forwarded-For"); } if (exchange.getIn().getHeader("X-Forwarded-Host") == null || exchange.getIn().getHeader("X-Forwarded-Host").toString().isEmpty()) { exchange.getIn().removeHeader("X-Forwarded-Host"); } // Remove cors headers removeHeader(exchange,"Access-Control-Allow-Methods"); removeHeader(exchange,"Access-Control-Allow-Origin"); removeHeader(exchange,"Access-Control-Max-Age"); removeHeader(exchange,"action"); } private void removeHeader(Exchange exchange, String header) { if (exchange.getIn().getHeader(header) != null ) { exchange.getIn().removeHeader(header); } } }
Change embedded join link to direct klicker.uzh.ch domain
import React from 'react' import PropTypes from 'prop-types' import { compose, withProps } from 'recompose' import QRCode from 'qrcode.react' import { withRouter } from 'next/router' import { StaticLayout } from '../components/layouts' import { withLogging } from '../lib' const propTypes = { shortname: PropTypes.string.isRequired, } const QR = ({ shortname }) => { const joinLink = process.env.APP_JOIN_URL ? `${process.env.APP_JOIN_URL}/${shortname}` : `${process.env.APP_BASE_URL}/join/${shortname}` return ( <StaticLayout pageTitle="QR"> <div className="link">{joinLink.replace(/^https?:\/\//, '')}</div> <div className="qr"> <QRCode size={700} value={`${process.env.APP_BASE_URL}/join/${shortname}`} /> </div> <style jsx>{` @import 'src/theme'; .link { line-height: 4rem; font-size: ${process.env.APP_JOIN_URL ? '5rem' : '4rem'}; font-weight: bold; margin-bottom: 2rem; } .qr { display: flex; align-items: center; justify-content: center; } `}</style> </StaticLayout> ) } QR.propTypes = propTypes export default compose( withRouter, withLogging(), withProps(({ router }) => ({ shortname: router.query.shortname, })) )(QR)
import React from 'react' import PropTypes from 'prop-types' import { compose, withProps } from 'recompose' import QRCode from 'qrcode.react' import { withRouter } from 'next/router' import { StaticLayout } from '../components/layouts' import { withLogging } from '../lib' const propTypes = { shortname: PropTypes.string.isRequired, } const QR = ({ shortname }) => { const joinLink = process.env.APP_JOIN_URL ? `${process.env.APP_JOIN_URL}/${shortname}` : `${process.env.APP_BASE_URL}/join/${shortname}` return ( <StaticLayout pageTitle="QR"> <div className="link">{joinLink.replace(/^https?:\/\//, '')}</div> <div className="qr"> <QRCode size={700} value={joinLink} /> </div> <style jsx>{` @import 'src/theme'; .link { line-height: 4rem; font-size: ${process.env.APP_JOIN_URL ? '5rem' : '4rem'}; font-weight: bold; margin-bottom: 2rem; } .qr { display: flex; align-items: center; justify-content: center; } `}</style> </StaticLayout> ) } QR.propTypes = propTypes export default compose( withRouter, withLogging(), withProps(({ router }) => ({ shortname: router.query.shortname, })) )(QR)
Remove comments and source-map from the minified version.
const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const path = require("path"); module.exports = { mode: "development", devtool: "inline-source-map", entry: { IntelliSearch: "./src/SearchClient.ts", "IntelliSearch.min": "./src/SearchClient.ts" }, output: { path: path.resolve(__dirname, "dist"), filename: "[name].js", libraryTarget: "umd", library: "IntelliSearch", umdNamedDefine: true }, resolve: { mainFields: ["browser", "module", "main"], // Add `.ts` and `.tsx` as a resolvable extension. extensions: [".ts", ".tsx", ".js"] }, plugins: [ new UglifyJsPlugin({ sourceMap: false, extractComments: true, include: /\.min\.js$/ }) ], module: { rules: [ // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` { test: /\.tsx?$/, loader: "ts-loader" } ] }, watch: false, watchOptions: { aggregateTimeout: 300, // The default ignored: ["dist", "es", "lib", "doc", "samples", "node_modules"] } };
const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const path = require("path"); module.exports = { mode: "development", devtool: "inline-source-map", entry: { IntelliSearch: "./src/SearchClient.ts", "IntelliSearch.min": "./src/SearchClient.ts" }, output: { path: path.resolve(__dirname, "dist"), filename: "[name].js", libraryTarget: "umd", library: "IntelliSearch", umdNamedDefine: true }, resolve: { mainFields: ["browser", "module", "main"], // Add `.ts` and `.tsx` as a resolvable extension. extensions: [".ts", ".tsx", ".js"] }, plugins: [ new UglifyJsPlugin({ sourceMap: true, include: /\.min\.js$/ }) ], module: { rules: [ // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader` { test: /\.tsx?$/, loader: "ts-loader" } ] }, watch: false, watchOptions: { aggregateTimeout: 300, // The default ignored: ["dist", "es", "lib", "doc", "samples", "node_modules"] } };
Remove unnecessary scratch file flag
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
import re from threading import Timer import sublime_plugin import sublime DEFAULT_NAME = 'Find Results' ALT_NAME_BASE = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): t = Timer(.001, self.update_view, (view,)) t.start() # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.update_view(view) def get_alt_name(self, view): first_line_coords = view.full_line(sublime.Region(0, 0)) first_line = view.substr(sublime.Region(*first_line_coords)) match = re.search('^Searching \d+ files for "(.*)"$', first_line) if match: query = match.group(1) return ALT_NAME_BASE + 'for "' + query + '"' return ALT_NAME_BASE def update_view(self, view): view.set_name(self.get_alt_name(view)) view.set_scratch(True) def is_search_view(self, view): name = view.name() return ( name == DEFAULT_NAME or name == ALT_NAME_BASE or name == self.get_alt_name(view) )
Rename seed clients for consistency.
<?php use Illuminate\Database\Seeder; use Northstar\Models\Client; use Northstar\Auth\Scope; class ClientTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('clients')->delete(); // For easy testing, we'll seed one client for web authentication: factory(Client::class, 'authorization_code')->create([ 'title' => 'Local Development', 'description' => 'This is an example web OAuth client seeded with your local Northstar installation.', 'allowed_grant' => 'authorization_code', 'client_id' => 'dev-oauth', 'client_secret' => 'secret1', 'scope' => collect(Scope::all())->except('admin')->keys()->toArray(), // @NOTE: We're omitting 'redirect_uri' here for easy local dev. 'redirect_uri' => null, ]); // ..and one for machine authentication: factory(Client::class, 'client_credentials')->create([ 'title' => 'Local Development (Machine)', 'description' => 'This is an example machine OAuth client seeded with your local Northstar installation.', 'allowed_grant' => 'client_credentials', 'client_id' => 'dev-machine', 'client_secret' => 'secret2', 'scope' => collect(Scope::all())->keys()->toArray(), ]); } }
<?php use Illuminate\Database\Seeder; use Northstar\Models\Client; use Northstar\Auth\Scope; class ClientTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('clients')->delete(); // For easy testing, we'll seed one client for web authentication: factory(Client::class, 'authorization_code')->create([ 'title' => 'Local Development', 'description' => 'This is an example web OAuth client seeded with your local Northstar installation.', 'allowed_grant' => 'authorization_code', 'client_id' => 'oauth-test-client', 'client_secret' => 'secret1', 'scope' => collect(Scope::all())->except('admin')->keys()->toArray(), // @NOTE: We're omitting 'redirect_uri' here for easy local dev. 'redirect_uri' => null, ]); // ..and one for machine authentication: factory(Client::class, 'client_credentials')->create([ 'title' => 'Local Development (Machine)', 'description' => 'This is an example machine OAuth client seeded with your local Northstar installation.', 'allowed_grant' => 'client_credentials', 'client_id' => 'machine-test-client', 'client_secret' => 'secret2', 'scope' => collect(Scope::all())->keys()->toArray(), ]); } }
Convert direction to upper case
#!/usr/bin/env python3 from nanagogo.api import NanagogoRequest, NanagogoError, s def get(path, params={}): r = NanagogoRequest(path, method="GET", params=params) return r.wrap() def post(path, params={}, data=None): r = NanagogoRequest(path, method="POST", params=params, data=data) return r.wrap() class NanagogoTalk(object): def __init__(self, name): self.name = name @property def info(self): path = ("talks", self.name) return get(path) def feed(self, count=30, targetid=None, direction="PREV"): path = ("talks", self.name, "posts") params = {'limit': count, 'targetId': targetid, 'direction': direction.upper()} return get(path, params=params) def iterfeed(self, count=200, targetid=None): while True: feed = self.feed(count=count, targetid=targetid, direction="PREV") if len(feed) == 0: break yield feed targetid = feed[-1]['post']['postId'] - 1 if targetid <= 0: break if __name__ == "__main__": tani = NanagogoTalk('tani-marika') print(tani.info)
#!/usr/bin/env python3 from nanagogo.api import NanagogoRequest, NanagogoError def get(path, params={}): r = NanagogoRequest(path, method="GET", params=params) return r.wrap() def post(path, params={}, data=None): r = NanagogoRequest(path, method="POST", params=params, data=data) return r.wrap() class NanagogoTalk(object): def __init__(self, name): self.name = name @property def info(self): path = ("talks", self.name) return get(path) def feed(self, count=30, targetid=None, direction="PREV"): path = ("talks", self.name, "posts") params = {'limit': count, 'targetId': targetid, 'direction': direction} return get(path, params=params) def iterfeed(self, count=200, targetid=None): while True: feed = self.feed(count=count, targetid=targetid, direction="PREV") if len(feed) == 0: break yield feed targetid = feed[-1]['post']['postId'] - 1 if targetid <= 0: break if __name__ == "__main__": tani = NanagogoTalk('tani-marika') print(tani.info)
Remove /want help; already is invalid usage so shows default help
package com.exphc.FreeTrade; import java.util.logging.Logger; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.*; import org.bukkit.entity.*; public class FreeTrade extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); public void onEnable() { log.info("FreeTrade enabled"); } public void onDisable() { log.info("FreeTrade disabled"); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player; String wanted, giving; if (!cmd.getName().equalsIgnoreCase("want")) { return false; } // /want if (args.length == 0) { return showOutstanding(sender); } if (sender instanceof Player) { player = (Player)sender; } else { // TODO: get player from name as first argument sender.sendMessage("this command can only be run by a player"); } if (args.length < 2) { return false; } wanted = args[0]; if (args[1].equalsIgnoreCase("for")) { giving = args[2]; } else { giving = args[1]; } sender.sendMessage("you want " + wanted + " for " + giving); return true; } public boolean showOutstanding(CommandSender sender) { sender.sendMessage("TODO: show open orders"); return false; } }
package com.exphc.FreeTrade; import java.util.logging.Logger; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.*; import org.bukkit.entity.*; public class FreeTrade extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); public void onEnable() { log.info("FreeTrade enabled"); } public void onDisable() { log.info("FreeTrade disabled"); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player; String wanted, giving; if (!cmd.getName().equalsIgnoreCase("want")) { return false; } // /want if (args.length == 0) { return showOutstanding(sender); } // /want help if (args[0].equalsIgnoreCase("help")) { return showHelp(sender); } if (sender instanceof Player) { player = (Player)sender; } else { // TODO: get player from name as first argument sender.sendMessage("this command can only be run by a player"); } if (args.length < 2) { return false; } wanted = args[0]; if (args[1].equalsIgnoreCase("for")) { giving = args[2]; } else { giving = args[1]; } sender.sendMessage("you want " + wanted + " for " + giving); return true; } public boolean showOutstanding(CommandSender sender) { sender.sendMessage("TODO: show open orders"); return false; } public boolean showHelp(CommandSender sender) { sender.sendMessage("TODO: show help"); // TODO: hook into built-in bukkit help? /help? return false; } }
Add user tooltip and links in message
import React from 'react'; import { FormattedRelative } from 'react-intl'; import { Link } from 'react-router'; import Body from '../post/Body'; import Avatar from '../widgets/Avatar'; import ProfileTooltipOrigin from '../user/profileTooltip/ProfileTooltipOrigin'; const Message = (props) => { const { model } = props; const sentAt = model[0].sentAt; const senderUsername = (model[0].senderUsername || model[0].sentBy); return ( <div className="Message message"> <div className="container"> <div data-uuid={model[0].uuid}> <div className="Message__left"> <ProfileTooltipOrigin username={senderUsername}> <Link to={`/@${senderUsername}`}> <Avatar sm username={senderUsername} /> </Link> </ProfileTooltipOrigin> </div> <div className="ml-5"> <div className="media-heading"> <b> <ProfileTooltipOrigin username={senderUsername}> <Link to={`/@${senderUsername}`}> {senderUsername} </Link> </ProfileTooltipOrigin> </b>{' '} <span className="text-info"> <FormattedRelative value={sentAt} /> </span> </div> <Body body={model[0].text} /> </div> </div> </div> {model.slice(1).map(({ uuid, text }, i) => <div className="container" key={i} data-uuid={uuid}> <div className="ml-5"> <Body body={text} /> </div> </div> )} </div> ); }; export default Message;
import React from 'react'; import { FormattedRelative } from 'react-intl'; import Body from '../post/Body'; import Avatar from '../widgets/Avatar'; const Message = (props) => { const { model } = props; const sentAt = model[0].sentAt; const senderUsername = (model[0].senderUsername || model[0].sentBy); return ( <div className="Message message"> <div className="container"> <div data-uuid={model[0].uuid}> <div className="Message__left"> <Avatar sm username={senderUsername} /> </div> <div className="ml-5"> <div className="media-heading"> <b>{senderUsername}</b>{' '} <span className="text-info"> <FormattedRelative value={sentAt} /> </span> </div> <Body body={model[0].text} /> </div> </div> </div> {model.slice(1).map(({ uuid, text }, i) => <div className="container" key={i} data-uuid={uuid}> <div className="ml-5"> <Body body={text} /> </div> </div> )} </div> ); }; export default Message;
Send to cloud every 60 seconds
package agent import ( "time" "fmt" "github.com/crowdmob/goamz/aws" "github.com/crowdmob/goamz/cloudwatch" ) const ( SCHEDULED_LOOP = 60 ) var cw *cloudwatch.CloudWatch func init() { region := aws.Regions["eu-west-1"] auth, err := aws.EnvAuth() if err != nil { L.Err("Unable to send data to CloudWatch") panic("Unable to send data to CloudWatch") } cw,_ = cloudwatch.NewCloudWatch(auth, region.CloudWatchServicepoint) } func SendCollectedData() { doEvery(SCHEDULED_LOOP * time.Second, func(time time.Time) { Database.Lock() for key, point := range Database.metrics { metric := new(cloudwatch.MetricDatum) metric.MetricName = point.Metric metric.Timestamp = time metric.Unit = "" metric.Value = point.Value metrics := []cloudwatch.MetricDatum{*metric} if _, err := cw.PutMetricDataNamespace(metrics, point.Namespace); err != nil { L.Err(fmt.Sprintf("%v", err)) } else { L.Info("Metric with key: \"" + key + "\" sent to cloud correcly") } delete(Database.metrics, key) } Database.Unlock() }) } func doEvery(d time.Duration, f func(time.Time)) { for { time.Sleep(d) f(time.Now()) } }
package agent import ( "time" "fmt" "github.com/crowdmob/goamz/aws" "github.com/crowdmob/goamz/cloudwatch" ) const ( SCHEDULED_LOOP = 6 ) var cw *cloudwatch.CloudWatch func init() { region := aws.Regions["eu-west-1"] auth, err := aws.EnvAuth() if err != nil { L.Err("Unable to send data to CloudWatch") panic("Unable to send data to CloudWatch") } cw,_ = cloudwatch.NewCloudWatch(auth, region.CloudWatchServicepoint) } func SendCollectedData() { doEvery(SCHEDULED_LOOP * time.Second, func(time time.Time) { Database.Lock() for key, point := range Database.metrics { metric := new(cloudwatch.MetricDatum) metric.MetricName = point.Metric metric.Timestamp = time metric.Unit = "" metric.Value = point.Value metrics := []cloudwatch.MetricDatum{*metric} if _, err := cw.PutMetricDataNamespace(metrics, point.Namespace); err != nil { L.Err(fmt.Sprintf("%v", err)) } else { L.Info("Metric with key: \"" + key + "\" sent to cloud correcly") } delete(Database.metrics, key) } Database.Unlock() }) } func doEvery(d time.Duration, f func(time.Time)) { for { time.Sleep(d) f(time.Now()) } }
Add override listener to Dashboard.
<?php namespace Octo\System\Admin\Controller; use b8\Config; use Octo\Admin\Controller; use Octo\Event; use Octo\Store; use Octo\System\Model\Setting; class DashboardController extends Controller { public function index() { $this->setTitle(Config::getInstance()->get('site.name') . ': Dashboard'); $this->addBreadcrumb('Dashboard', '/'); $moduleManager = Config::getInstance()->get('ModuleManager'); $pageStore = Store::get('Page'); if ($pageStore && $moduleManager->isEnabled('Pages')) { $this->view->pages = $pageStore->getTotal(); $this->view->latestPages = $pageStore->getLatest(5); } if ($moduleManager->isEnabled('Forms')) { $contactStore = Store::get('Contact'); if ($contactStore) { $this->view->contacts = $contactStore->getTotal(); } $submissionStore = Store::get('Submission'); if ($submissionStore) { $this->view->submissions = $submissionStore->getTotal(); $this->view->latestSubmissions = $submissionStore->getAll(0, 5); } } $this->view->showAnalytics = false; if (Setting::get('analytics', 'ga_email') != '') { $this->view->showAnalytics = true; } $instance = clone($this); // Can't pass and return $this to a listener, sadface. Event::trigger('dashboardLoad', $instance); $this->view = $instance->view; } }
<?php namespace Octo\System\Admin\Controller; use b8\Config; use Octo\Admin\Controller; use Octo\Event; use Octo\Store; use Octo\System\Model\Setting; class DashboardController extends Controller { public function index() { $this->setTitle(Config::getInstance()->get('site.name') . ': Dashboard'); $this->addBreadcrumb('Dashboard', '/'); $moduleManager = Config::getInstance()->get('ModuleManager'); $pageStore = Store::get('Page'); if ($pageStore && $moduleManager->isEnabled('Pages')) { $this->view->pages = $pageStore->getTotal(); $this->view->latestPages = $pageStore->getLatest(5); } if ($moduleManager->isEnabled('Forms')) { $contactStore = Store::get('Contact'); if ($contactStore) { $this->view->contacts = $contactStore->getTotal(); } $submissionStore = Store::get('Submission'); if ($submissionStore) { $this->view->submissions = $submissionStore->getTotal(); $this->view->latestSubmissions = $submissionStore->getAll(0, 5); } } $this->view->showAnalytics = false; if (Setting::get('analytics', 'ga_email') != '') { $this->view->showAnalytics = true; } Event::trigger('dashboardLoad', $this); } }
Set default AUTOGEN_TEST to 0
INPUT_DECL_PATHS = [ "../../target/device/libio/export" # "../../../pia-sdk-repo/iolib/arduino/arduiPIA.h" ] AUTOGEN_TEST = 0 if AUTOGEN_TEST == 1: INPUT_DECL_PATHS = [ "./testSuite/" ] VERSION = '0.0.1' TARGET = 'galileo' OUTPUT_COMP_PATH = '../../target/companion/lib/board/' OUTPUT_DEV_PATH = '../../target/device/src' OUTPUT_SERVER_PATH = '../../target/server/lib/board' OUTPUT_CMD_MAP_PATH = '../../target/doc/' EXPORT_DEF = 'main.h' EXPORT_CPP = 'main.cpp' GLOBAL_DEF = '_globalvar.h' GLOBAL_CPP = '_globalvar.cpp' EXPORT_MODULE = 'galileo' GYP_PATH = OUTPUT_DEV_PATH + '/../' GYP_SRC_PATH = 'src/' #the relative path of GYP_SRC_PATH to OUTPUT_DEV_PATH from GYP_FILE = 'binding.gyp' Global_CLASS_VAR_FILE = 'globalClassVarSetterGetter.js' INSTANCE_V8CLASS_ARG = '__instanceV8' # used to generate a V8 class Object without # corresponding C class generated. INC_MAKEFILE = 'autogen.make' DEBUG = 1
INPUT_DECL_PATHS = [ "../../target/device/libio/export" # "../../../pia-sdk-repo/iolib/arduino/arduiPIA.h" ] AUTOGEN_TEST = 1 if AUTOGEN_TEST == 1: INPUT_DECL_PATHS = [ "./testSuite/" ] VERSION = '0.0.1' TARGET = 'galileo' OUTPUT_COMP_PATH = '../../target/companion/lib/board/' OUTPUT_DEV_PATH = '../../target/device/src' OUTPUT_SERVER_PATH = '../../target/server/lib/board' OUTPUT_CMD_MAP_PATH = '../../target/doc/' EXPORT_DEF = 'main.h' EXPORT_CPP = 'main.cpp' GLOBAL_DEF = '_globalvar.h' GLOBAL_CPP = '_globalvar.cpp' EXPORT_MODULE = 'galileo' GYP_PATH = OUTPUT_DEV_PATH + '/../' GYP_SRC_PATH = 'src/' #the relative path of GYP_SRC_PATH to OUTPUT_DEV_PATH from GYP_FILE = 'binding.gyp' Global_CLASS_VAR_FILE = 'globalClassVarSetterGetter.js' INSTANCE_V8CLASS_ARG = '__instanceV8' # used to generate a V8 class Object without # corresponding C class generated. INC_MAKEFILE = 'autogen.make' DEBUG = 1
Update stratisd-client-dbus requirement to 0.07 Signed-off-by: mulhern <[email protected]>
import os import sys import setuptools if sys.version_info[0] < 3: from codecs import open def local_file(name): return os.path.relpath(os.path.join(os.path.dirname(__file__), name)) README = local_file("README.rst") with open(local_file("src/stratis_cli/_version.py")) as o: exec(o.read()) setuptools.setup( name='stratis-cli', version=__version__, author='Anne Mulhern', author_email='[email protected]', description='prototype stratis cli', long_description=open(README, encoding='utf-8').read(), platforms=['Linux'], license='Apache 2.0', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Filesystems', 'Topic :: Systems Administration' ], install_requires = [ 'stratisd-client-dbus>=0.07' ], package_dir={"": "src"}, packages=setuptools.find_packages("src"), scripts=['bin/stratis'] )
import os import sys import setuptools if sys.version_info[0] < 3: from codecs import open def local_file(name): return os.path.relpath(os.path.join(os.path.dirname(__file__), name)) README = local_file("README.rst") with open(local_file("src/stratis_cli/_version.py")) as o: exec(o.read()) setuptools.setup( name='stratis-cli', version=__version__, author='Anne Mulhern', author_email='[email protected]', description='prototype stratis cli', long_description=open(README, encoding='utf-8').read(), platforms=['Linux'], license='Apache 2.0', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries', 'Topic :: System :: Filesystems', 'Topic :: Systems Administration' ], install_requires = [ 'stratisd-client-dbus>=0.06' ], package_dir={"": "src"}, packages=setuptools.find_packages("src"), scripts=['bin/stratis'] )
Add slightly more descriptive keywords for PyPI
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'pyparsing' ] test_requirements = [ ] setup( name='boolrule', version='0.1.0', description="Simple boolean expression evaluation engine", long_description=readme + '\n\n' + history, author="Steve Webster", author_email='[email protected]', url='https://github.com/tailsdotcom/boolrule', packages=[ 'boolrule', ], package_dir={'boolrule': 'boolrule'}, include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='boolrule boolean expression', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'pyparsing' ] test_requirements = [ ] setup( name='boolrule', version='0.1.0', description="Simple boolean expression evaluation engine", long_description=readme + '\n\n' + history, author="Steve Webster", author_email='[email protected]', url='https://github.com/tailsdotcom/boolrule', packages=[ 'boolrule', ], package_dir={'boolrule': 'boolrule'}, include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='boolrule', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], test_suite='tests', tests_require=test_requirements )
Fix destination be at current directory
<?php namespace FaizShukri\Quran\Supports; class Config { private $config; public function __construct(array $config = []) { $this->config = $this->buildConfig($config); } /** * Build a config array. Merge user defined config with our default config. * * @param array $config User defined config * * @return array New configuration array */ private function buildConfig(array $config = []) { // Merge our config with user config $result = array_replace_recursive((include realpath(__DIR__.'/../../config/quran.php')), $config); // If function storage_path is exist (laravel), we update the path to laravel's storage path if (function_exists('storage_path') && php_sapi_name() !== 'cli') { $result['storage_path'] = storage_path('app/' . $result['storage_path']); } else { $result['storage_path'] = realpath(__DIR__ . '/../..') . '/' . $result['storage_path']; } return $result; } /** * Get the config variable. * * @param string $val Variable name * * @return array|string Variable value */ public function get($val) { $configs = explode('.', $val); $first = $this->config[array_shift($configs)]; foreach ($configs as $config) { $first = $first[$config]; } return $first; } /** * Return all configurations. * * @return array */ public function all() { return $this->config; } }
<?php namespace FaizShukri\Quran\Supports; class Config { private $config; public function __construct(array $config = []) { $this->config = $this->buildConfig($config); } /** * Build a config array. Merge user defined config with our default config. * * @param array $config User defined config * * @return array New configuration array */ private function buildConfig(array $config = []) { // Merge our config with user config $result = array_replace_recursive((include realpath(__DIR__.'/../../config/quran.php')), $config); // If function storage_path is exist (laravel), we update the path to laravel's storage path if (function_exists('storage_path') && php_sapi_name() !== 'cli') { $result['storage_path'] = storage_path('app'.DIRECTORY_SEPARATOR.$result['storage_path']); } return $result; } /** * Get the config variable. * * @param string $val Variable name * * @return array|string Variable value */ public function get($val) { $configs = explode('.', $val); $first = $this->config[array_shift($configs)]; foreach ($configs as $config) { $first = $first[$config]; } return $first; } /** * Return all configurations. * * @return array */ public function all() { return $this->config; } }