text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add option to enable self updating This is a customization option for more flexibility. If you want to autoupdate, then you can give a -u option. If not - don't.
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-u', '--updater', action='store_true', help='enable self updating', ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that`s how you`d detect a sneaky chinese bot.', prog='mfh.py', ) client_group = parser.add_mutually_exclusive_group() client_group.add_argument( '-c', action='store_true', help='launch client with on port defined in settings', ) client_group.add_argument( '--client', help='port to start a client on', metavar='PORT', nargs='?', type=int, ) parser.add_argument( '-v', '--verbose', action='store_true', help='increase output verbosity', ) return parser.parse_args()
Change subjects -> subject_ids when retiring subjects
from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.subject import Subject class Workflow(PanoptesObject): _api_slug = 'workflows' _link_slug = 'workflows' _edit_attributes = [] def retire_subjects(self, subjects, reason='other'): if type(subjects) not in (list, tuple): subjects = [ subjects ] subjects = [ s.id if isinstance(s, Subject) else s for s in subjects ] return Workflow.post( '{}/retired_subjects'.format(self.id), json={ 'subject_ids': subjects, 'retirement_reason': reason } ) LinkResolver.register(Workflow)
from panoptes_client.panoptes import PanoptesObject, LinkResolver from panoptes_client.subject import Subject class Workflow(PanoptesObject): _api_slug = 'workflows' _link_slug = 'workflows' _edit_attributes = [] def retire_subjects(self, subjects, reason='other'): if type(subjects) not in (list, tuple): subjects = [ subjects ] subjects = [ s.id if isinstance(s, Subject) else s for s in subjects ] return Workflow.post( '{}/retired_subjects'.format(self.id), json={ 'subjects': subjects, 'retirement_reason': reason } ) LinkResolver.register(Workflow)
Create custom test for Jinja2
import sys from flask import Flask, render_template from flask_flatpages import FlatPages, flatpages from flask_frozen import Freezer DEBUG = True FLATPAGES_AUTO_RELOAD = DEBUG FLATPAGES_EXTENSION = '.md' FREEZER_DESTINATION = 'dist' app = Flask(__name__) app.config.from_object(__name__) pages = FlatPages(app) freezer = Freezer(app) @app.route('/') @app.route('/bio/') def index(): return render_template('bio.html', pages=pages) @app.route('/portfolio/') def portfolio(): projects = (p for p in pages if 'date' in p.meta) projects = sorted(projects, reverse=True, key=lambda p: p.meta['date']) return render_template('portfolio.html', pages=projects) @app.route('/portfolio/<path:path>/') def page(path): page = pages.get_or_404(path) return render_template('project.html', page=page) @app.route('/contatti/') def contatti(): page = pages.get_or_404("contatti") return render_template('page.html', page=page) @app.template_test("list") def is_list(value): return isinstance(value, list) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == "build": freezer.freeze() else: app.run(port=8080)
import sys from flask import Flask, render_template from flask_flatpages import FlatPages, flatpages from flask_frozen import Freezer DEBUG = True FLATPAGES_AUTO_RELOAD = DEBUG FLATPAGES_EXTENSION = '.md' FREEZER_DESTINATION = 'dist' app = Flask(__name__) app.config.from_object(__name__) pages = FlatPages(app) freezer = Freezer(app) @app.route('/') @app.route('/bio/') def index(): return render_template('bio.html', pages=pages) @app.route('/portfolio/') def portfolio(): projects = (p for p in pages if 'date' in p.meta) projects = sorted(projects, reverse=True, key=lambda p: p.meta['date']) return render_template('portfolio.html', pages=projects) @app.route('/portfolio/<path:path>/') def page(path): page = pages.get_or_404(path) return render_template('project.html', page=page) @app.route('/contatti/') def contatti(): page = pages.get_or_404("contatti") return render_template('page.html', page=page) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == "build": freezer.freeze() else: app.run(port=8080)
Fix a bug where close event was not sent
<?php declare(strict_types=1); namespace HomoChecker\View; class ServerSentEventView implements ViewInterface { public $event; public function __construct($event) { $this->event = $event; // @codeCoverageIgnoreStart if (!headers_sent()) { header('Content-Type: text/event-stream'); } // @codeCoverageIgnoreEnd // 2 KiB padding echo ":" . str_repeat(" ", 2048) . "\n"; $this->flush(); } /** * @codeCoverageIgnore */ public function render($data, $event = null): void { $event = $event ?? $this->event; echo "event: {$event}\n"; echo "data: " . json_encode($data) . "\n\n"; $this->flush(); } public function flush(): void { @ob_flush(); flush(); } public function close(): void { echo "event: close\n"; echo "data: end\n\n"; $this->flush(); } }
<?php declare(strict_types=1); namespace HomoChecker\View; class ServerSentEventView implements ViewInterface { public $event; public function __construct($event) { $this->event = $event; // @codeCoverageIgnoreStart if (!headers_sent()) { header('Content-Type: text/event-stream'); } // @codeCoverageIgnoreEnd // 2 KiB padding echo ":" . str_repeat(" ", 2048) . "\n"; $this->flush(); } /** * @codeCoverageIgnore */ public function render($data, $event = null): void { $event = $event ?? $this->event; echo "event: {$event}\n"; echo "data: " . json_encode($data) . "\n\n"; $this->flush(); } public function flush(): void { @ob_flush(); flush(); } public function close(): void { echo "event: close\n"; echo "data: end\n\n"; } }
Fix mistake in ColorModel from ABGR into ARGB
package pl.edu.uj.JImageStream.model; import pl.edu.uj.JImageStream.api.ImageStream; import pl.edu.uj.JImageStream.util.Util; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; //todo needs some added functionality, return bufferedImage, etc public class StreamableImage { private BufferedImage bufferedImage; //todo extract to IOImageUtilsClass, maybe public StreamableImage(File file) throws IOException { bufferedImage = Util.convert(ImageIO.read(file), BufferedImage.TYPE_INT_ARGB_PRE); } public StreamableImage(BufferedImage bufferedImage) { this.bufferedImage = bufferedImage; } //todo same, maybe public void save(String format, String file) throws IOException { ImageIO.write(bufferedImage, format, new File(file)); } public int getHeight() { return bufferedImage.getHeight(); } public int getWidth() { return bufferedImage.getWidth(); } public ImageStream stream() { return new ImageStream(bufferedImage, false); } public ImageStream parallelStream() { return new ImageStream(bufferedImage, true); } }
package pl.edu.uj.JImageStream.model; import pl.edu.uj.JImageStream.api.ImageStream; import pl.edu.uj.JImageStream.util.Util; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; //todo needs some added functionality, return bufferedImage, etc public class StreamableImage { private BufferedImage bufferedImage; //todo extract to IOImageUtilsClass, maybe public StreamableImage(File file) throws IOException { bufferedImage = Util.convert(ImageIO.read(file), BufferedImage.TYPE_4BYTE_ABGR_PRE); } public StreamableImage(BufferedImage bufferedImage) { this.bufferedImage = bufferedImage; } //todo same, maybe public void save(String format, String file) throws IOException { ImageIO.write(bufferedImage, format, new File(file)); } public int getHeight() { return bufferedImage.getHeight(); } public int getWidth() { return bufferedImage.getWidth(); } public ImageStream stream() { return new ImageStream(bufferedImage, false); } public ImageStream parallelStream() { return new ImageStream(bufferedImage, true); } }
Make setRadius and updateStyle({radius: 123 }) work.
/* * L.CircleMarker is a circle overlay with a permanent pixel radius. */ L.CircleMarker = L.Circle.extend({ options: { radius: 10, weight: 2 }, initialize: function (latlng, options) { L.Circle.prototype.initialize.call(this, latlng, null, options); this._radius = this.options.radius; }, projectLatlngs: function () { this._point = this._map.latLngToLayerPoint(this._latlng); }, _updateStyle : function () { L.Circle.prototype._updateStyle.call(this); this.setRadius(this.options.radius); }, setRadius: function (radius) { this.options.radius = this._radius = radius; return this.redraw(); } }); L.circleMarker = function (latlng, options) { return new L.CircleMarker(latlng, options); };
/* * L.CircleMarker is a circle overlay with a permanent pixel radius. */ L.CircleMarker = L.Circle.extend({ options: { radius: 10, weight: 2 }, initialize: function (latlng, options) { L.Circle.prototype.initialize.call(this, latlng, null, options); this._radius = this.options.radius; }, projectLatlngs: function () { this._point = this._map.latLngToLayerPoint(this._latlng); }, _updateStyle : function () { L.Circle.prototype._updateStyle.call(this); }, setRadius: function (radius) { this._radius = radius; return this.redraw(); } }); L.circleMarker = function (latlng, options) { return new L.CircleMarker(latlng, options); };
Fix YAMLStorage as per TinyDB doc changes
import yaml import sys from tinydb.database import Document from tinydb.storages import Storage, touch def represent_doc(dumper, data): # Represent `Document` objects as their dict's string representation # which PyYAML understands return dumper.represent_data(dict(data)) yaml.add_representer(Document, represent_doc) class YAMLStorage(Storage): def __init__(self, filename): self.filename = filename touch(filename, False) def read(self): with open(self.filename) as handle: data = yaml.safe_load(handle.read()) return data def write(self, data): with open(self.filename, 'w') as handle: yaml.dump(data, handle) def close(self): pass
import yaml import sys from tinydb.storages import Storage class YAMLStorage(Storage): def __init__(self, filename): # (1) self.filename = filename def read(self): with open(self.filename) as handle: try: data = yaml.safe_load(handle.read()) # (2) return data except yaml.YAMLError: return None # (3) def write(self, data): with open(self.filename, 'w') as handle: yaml.dump(yaml.safe_load(str(data)), handle) def close(self): # (4) pass
Update constants as per db list
package com.koustuvsinha.benchmarker.utils; import com.koustuvsinha.benchmarker.models.DbFactoryModel; import java.util.ArrayList; /** * Created by koustuv on 24/5/15. */ public class Constants { public static ArrayList<DbFactoryModel> DB_LIST = new ArrayList<DbFactoryModel>() {{ add(new DbFactoryModel("Realm","v0.83.3","Realm",true)); add(new DbFactoryModel("ORM Lite Android","v4.48","ORM Lite",true)); add(new DbFactoryModel("Sugar ORM","v1.4","Satya Narayan",true)); add(new DbFactoryModel("Green DAO","v1.3","Green DAO",true)); add(new DbFactoryModel("Active Android","v3.0","Michael Pardo",true)); add(new DbFactoryModel("Android SQLite","v1.0","Android",true)); }}; public static int DB_TYPE_REALM = 1; public static int DB_TYPE_ORMLITE = 2; public static int DB_TYPE_SUGARORM = 3; public static int DB_TYPE_GREENDAO = 4; public static int DB_TYPE_ACTIVEANDROID = 5; public static int DB_TYPE_DEFAULT = 6; }
package com.koustuvsinha.benchmarker.utils; import com.koustuvsinha.benchmarker.models.DbFactoryModel; import java.util.ArrayList; /** * Created by koustuv on 24/5/15. */ public class Constants { public static ArrayList<DbFactoryModel> DB_LIST = new ArrayList<DbFactoryModel>() {{ add(new DbFactoryModel("Realm","v0.83.3","Realm",true)); add(new DbFactoryModel("ORM Lite Android","v4.48","ORM Lite",true)); add(new DbFactoryModel("Sugar ORM","v1.4","Satya Narayan",true)); add(new DbFactoryModel("Green DAO","v1.3","Green DAO",true)); add(new DbFactoryModel("Active Android","v3.0","Michael Pardo",true)); }}; }
Make sure the server has starded before launching tests
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import socket import threading import time import connexion from swagger_tester import swagger_test def test_swagger_test(): swagger_test(os.path.join(os.path.dirname(__file__), 'swagger.yaml')) def get_open_port(): """Get an open port on localhost""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 0)) s.listen(1) port = s.getsockname()[1] s.close() return port def test_swagger_test_app_url(): port = get_open_port() swagger_yaml_path = os.path.join(os.path.dirname(__file__), 'swagger.yaml') app = connexion.App(__name__, port=port, specification_dir=os.path.dirname(os.path.realpath(swagger_yaml_path))) app.add_api(os.path.basename(swagger_yaml_path)) server = threading.Thread(None, app.run) server.daemon = True server.start() time.sleep(3) # Make sure the server has started swagger_test(app_url='http://localhost:{0}/v2'.format(port))
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import socket import threading import connexion from swagger_tester import swagger_test def test_swagger_test(): swagger_test(os.path.join(os.path.dirname(__file__), 'swagger.yaml')) def get_open_port(): """Get an open port on localhost""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 0)) s.listen(1) port = s.getsockname()[1] s.close() return port def test_swagger_test_app_url(): port = get_open_port() swagger_yaml_path = os.path.join(os.path.dirname(__file__), 'swagger.yaml') app = connexion.App(__name__, port=port, specification_dir=os.path.dirname(os.path.realpath(swagger_yaml_path))) app.add_api(os.path.basename(swagger_yaml_path)) server = threading.Thread(None, app.run) server.daemon = True server.start() swagger_test(app_url='http://localhost:{0}/v2'.format(port))
Fix typo in json string
<?php namespace spec\SearchApi\Providers; use SearchApi; use SearchApi\Models; use SearchApi\Services\Search; use SearchApi\Builders\QueryBuilder; use SearchApi\Clients\HttpClient; use PhpSpec\ObjectBehavior; /** * SolrSearchSpec - Spec test for SolrSearch */ class SolrSearchSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType( 'SearchApi\Providers\SolrSearch' ); } function it_should_call_query_builder( QueryBuilder $queryBuilder ) { $this->beConstructedWith( $queryBuilder ); $queryBuilder->build( 'test', null )->shouldBeCalled(); $this->query( 'test' ); } function it_should_return_null_when_keywords_empty() { $result = $this->query( null ); $result->shouldBeNull(); } function it_should_return_search_result_when_keywords_not_empty( QueryBuilder $queryBuilder, HttpClient $httpClient ) { $queryBuilder->build( 'test', null )->willReturn( 'test_query' ); $httpClient->get( 'test_query' )->willReturn( '{"response":{"numFound":1,"start":0,"docs":[{"id":"testid","author":"testauthor","date":"testdate","content":"testcontent"}]}}' ); $result = $this->query( 'test' ); $result->shouldHaveType( 'SearchApi\Models\SearchResult' ); $result->count->shouldBe( 1 ); } }
<?php namespace spec\SearchApi\Providers; use SearchApi; use SearchApi\Models; use SearchApi\Services\Search; use SearchApi\Builders\QueryBuilder; use SearchApi\Clients\HttpClient; use PhpSpec\ObjectBehavior; /** * SolrSearchSpec - Spec test for SolrSearch */ class SolrSearchSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType( 'SearchApi\Providers\SolrSearch' ); } function it_should_call_query_builder( QueryBuilder $queryBuilder ) { $this->beConstructedWith( $queryBuilder ); $queryBuilder->build( 'test', null )->shouldBeCalled(); $this->query( 'test' ); } function it_should_return_null_when_keywords_empty() { $result = $this->query( null ); $result->shouldBeNull(); } function it_should_return_search_result_when_keywords_not_empty( QueryBuilder $queryBuilder, HttpClient $httpClient ) { $queryBuilder->build( 'test', null )->willReturn( 'test_query' ); $httpClient->get( 'test_query' )->willReturn( '{"responseHeader":{"response":{"numFound":1,"start":0,"docs":[{"id":"testid","author":"testauthor","date":"testdate","content":"testcontent"}]}}' ); $result = $this->query( 'test' ); $result->shouldHaveType( 'SearchApi\Models\SearchResult' ); $result->count->shouldBe( 1 ); } }
Fix to use proper file element for session uploads
<?php namespace ZF2FileUploadExamples\Form; use Zend\InputFilter; use Zend\Form\Form; use Zend\Form\Element; class ProgressUpload extends Form { public function __construct($name = null, $options = array()) { parent::__construct($name, $options); $this->addElements(); $this->setInputFilter($this->createInputFilter()); } public function addElements() { // File Input $file = new Element\File('file'); $file ->setLabel('File Input') ->setAttributes(array( 'id' => 'file', 'multiple' => true )); $this->add($file); // Progress ID $progressId = new Element\File\SessionProgress(); $this->add($progressId); $this->byName['progressId'] = $progressId; // Add an alias for the view } public function createInputFilter() { $inputFilter = new InputFilter\InputFilter(); // File Input $file = new InputFilter\FileInput('file'); $file->setRequired(true); $inputFilter->add($file); return $inputFilter; } }
<?php namespace ZF2FileUploadExamples\Form; use Zend\InputFilter; use Zend\Form\Form; use Zend\Form\Element; class ProgressUpload extends Form { public function __construct($name = null, $options = array()) { parent::__construct($name, $options); $this->addElements(); $this->setInputFilter($this->createInputFilter()); } public function addElements() { // File Input $file = new Element\File('file'); $file ->setLabel('File Input') ->setAttributes(array( 'id' => 'file', 'multiple' => true )); $this->add($file); // Progress ID $progressId = new Element\File\UploadProgress(); $this->add($progressId); $this->byName['progressId'] = $progressId; // Add an alias for the view } public function createInputFilter() { $inputFilter = new InputFilter\InputFilter(); // File Input $file = new InputFilter\FileInput('file'); $file->setRequired(true); $inputFilter->add($file); return $inputFilter; } }
Make public feed show all stories, using the omnipotent user Auditors: chad
<?php final class PhabricatorFeedPublicStreamController extends PhabricatorFeedController { public function shouldRequireLogin() { return false; } public function processRequest() { if (!PhabricatorEnv::getEnvConfig('feed.public')) { return new Aphront404Response(); } $request = $this->getRequest(); $viewer = PhabricatorUser::getOmnipotentUser(); $query = new PhabricatorFeedQuery(); $query->setViewer($viewer); $query->setLimit(100); $stories = $query->execute(); $builder = new PhabricatorFeedBuilder($stories); $builder ->setFramed(true) ->setUser($viewer); $view = hsprintf('<div class="phabricator-public-feed-frame">%s</div>', $builder->buildView()); return $this->buildStandardPageResponse( $view, array( 'title' => pht('Public Feed'), 'public' => true, )); } }
<?php final class PhabricatorFeedPublicStreamController extends PhabricatorFeedController { public function shouldRequireLogin() { return false; } public function processRequest() { if (!PhabricatorEnv::getEnvConfig('feed.public')) { return new Aphront404Response(); } $request = $this->getRequest(); $viewer = $request->getUser(); $query = new PhabricatorFeedQuery(); $query->setViewer($viewer); $query->setLimit(100); $stories = $query->execute(); $builder = new PhabricatorFeedBuilder($stories); $builder ->setFramed(true) ->setUser($viewer); $view = hsprintf('<div class="phabricator-public-feed-frame">%s</div>', $builder->buildView()); return $this->buildStandardPageResponse( $view, array( 'title' => pht('Public Feed'), 'public' => true, )); } }
Allow POST requests for auth method so OpenID forms could use it that way.
from pyramid.view import view_config from social.utils import module_member from social.actions import do_auth, do_complete, do_disconnect from social.apps.pyramid_app.utils import psa, login_required @view_config(route_name='social.auth', request_method=('GET', 'POST')) @psa('social.complete') def auth(request): return do_auth(request.backend, redirect_name='next') @view_config(route_name='social.complete', request_method=('GET', 'POST')) @psa('social.complete') def complete(request, *args, **kwargs): do_login = module_member(request.backend.setting('LOGIN_FUNCTION')) return do_complete(request.backend, do_login, request.user, redirect_name='next', *args, **kwargs) @view_config(route_name='social.disconnect', request_method=('POST',)) @view_config(route_name='social.disconnect_association', request_method=('POST',)) @psa() @login_required def disconnect(request): return do_disconnect(request.backend, request.user, request.matchdict.get('association_id'), redirect_name='next')
from pyramid.view import view_config from social.utils import module_member from social.actions import do_auth, do_complete, do_disconnect from social.apps.pyramid_app.utils import psa, login_required @view_config(route_name='social.auth', request_method='GET') @psa('social.complete') def auth(request): return do_auth(request.backend, redirect_name='next') @view_config(route_name='social.complete', request_method=('GET', 'POST')) @psa('social.complete') def complete(request, *args, **kwargs): do_login = module_member(request.backend.setting('LOGIN_FUNCTION')) return do_complete(request.backend, do_login, request.user, redirect_name='next', *args, **kwargs) @view_config(route_name='social.disconnect', request_method=('POST',)) @view_config(route_name='social.disconnect_association', request_method=('POST',)) @psa() @login_required def disconnect(request): return do_disconnect(request.backend, request.user, request.matchdict.get('association_id'), redirect_name='next')
Add missing key in Homepage quicklinks
import React from 'react'; import './HomePage.css'; import {connect} from 'react-redux'; import logo from './svg/manny_wave.svg'; import {getQuicklinks} from './selectors'; import Card from './components/Card'; const HomePage = ({quickLinks}) => ( <main className="MannequinHome"> <div className="branding"> <img src={logo} alt="Mannequin" className="logo" /> <h1>Mannequin <small>Pattern Library</small></h1> </div> {quickLinks.length > 0 && <div className="quicklinks grid-container"> <h4>Quick Links</h4> <div className="CardGrid"> {quickLinks.map(pattern => ( <Card key={pattern.id} title={pattern.name} subtitle={pattern.tags['category']} to={`pattern/${pattern.id}`} /> ))} </div> </div> } </main> ) const mapStateToProps = (state) => { return { quickLinks: getQuicklinks(state) } } export default connect(mapStateToProps)(HomePage)
import React from 'react'; import './HomePage.css'; import {connect} from 'react-redux'; import logo from './svg/manny_wave.svg'; import {getQuicklinks} from './selectors'; import Card from './components/Card'; const HomePage = ({quickLinks}) => ( <main className="MannequinHome"> <div className="branding"> <img src={logo} alt="Mannequin" className="logo" /> <h1>Mannequin <small>Pattern Library</small></h1> </div> {quickLinks.length > 0 && <div className="quicklinks grid-container"> <h4>Quick Links</h4> <div className="CardGrid"> {quickLinks.map(pattern => ( <Card title={pattern.name} subtitle={pattern.tags['category']} to={`pattern/${pattern.id}`} /> ))} </div> </div> } </main> ) const mapStateToProps = (state) => { return { quickLinks: getQuicklinks(state) } } export default connect(mapStateToProps)(HomePage)
Make GUI Factory class static
package de.errorcraftlp.cryingobsidian.config; import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import de.errorcraftlp.cryingobsidian.CryingObsidian; public class ConfigGUI { public static class Factory implements IModGuiFactory { @Override public void initialize(Minecraft mc) {} @Override public Class<? extends GuiScreen> mainConfigGuiClass() { return GUI.class; } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } @Override public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { return null; } } public class GUI extends GuiConfig { public GUI(GuiScreen gui) { super(gui, new ConfigElement(CryingObsidian.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), CryingObsidian.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath(CryingObsidian.configuration.toString())); } } }
package de.errorcraftlp.cryingobsidian.config; import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import de.errorcraftlp.cryingobsidian.CryingObsidian; public class ConfigGUI { public class Factory implements IModGuiFactory { @Override public void initialize(Minecraft mc) {} @Override public Class<? extends GuiScreen> mainConfigGuiClass() { return GUI.class; } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } @Override public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { return null; } } public class GUI extends GuiConfig { public GUI(GuiScreen gui) { super(gui, new ConfigElement(CryingObsidian.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), CryingObsidian.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath(CryingObsidian.configuration.toString())); } } }
Use 'index' as the default page alias for lookups
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('index') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data
from pyramid.view import view_config from pyramid.httpexceptions import ( HTTPNotFound, ) @view_config(route_name='page', renderer='templates/page.mako') @view_config(route_name='page_view', renderer='templates/page.mako') def page_view(request): if 'page_id' in request.matchdict: data = request.kimochi.page(request.matchdict['page_id']) else: data = request.kimochi.page('1') return data @view_config(route_name='gallery_view', renderer='templates/gallery.mako') def gallery_view(request): data = request.kimochi.gallery(request.matchdict['gallery_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data @view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako') def gallery_image_view(request): data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id']) if 'gallery' not in data or not data['gallery']: raise HTTPNotFound return data
Use PHP_ENV for stage on app side. Signed-off-by: Daniel (dmilith) Dettlaff <0df25c85cef740557ee7be110d93fbdb7c899ad6@verknowsys.com>
<?php try { $curr_dir = getcwd(); # copy app root dir to var chdir(getcwd() . "/../../"); # NOTE: from global definitions: databaseName = serviceName + "_" + stage; $serviceName = basename(getcwd()); # gather name of directory which is also service name chdir($curr_dir); # go back to app root dir $stage = getenv("PHP_ENV"); echo "Connecting to: mysql:socket=localhost:~/SoftwareData/Mysql/service.sock;dbname=".$serviceName."_".$stage."<br/>"; $dbh = new PDO('mysql:socket=localhost:~/SoftwareData/Mysql/service.sock;dbname='.$serviceName."_".$stage, '', '' ); $stmt = $dbh->prepare('select * from test1'); # test1 is a testing database created by init.sql file $stmt->execute(); $results = $stmt->fetchAll(); var_dump($results); } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } ?>
<?php try { $curr_dir = getcwd(); # copy app root dir to var chdir(getcwd() . "/../../"); # NOTE: from global definitions: databaseName = serviceName + "_" + stage; $serviceName = basename(getcwd()); # gather name of directory which is also service name chdir($curr_dir); # go back to app root dir $stage = "staging"; echo "Connecting to: mysql:socket=localhost:~/SoftwareData/Mysql/service.sock;dbname=".$serviceName."_".$stage."<br/>"; $dbh = new PDO('mysql:socket=localhost:~/SoftwareData/Mysql/service.sock;dbname='.$serviceName."_".$stage, '', '' ); $stmt = $dbh->prepare('select * from test1'); # test1 is a testing database created by init.sql file $stmt->execute(); $results = $stmt->fetchAll(); var_dump($results); } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } ?>
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
#!/usr/bin/env python '''Implementation of a simple hash table. The table has `hash`, `get` and `set` methods. The hash function uses a very basic hash algorithm to insert the value into the table. ''' class HashItem(object): def __init__(self, key, value): self.key = key self.value = value class Hash(object): def __init__(self, size=1024): self.table = [] for i in range(size): self.table.append(list()) def hash(self, key): hash_value = 0 for i in key: hash_value += ord(key) return hash_value % len(self.table) def get(self, key): hashed_key = self.hash(key) for k in self.table[hashed_key]: if k[0] == key: return k[1] else: raise KeyError('Value not found') def set(self, key, val): hashed_key = self.hash(key) self.table[hashed_key].append((key, val))
#!/usr/bin/env python '''Implementation of a simple hash table. The table has `hash`, `get` and `set` methods. The hash function uses a very basic hash algorithm to insert the value into the table. ''' class HashItem(object): def __init__(self, key, value): self.key = key self.value = value class Hash(object): def __init__(self, size=1024): self.table = [] for i in range(size): self.table.append(list()) def hash(self, key): hash_value = 0 for i in key: hash_value += ord(key) return hash_value % len(self.table) def get(self, key): hashed_key = self.hash(key) for k in self.table[hashed_key]: if k[0] == key: return k[1] else: raise KeyError('Value not found') def set(self): pass
Use space to make file marker match more specific
;(function() { // CommonJS typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; function Brush() { this.regexList = [ { regex: /^\+\+\+ .*$/gm, css: 'color2' }, // new file { regex: /^\-\-\- .*$/gm, css: 'color2' }, // old file { regex: /^\s.*$/gm, css: 'color1' }, { regex: /^@@.*@@.*$/gm, css: 'variable' }, // location { regex: /^\+[^\+]{1}.*$/gm, css: 'string' }, { regex: /^\-[^\-]{1}.*$/gm, css: 'comments' } ]; }; Brush.prototype = new SyntaxHighlighter.Highlighter(); Brush.aliases = ['diff', 'patch']; SyntaxHighlighter.brushes.Diff = Brush; // CommonJS typeof(exports) != 'undefined' ? exports.Brush = Brush : null; })();
;(function() { // CommonJS typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null; function Brush() { this.regexList = [ { regex: /^\+\+\+.*$/gm, css: 'color2' }, { regex: /^\-\-\-.*$/gm, css: 'color2' }, { regex: /^\s.*$/gm, css: 'color1' }, { regex: /^@@.*@@.*$/gm, css: 'variable' }, // location { regex: /^\+[^\+]{1}.*$/gm, css: 'string' }, { regex: /^\-[^\-]{1}.*$/gm, css: 'comments' } ]; }; Brush.prototype = new SyntaxHighlighter.Highlighter(); Brush.aliases = ['diff', 'patch']; SyntaxHighlighter.brushes.Diff = Brush; // CommonJS typeof(exports) != 'undefined' ? exports.Brush = Brush : null; })();
Add new contact on form submitted
window.ContactManager = { Models: {}, Collections: {}, Views: {}, start: function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(); router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); }); router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); }); router.on('route:newContact', function() { var newContactForm = new ContactManager.Views.ContactForm(); newContactForm.on('form:submitted', function(attrs) { attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1); contacts.add(attrs); router.navigate('contacts', true); }); $('.main-container').html(newContactForm.render().$el); }); router.on('route:editContact', function(id) { console.log('Edit contact'); }); Backbone.history.start(); } };
window.ContactManager = { Models: {}, Collections: {}, Views: {}, start: function(data) { var contacts = new ContactManager.Collections.Contacts(data.contacts), router = new ContactManager.Router(); router.on('route:home', function() { router.navigate('contacts', { trigger: true, replace: true }); }); router.on('route:showContacts', function() { var contactsView = new ContactManager.Views.Contacts({ collection: contacts }); $('.main-container').html(contactsView.render().$el); }); router.on('route:newContact', function() { var newContactForm = new ContactManager.Views.ContactForm(); $('.main-container').html(newContactForm.render().$el); }); router.on('route:editContact', function(id) { console.log('Edit contact'); }); Backbone.history.start(); } };
Revert string -> integer change for statsd port Turns out they want a string...
""" bux_grader_framework ~~~~~~~~~~~~~~~~~~~~ A framework for bootstraping of external graders for your edX course. :copyright: 2014 Boston University :license: GNU Affero General Public License """ __version__ = '0.4.3' DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s - %(message)s' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, }, } import os os.environ['STATSD_HOST'] = os.environ.get('STATSD_HOST', '127.0.0.1') os.environ['STATSD_PORT'] = os.environ.get('STATSD_PORT', '8125') from .conf import Config from .evaluators import registered_evaluators, BaseEvaluator from .grader import Grader from .workers import EvaluatorWorker, XQueueWorker from .xqueue import XQueueClient
""" bux_grader_framework ~~~~~~~~~~~~~~~~~~~~ A framework for bootstraping of external graders for your edX course. :copyright: 2014 Boston University :license: GNU Affero General Public License """ __version__ = '0.4.3' DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s - %(message)s' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, }, } import os os.environ['STATSD_HOST'] = os.environ.get('STATSD_HOST', '127.0.0.1') os.environ['STATSD_PORT'] = os.environ.get('STATSD_PORT', 8125) from .conf import Config from .evaluators import registered_evaluators, BaseEvaluator from .grader import Grader from .workers import EvaluatorWorker, XQueueWorker from .xqueue import XQueueClient
Add more tests for GeneralObject * wqflask/tests/base/test_general_object.py: test object's magic methods
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1)
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n")
Fix CS errors. Damn you jippi
<?php App::uses('DebugPanel', 'DebugKit.Lib'); /** * Crud debug panel in DebugKit * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Christian Winther, 2013 */ class CrudPanel extends DebugPanel { /** * Declare we are a plugin * * @var string */ public $plugin = 'Crud'; /** * beforeRender callback * * @param Controller $controller * @return void */ public function beforeRender(Controller $controller) { if ($controller->Crud->isActionMapped()) { $Action = $controller->Crud->action(); $controller->set('CRUD_action_config', $Action->config()); } $listenerConfig = array(); foreach ($controller->Crud->config('listeners') as $listener => $value) { $listenerConfig[$listener] = $controller->Crud->listener($listener)->config(); } $controller->set('CRUD_config', $controller->Crud->config()); $controller->set('CRUD_listener_config', $listenerConfig); } }
<?php App::uses ('DebugPanel', 'DebugKit.Lib'); /** * Crud debug panel in DebugKit * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Christian Winther, 2013 */ class CrudPanel extends DebugPanel { /** * Declare we are a plugin * * @var string */ public $plugin = 'Crud'; /** * beforeRender callback * * @param Controller $controller * @return void */ public function beforeRender(Controller $controller) { if ($controller->Crud->isActionMapped()) { $Action = $controller->Crud->action(); $controller->set('CRUD_action_config', $Action->config()); } $listener_config = array(); foreach ($controller->Crud->config('listeners') as $listener => $value) { $listener_config[$listener] = $controller->Crud->listener($listener)->config(); } $controller->set('CRUD_config', $controller->Crud->config()); $controller->set('CRUD_listener_config', $listener_config); } }
Fix another missed linting issue
package cmd import ( "fmt" "os" "runtime" "github.com/exercism/cli/api" "github.com/spf13/cobra" ) // BinaryName is the name of the app. // By default this is exercism, but people // are free to name this however they want. // The usage examples and help strings should reflect // the actual name of the binary. var BinaryName string // RootCmd represents the base command when called without any subcommands. var RootCmd = &cobra.Command{ Use: BinaryName, Short: "A friendly command-line interface to Exercism.", Long: `A command-line interface for https://v2.exercism.io. Download exercises and submit your solutions.`, } // Execute adds all child commands to the root command. func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { BinaryName = os.Args[0] api.UserAgent = fmt.Sprintf("github.com/exercism/cli v%s (%s/%s)", Version, runtime.GOOS, runtime.GOARCH) }
package cmd import ( "fmt" "os" "runtime" "github.com/exercism/cli/api" "github.com/spf13/cobra" ) var BinaryName string // RootCmd represents the base command when called without any subcommands. var RootCmd = &cobra.Command{ Use: BinaryName, Short: "A friendly command-line interface to Exercism.", Long: `A command-line interface for https://v2.exercism.io. Download exercises and submit your solutions.`, } // Execute adds all child commands to the root command. func Execute() { if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { BinaryName = os.Args[0] api.UserAgent = fmt.Sprintf("github.com/exercism/cli v%s (%s/%s)", Version, runtime.GOOS, runtime.GOARCH) }
Handle floating issue numbers better (.5 and .1 issues)
#!/usr/bin/python import os import sys import re from collections import defaultdict COMIC_RE = re.compile(r'^\d+ +([^#]+)#([\d.]+)') def lines(todofile): with open(todofile) as todolines: for line in todolines: title_match = COMIC_RE.match(line) if title_match: # (title, issue) yield line.strip(), title_match.group(1), title_match.group(2) def issues(todofile): seen = defaultdict(int) for line, title, issue in lines(todofile): if issue and issue != '0': if seen[title]: delta = abs(float(issue) - float(seen[title])) if delta == 0 or delta > 1: yield line, seen[title] seen[title] = issue def main(files): for todofile in files: for issue, lastissue in issues(todofile): print "%s (last seen %s)" % (issue, lastissue) if __name__ == '__main__': main(sys.argv[1:])
#!/usr/bin/python import os import sys import re from collections import defaultdict COMIC_RE = re.compile(r'^\d+ +([^#]+)#(\d+)') def lines(todofile): with open(todofile) as todolines: for line in todolines: title_match = COMIC_RE.match(line) if title_match: # (title, issue) yield line.strip(), title_match.group(1), int(title_match.group(2)) def issues(todofile): seen = defaultdict(int) for line, title, issue in lines(todofile): if issue and seen[title] and abs(issue - seen[title]) > 1: yield line, seen[title] seen[title] = issue def main(files): for todofile in files: for issue, lastissue in issues(todofile): print "%s (last seen %d)" % (issue, lastissue) if __name__ == '__main__': main(sys.argv[1:])
[TASK] Return hash with contract metadata
var Token = require('../models/token').model; var Bitcoin = require('../lib/bitcoin'); var config = require('../lib/config'); module.exports = function(manager, req, res, next) { var token = req.params.token; if (!token) { res.status(400).json({ message: "Must supply contract token to retrieve metadata" }); return; } new Token({token: token}).fetch({ withRelated: ['balance', 'contract'] }).then(function (model) { if (!model) { res.status(404).json({ message: "Token not found" }); return; } else { manager.checkTokenBalance(token).then(function(balance){ res.status(200).json({ token: token, hash: model.related('contract').get('hash'), compute_units: balance, bitcoin_address: Bitcoin.generateDeterministicWallet(model.related('balance').id), compute_units_per_bitcoin: config.get('compute_units_per_bitcoin') }); }); } }); };
var Token = require('../models/token').model; var Bitcoin = require('../lib/bitcoin'); var config = require('../lib/config'); module.exports = function(manager, req, res, next) { var token = req.params.token; if (!token) { res.status(400).json({ message: "Must supply contract token to retrieve metadata" }); return; } new Token({token: token}).fetch({ withRelated: ['balance'] }).then(function (model) { if (!model) { res.status(404).json({ message: "Token not found" }); return; } else { manager.checkTokenBalance(token).then(function(balance){ res.status(200).json({ token: token, compute_units: balance, bitcoin_address: Bitcoin.generateDeterministicWallet(model.related('balance').id), compute_units_per_bitcoin: config.get('compute_units_per_bitcoin') }); }); } }); };
Add context.stop() and the end of the class.
package spark.elastic; import static org.elasticsearch.spark.rdd.api.java.JavaEsSpark.esRDD; import java.util.Map; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; public class ReadingFromES { private static final String es_nodes = "localhost"; private static final String es_port = "9200"; private static final String index = "spark"; private static final String mapping = "json"; public static void main(String[] args) { // Create Spark configuration SparkConf conf = new SparkConf(); conf.setAppName("ReadingFromES"); conf.setMaster("local[2]"); conf.set("es.nodes", es_nodes); conf.set("es.port", es_port); JavaSparkContext context = new JavaSparkContext(conf); // Keys: fieldName, values: fieldValue JavaRDD<Map<String, Object>> javaRDD = esRDD(context, index + "/" + mapping).values(); javaRDD.foreach(rdd -> System.out.println(rdd.values())); context.stop(); } }
package spark.elastic; import static org.elasticsearch.spark.rdd.api.java.JavaEsSpark.esRDD; import java.util.Map; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; public class ReadingFromES { private static final String es_nodes = "localhost"; private static final String es_port = "9200"; private static final String index = "spark"; private static final String mapping = "json"; public static void main(String[] args) { // Create Spark configuration SparkConf conf = new SparkConf(); conf.setAppName("ReadingFromES"); conf.setMaster("local[2]"); conf.set("es.nodes", es_nodes); conf.set("es.port", es_port); JavaSparkContext context = new JavaSparkContext(conf); // Keys: fieldName, values: fieldValue JavaRDD<Map<String, Object>> javaRDD = esRDD(context, index + "/" + mapping).values(); javaRDD.foreach(rdd -> System.out.println(rdd.values())); } }
Update ServiceProvider & build tools
<?php namespace Onderdelen\Client; use Illuminate\Support\ServiceProvider; class ClientServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
<?php namespace Client; use Illuminate\Support\ServiceProvider; class ClientServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
Update Sami theme as default.
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('3.*') ->addFromTags('4.*'); return new Sami($iterator, array( 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ]);
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('3.*') ->addFromTags('4.*'); return new Sami($iterator, [ 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__.'/build/sami/%version%', 'cache_dir' => __DIR__.'/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ]);
Use deepmerge on loaded inventory items
import devtools from '../devtools'; import { REALLY_BIG_NUMBER } from '../utils'; import { load } from '../save'; import merge from 'deepmerge'; import PineCone from '../sprites/object/PineCone'; const itemMax = 500; const loadedItems = load('items') || {}; const defaultItems = { 'wood-axe': { value: true, rank: 0, sellable: false, }, bucket: { value: false, sellable: false, }, water: { value: 0, max: itemMax, sellable: false, }, log: { value: 0, max: itemMax, sellable: true, }, 'pine-cone': { value: 0, max: itemMax, sellable: false, }, }; let items = merge(defaultItems, loadedItems); items['pine-cone'].place = PineCone; let money = load('money') || 0; export { items, money };
import devtools from '../devtools'; import { REALLY_BIG_NUMBER } from '../utils'; import { load } from '../save'; import merge from 'deepmerge'; import PineCone from '../sprites/object/PineCone'; const itemMax = 500; const loadedItems = load('items') || {}; const defaultItems = { 'wood-axe': { value: true, rank: 0, sellable: false, }, bucket: { value: false, sellable: false, }, water: { value: 0, max: itemMax, sellable: false, }, log: { value: 0, max: itemMax, sellable: true, }, 'pine-cone': { value: 0, max: itemMax, sellable: false, }, }; let items = Object.assign(defaultItems, loadedItems); items['pine-cone'].place = PineCone; let money = load('money') || 0; export { items, money };
Set redis-py >= 2.9.0 requirement.
from setuptools import setup description = """ Full featured redis cache backend for Django. """ setup( name = "django-redis", url = "https://github.com/niwibe/django-redis", author = "Andrei Antoukh", author_email = "niwi@niwi.be", version='3.5.2', packages = [ "redis_cache", "redis_cache.client" ], description = description.strip(), install_requires=[ 'redis>=2.9.0', ], zip_safe=False, include_package_data = True, package_data = { '': ['*.html'], }, classifiers = [ "Development Status :: 5 - Production/Stable", "Operating System :: OS Independent", "Environment :: Web Environment", "Framework :: Django", "License :: OSI Approved :: BSD License", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Topic :: Software Development :: Libraries", "Topic :: Utilities", ], )
from setuptools import setup description = """ Full featured redis cache backend for Django. """ setup( name = "django-redis", url = "https://github.com/niwibe/django-redis", author = "Andrei Antoukh", author_email = "niwi@niwi.be", version='3.5.2', packages = [ "redis_cache", "redis_cache.client" ], description = description.strip(), install_requires=[ 'redis>=2.7.0', ], zip_safe=False, include_package_data = True, package_data = { '': ['*.html'], }, classifiers = [ "Development Status :: 5 - Production/Stable", "Operating System :: OS Independent", "Environment :: Web Environment", "Framework :: Django", "License :: OSI Approved :: BSD License", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Topic :: Software Development :: Libraries", "Topic :: Utilities", ], )
Update tests to leverage factory pattern
from flask.ext.testing import TestCase import unittest from app import create_app, db class BaseTestCase(TestCase): def create_app(self): return create_app('config.TestingConfiguration') def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all() def login(self, username, password): return self.client.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get('/logout', follow_redirects=True) if __name__ == '__main__': unittest.main()
from flask.ext.testing import TestCase import unittest from app import app, db class BaseTestCase(TestCase): def create_app(self): app.config.from_object('config.TestingConfiguration') return app def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all() def login(self, username, password): return self.client.post('/login', data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get('/logout', follow_redirects=True) if __name__ == '__main__': unittest.main()
Remove error return from Map; it's most likely not going to be used
package mapper import ( "git.aviuslabs.net/golang/async" "reflect" ) func Map(data interface{}, routine async.Routine, callbacks ...async.Done) { var ( routines []async.Routine results []interface{} ) d := reflect.ValueOf(data) for i := 0; i < d.Len(); i++ { v := d.Index(i).Interface() routines = append(routines, func(done async.Done, args ...interface{}) { done = func(original async.Done) async.Done { return func(err error, args ...interface{}) { results = append(results, args...) if i == d.Len() { original(err, results...) return } original(err, args...) } }(done) routine(done, v) }) } async.Waterfall(routines, callbacks...) }
package mapper import ( "git.aviuslabs.net/golang/async" "reflect" ) func Map(data interface{}, routine async.Routine, callbacks ...async.Done) error { var ( routines []async.Routine results []interface{} ) d := reflect.ValueOf(data) for i := 0; i < d.Len(); i++ { v := d.Index(i).Interface() routines = append(routines, func(done async.Done, args ...interface{}) { done = func(original async.Done) async.Done { return func(err error, args ...interface{}) { results = append(results, args...) if i == d.Len() { original(err, results...) return } original(err, args...) } }(done) routine(done, v) }) } async.Waterfall(routines, callbacks...) return nil }
Add isPrivate flag to user
import { USER_ROLES } from '../constants'; const { ADMIN_ROLE, MEMBER_ROLE } = USER_ROLES; export const hasPaidMail = ({ Subscribed }) => Subscribed & 1; export const hasPaidVpn = ({ Subscribed }) => Subscribed & 4; export const isPaid = ({ Subscribed }) => Subscribed; export const isPrivate = ({ Private }) => Private === 1; export const isFree = (user) => !isPaid(user); export const isAdmin = ({ Role }) => Role === ADMIN_ROLE; export const isMember = ({ Role }) => Role === MEMBER_ROLE; export const isSubUser = ({ OrganizationPrivateKey }) => typeof OrganizationPrivateKey !== 'undefined'; export const isDelinquent = ({ Delinquent }) => Delinquent; export const getInfo = (User) => { return { isAdmin: isAdmin(User), isMember: isMember(User), isFree: isFree(User), isPaid: isPaid(User), isPrivate: isPrivate(User), isSubUser: isSubUser(User), isDelinquent: isDelinquent(User), hasPaidMail: hasPaidMail(User), hasPaidVpn: hasPaidVpn(User) }; };
import { USER_ROLES } from '../constants'; const { ADMIN_ROLE, MEMBER_ROLE } = USER_ROLES; export const hasPaidMail = ({ Subscribed }) => Subscribed & 1; export const hasPaidVpn = ({ Subscribed }) => Subscribed & 4; export const isPaid = ({ Subscribed }) => Subscribed; export const isFree = (user) => !isPaid(user); export const isAdmin = ({ Role }) => Role === ADMIN_ROLE; export const isMember = ({ Role }) => Role === MEMBER_ROLE; export const isSubUser = ({ OrganizationPrivateKey }) => typeof OrganizationPrivateKey !== 'undefined'; export const isDelinquent = ({ Delinquent }) => Delinquent; export const getInfo = (User) => { return { isAdmin: isAdmin(User), isMember: isMember(User), isFree: isFree(User), isPaid: isPaid(User), isSubUser: isSubUser(User), isDelinquent: isDelinquent(User), hasPaidMail: hasPaidMail(User), hasPaidVpn: hasPaidVpn(User) }; };
Remove empty object from variables array
import {Hooks} from 'PluginSDK'; let EnvironmentVariables = { description: 'Set environment variables for each task your service launches in addition to those set by Mesos.', type: 'object', title: 'Environment Variables', properties: { variables: { type: 'array', duplicable: true, addLabel: 'Add Environment Variable', getter: function (service) { let variableMap = service.getEnvironmentVariables(); if (variableMap == null) { return []; } return Object.keys(variableMap).map(function (key) { return Hooks.applyFilter('variablesGetter', { key, value: variableMap[key] }, service); }); }, itemShape: { properties: { key: { title: 'Key', type: 'string' }, value: { title: 'Value', type: 'string' } } } } } }; module.exports = EnvironmentVariables;
import {Hooks} from 'PluginSDK'; let EnvironmentVariables = { description: 'Set environment variables for each task your service launches in addition to those set by Mesos.', type: 'object', title: 'Environment Variables', properties: { variables: { type: 'array', duplicable: true, addLabel: 'Add Environment Variable', getter: function (service) { let variableMap = service.getEnvironmentVariables(); if (variableMap == null) { return [{}]; } return Object.keys(variableMap).map(function (key) { return Hooks.applyFilter('variablesGetter', { key, value: variableMap[key] }, service); }); }, itemShape: { properties: { key: { title: 'Key', type: 'string' }, value: { title: 'Value', type: 'string' } } } } } }; module.exports = EnvironmentVariables;
Set getPageTimeout to 60 seconds
// Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/docs/referenceConf.js /*global jasmine */ var SpecReporter = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, getPageTimeout: 60000, specs: [ './e2e/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, useAllAngular2AppRoots: true, beforeLaunch: function() { require('ts-node').register({ project: 'e2e' }); }, onPrepare: function() { jasmine.getEnv().addReporter(new SpecReporter()); } };
// Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/docs/referenceConf.js /*global jasmine */ var SpecReporter = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './e2e/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, useAllAngular2AppRoots: true, beforeLaunch: function() { require('ts-node').register({ project: 'e2e' }); }, onPrepare: function() { jasmine.getEnv().addReporter(new SpecReporter()); } };
Add a hack to ensure mocha waits for page to load
if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { setTimeout(function (){ describe('The Route "/"', function () { it('Should have the title "Map"', function () { var title = document.title console.log(title) chai.assert.include(title, 'Map') }) }) describe('A list of places', function () { it('Should have a main section with the class map', function () { var map = $('main.map') chai.assert.ok(map.length > 0) }) it('Should contain map__places', function () { var placesList = $('main.map ul.map__places') chai.assert.ok(placesList.length > 0) }) it('should at least contain one place', function () { var places = $('ul.map__places li.place') chai.assert.ok(places.length > 0) }) }) describe('A place', function () { it('Should include a location', function () { var title = $('li.place .place__location').text() chai.assert.ok(title.length > 0) }) }) }, 1000) }) }
if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { describe('The Route "/"', function () { it('Should have the title "map"', function () { var title = document.title console.log(title) chai.assert.include(title, 'Map') }) }) describe('A list of places', function () { it('Should have a main section with the class map', function () { var map = $('main.map') chai.assert.ok(map.length > 0) }) it('Should contain map__places', function () { var placesList = $('main.map ul.map__places') chai.assert.ok(placesList.length > 0) }) it('should at least contain one place', function () { var places = $('ul.map__places li.place') chai.assert.ok(places.length > 0) }) }) describe('A place', function () { it('Should include a title', function () { var title = $('li.place .place__title').text() console.log(title) chai.assert.ok(title.length > 0) }) }) }) }
Use single quotes instead of double quotes
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_identify_repo ------------------ """ import pytest from cookiecutter import exceptions, vcs def test_identify_git_github(): repo_url = 'https://github.com/audreyr/cookiecutter-pypackage.git' assert vcs.identify_repo(repo_url) == 'git' def test_identify_git_github_no_extension(): repo_url = 'https://github.com/audreyr/cookiecutter-pypackage' assert vcs.identify_repo(repo_url) == 'git' def test_identify_git_gitorious(): repo_url = ( 'git@gitorious.org:cookiecutter-gitorious/cookiecutter-gitorious.git' ) assert vcs.identify_repo(repo_url) == 'git' def test_identify_hg_mercurial(): repo_url = 'https://audreyr@bitbucket.org/audreyr/cookiecutter-bitbucket' assert vcs.identify_repo(repo_url) == 'hg' def test_unknown_repo_type(): repo_url = 'http://norepotypespecified.com' with pytest.raises(exceptions.UnknownRepoType): vcs.identify_repo(repo_url)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_identify_repo ------------------ """ import pytest from cookiecutter import exceptions, vcs def test_identify_git_github(): repo_url = "https://github.com/audreyr/cookiecutter-pypackage.git" assert vcs.identify_repo(repo_url) == "git" def test_identify_git_github_no_extension(): repo_url = "https://github.com/audreyr/cookiecutter-pypackage" assert vcs.identify_repo(repo_url) == "git" def test_identify_git_gitorious(): repo_url = ( "git@gitorious.org:cookiecutter-gitorious/cookiecutter-gitorious.git" ) assert vcs.identify_repo(repo_url) == "git" def test_identify_hg_mercurial(): repo_url = "https://audreyr@bitbucket.org/audreyr/cookiecutter-bitbucket" assert vcs.identify_repo(repo_url) == "hg" def test_unknown_repo_type(): repo_url = "http://norepotypespecified.com" with pytest.raises(exceptions.UnknownRepoType): vcs.identify_repo(repo_url)
Remove implicit import of symbols Currently, using libclient for python requires selecting the target node type (MN or CN) and the target DataONE API version, by specifying the appropriate client, so it better to use the library by explicitly importing only the needed clients instead of all of of them.
#!/usr/bin/env python # -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2012 DataONE # # 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. __version__ = "2.0.dev8" # __all__ = [ # 'cnclient', # 'cnclient_1_1', # 'd1baseclient', # 'd1baseclient_1_1', # 'd1baseclient_2_0', # 'd1client', # 'data_package', # 'logrecorditerator', # 'mnclient', # 'mnclient_1_1', # 'object_format_info', # 'objectlistiterator', # 'solr_client', # 'svnrevision', # 'systemmetadata', # ]
#!/usr/bin/env python # -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2012 DataONE # # 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. __version__ = "2.0.dev8" __all__ = [ 'cnclient', 'cnclient_1_1', 'd1baseclient', 'd1baseclient_1_1', 'd1baseclient_2_0', 'd1client', 'data_package', 'logrecorditerator', 'mnclient', 'mnclient_1_1', 'object_format_info', 'objectlistiterator', 'solr_client', 'svnrevision', 'systemmetadata', ]
Raise Kotlin compiler time limit to 20s
import os.path from dmoj.executors.java_executor import JavaExecutor with open(os.path.join(os.path.dirname(__file__), 'java-security.policy')) as policy_file: policy = policy_file.read() class Executor(JavaExecutor): name = 'KOTLIN' ext = '.kt' compiler = 'kotlinc' compiler_time_limit = 20 vm = 'kotlin_vm' security_policy = policy test_program = '''\ fun main(args: Array<String>) { println(readLine()) } ''' def create_files(self, problem_id, source_code, *args, **kwargs): super(Executor, self).create_files(problem_id, source_code, *args, **kwargs) self._jar_name = '%s.jar' % problem_id def get_cmdline(self): res = super(Executor, self).get_cmdline() res[-2:] = ['-jar', self._jar_name] return res def get_compile_args(self): return [self.get_compiler(), '-include-runtime', '-d', self._jar_name, self._code] @classmethod def get_versionable_commands(cls): return [('kotlinc', cls.get_compiler()), ('java', cls.get_vm())]
import os.path from dmoj.executors.java_executor import JavaExecutor with open(os.path.join(os.path.dirname(__file__), 'java-security.policy')) as policy_file: policy = policy_file.read() class Executor(JavaExecutor): name = 'KOTLIN' ext = '.kt' compiler = 'kotlinc' vm = 'kotlin_vm' security_policy = policy test_program = '''\ fun main(args: Array<String>) { println(readLine()) } ''' def create_files(self, problem_id, source_code, *args, **kwargs): super(Executor, self).create_files(problem_id, source_code, *args, **kwargs) self._jar_name = '%s.jar' % problem_id def get_cmdline(self): res = super(Executor, self).get_cmdline() res[-2:] = ['-jar', self._jar_name] return res def get_compile_args(self): return [self.get_compiler(), '-include-runtime', '-d', self._jar_name, self._code] @classmethod def get_versionable_commands(cls): return [('kotlinc', cls.get_compiler()), ('java', cls.get_vm())]
Add URL in package info
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-api', version='0.1.2', packages=['django_api'], url='https://github.com/bipsandbytes/django-api', include_package_data=True, license='BSD License', description='Specify and validate your Django APIs', long_description=README, author='Bipin Suresh', author_email='bipins@alumni.stanford.edu', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-api', version='0.1.2', packages=['django_api'], include_package_data=True, license='BSD License', description='Specify and validate your Django APIs', long_description=README, author='Bipin Suresh', author_email='bipins@alumni.stanford.edu', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
[webapp] Update crossOriginWhitelist properly when using config.js
import ENV from 'webapp/config/environment'; import Ember from 'ember'; export default { name: 'api-server-setup', before: ['oauth2-w-auth'], initialize: function() { if (!Ember.isEmpty(window.SHELVES_API_SERVER)) { ENV.APP.API_SERVER = window.SHELVES_API_SERVER; ENV.APP.API_BASE = window.SHELVES_API_BASE; ENV.APP.API_NAMESPACE = ENV.APP.API_BASE + window.SHELVES_API_NAMESPACE; ENV['simple-auth'].crossOriginWhitelist = [ENV.APP.API_SERVER]; ENV['simple-auth-oauth2'].serverTokenEndpoint = ENV.APP.API_SERVER + (ENV.APP.API_BASE ? '/' + ENV.APP.API_BASE : '') + '/oauth/token'; } } };
import ENV from 'webapp/config/environment'; import Ember from 'ember'; export default { name: 'api-server-setup', before: ['oauth2-w-auth'], initialize: function() { if (!Ember.isEmpty(window.SHELVES_API_SERVER)) { ENV.APP.API_SERVER = window.SHELVES_API_SERVER; ENV.APP.API_BASE = window.SHELVES_API_BASE; ENV.APP.API_NAMESPACE = ENV.APP.API_BASE + window.SHELVES_API_NAMESPACE; ENV['simple-auth-oauth2'].serverTokenEndpoint = ENV.APP.API_SERVER + (ENV.APP.API_BASE ? '/' + ENV.APP.API_BASE : '') + '/oauth/token'; } } };
Remove debug outputs for ssr
const SSR = require('vue-server-renderer'); const fs = require('fs'); const express = require('express'); const path = require('path'); const renderer = SSR.createBundleRenderer(fs.readFileSync('./ssrres/static/js/app.js', 'utf-8')); const index = fs.readFileSync('./ssrres/index.html', 'utf-8'); const parts = index.split(/\<div\ id\=.*\<\/div\>/); const server = express(); server.use(express.static(path.resolve(__dirname, '../ssrres'), { index: false, })); server.get('*', (req, res) => { const stream = renderer.renderToStream({ url: req.url }); res.write(parts[0]); stream.pipe(res).on('end', () => { res.write(parts[1]); }); }); const config = require('../config'); server.listen(config.ssr.port, () => { console.log(`Server up at ${config.ssr.port}`); });
const SSR = require('vue-server-renderer'); const fs = require('fs'); const express = require('express'); const path = require('path'); const renderer = SSR.createBundleRenderer(fs.readFileSync('./ssrres/static/js/app.js', 'utf-8')); const index = fs.readFileSync('./ssrres/index.html', 'utf-8'); const parts = index.split(/\<div\ id\=.*\<\/div\>/); const server = express(); server.use(express.static(path.resolve(__dirname, '../ssrres'), { index: false, })); server.get('*', (req, res) => { renderer.renderToString({ url: req.url }, (err, html) => { if(err) console.log(err); console.log(html); }); const stream = renderer.renderToStream({ url: req.url }); res.write(parts[0]); stream.pipe(res).on('end', () => { console.log("END"); }); }); const config = require('../config'); server.listen(config.ssr.port, () => { console.log(`Server up at ${config.ssr.port}`); });
Update count of things in DB
import os import sys import unittest import tempfile sys.path.insert(0, os.environ.get('BLOG_PATH')) from blog.blog import * class BlogUnitTestCase(unittest.TestCase): def test_connect_db(self): db = connect_db() assert isinstance(db, sqlite3.Connection) def test_get_db(self): self.db, app.config['DATABASE'] = tempfile.mkstemp() app.config['TESTING'] = True self.app = app.test_client() with app.app_context(): db = get_db() assert isinstance(db, sqlite3.Connection) def schema(): return db.execute("SELECT * FROM sqlite_master").fetchall() assert len(schema()) == 0 init = migrate_db() assert len(schema()) == 21 if __name__ == '__main__': unittest.main()
import os import sys import unittest import tempfile sys.path.insert(0, os.environ.get('BLOG_PATH')) from blog.blog import * class BlogUnitTestCase(unittest.TestCase): def test_connect_db(self): db = connect_db() assert isinstance(db, sqlite3.Connection) def test_get_db(self): self.db, app.config['DATABASE'] = tempfile.mkstemp() app.config['TESTING'] = True self.app = app.test_client() with app.app_context(): db = get_db() assert isinstance(db, sqlite3.Connection) def schema(): return db.execute("SELECT * FROM sqlite_master").fetchall() assert len(schema()) == 0 init = migrate_db() assert len(schema()) == 11 if __name__ == '__main__': unittest.main()
Add test for index route
import unittest from flask import json from api import db from api.BucketListAPI import app from instance.config import application_config class AuthenticationTestCase(unittest.TestCase): def setUp(self): app.config.from_object(application_config['TestingEnv']) self.client = app.test_client() # Binds the app to current context with app.app_context(): # Create all tables db.create_all() def test_index_route(self): response = self.client.get('/') self.assertEqual(response.status_code, 201) self.assertIn('Welcome Message', response.data.decode()) def tearDown(self): # Drop all tables with app.app_context(): # Drop all tables db.session.remove() db.drop_all() if __name__ == '__main__': unittest.main()
import unittest from flask import json from api import create_app, db class AuthenticationTestCase(unittest.TestCase): def setUp(self): self.app = create_app(config_name='TestingEnv') self.client = self.app.test_client() # Binds the app to current context with self.app.app_context(): # Create all tables db.create_all() def tearDown(self): # Drop all tables with self.app.app_context(): # Drop all tables db.session.remove() db.drop_all() def test_something(self): self.assertTrue(1) if __name__ == '__main__': unittest.main()
Add a formal doc for an overridden method.
/* * Copyright (c) 2000-2018 TeamDev Ltd. All rights reserved. * TeamDev PROPRIETARY and CONFIDENTIAL. * Use is subject to license terms. */ package io.spine.web.firebase; import io.spine.web.QueryProcessingResult; import javax.servlet.ServletResponse; import java.io.IOException; /** * A result of a query processed by a {@link FirebaseQueryBridge}. * * <p>This result represents a database path to the requested data. * See {@link FirebaseQueryBridge} for more details. * * @author Dmytro Dashenkov */ final class FirebaseQueryProcessingResult implements QueryProcessingResult { private static final String MIME_TYPE = "text/plain"; private final FirebaseDatabasePath path; FirebaseQueryProcessingResult(FirebaseDatabasePath path) { this.path = path; } /** * {@inheritDoc} */ @Override public void writeTo(ServletResponse response) throws IOException { final String databaseUrl = path.toString(); response.getWriter().append(databaseUrl); response.setContentType(MIME_TYPE); } @Override public String toString() { return path.toString(); } }
/* * Copyright (c) 2000-2018 TeamDev Ltd. All rights reserved. * TeamDev PROPRIETARY and CONFIDENTIAL. * Use is subject to license terms. */ package io.spine.web.firebase; import io.spine.web.QueryProcessingResult; import javax.servlet.ServletResponse; import java.io.IOException; /** * A result of a query processed by a {@link FirebaseQueryBridge}. * * <p>This result represents a database path to the requested data. * See {@link FirebaseQueryBridge} for more details. * * @author Dmytro Dashenkov */ final class FirebaseQueryProcessingResult implements QueryProcessingResult { private static final String MIME_TYPE = "text/plain"; private final FirebaseDatabasePath path; FirebaseQueryProcessingResult(FirebaseDatabasePath path) { this.path = path; } @Override public void writeTo(ServletResponse response) throws IOException { final String databaseUrl = path.toString(); response.getWriter().append(databaseUrl); response.setContentType(MIME_TYPE); } @Override public String toString() { return path.toString(); } }
Support 4X releases of libicu
var funcs = require('./funcs.js') module.exports = function (dist, release) { var contents = funcs.replace(header, {dist: dist, release: release}) + '\n\n' + funcs.replace(pkgs, {pkgs: funcs.generatePkgStr(commonPkgs)}) return contents } var header = 'FROM {{DIST}}:{{RELEASE}}\n' + 'MAINTAINER William Blankenship <wblankenship@nodesource.com>' var pkgs = 'RUN apt-get update \\\n' + ' && apt-get install -y --force-yes --no-install-recommends\\\n' + '{{PKGS}}' + ' && rm -rf /var/lib/apt/lists/*;' var commonPkgs = [ 'apt-transport-https', 'ssh-client', 'build-essential', 'curl', 'ca-certificates', 'git', 'libicu-dev', '\'libicu[0-9][0-9].*\'', 'lsb-release', 'python-all', 'rlwrap']
var funcs = require('./funcs.js') module.exports = function (dist, release) { var contents = funcs.replace(header, {dist: dist, release: release}) + '\n\n' + funcs.replace(pkgs, {pkgs: funcs.generatePkgStr(commonPkgs)}) return contents } var header = 'FROM {{DIST}}:{{RELEASE}}\n' + 'MAINTAINER William Blankenship <wblankenship@nodesource.com>' var pkgs = 'RUN apt-get update \\\n' + ' && apt-get install -y --force-yes --no-install-recommends\\\n' + '{{PKGS}}' + ' && rm -rf /var/lib/apt/lists/*;' var commonPkgs = [ 'apt-transport-https', 'ssh-client', 'build-essential', 'curl', 'ca-certificates', 'git', 'libicu-dev', '\'libicu5-*\'', 'lsb-release', 'python-all', 'rlwrap']
Fix few code to match the doc
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; FriendlyEats.prototype.addRestaurant = function(data) { /* TODO: Implement adding a document */ }; FriendlyEats.prototype.getAllRestaurants = function(renderer) { /* TODO: Retrieve list of restaurants */ }; FriendlyEats.prototype.getDocumentsInQuery = function(query, renderer) { /* TODO: Render all documents in the provided query */ }; FriendlyEats.prototype.getRestaurant = function(id) { /* TODO: Retrieve a single restaurant */ }; FriendlyEats.prototype.getFilteredRestaurants = function(filters, render) { /* TODO: Retrieve filtered list of restaurants */ }; FriendlyEats.prototype.addRating = function(restaurantID, rating) { /* TODO: Retrieve add a rating to a restaurant */ };
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; FriendlyEats.prototype.addRestaurant = function(data) { /* TODO: Implement adding a document */ }; FriendlyEats.prototype.getAllRestaurants = function(render) { /* TODO: Retrieve list of restaurants */ }; FriendlyEats.prototype.getDocumentsInQuery = function(query, render) { /* TODO: Render all documents in the provided query */ }; FriendlyEats.prototype.getRestaurant = function(id) { /* TODO: Retrieve a single restaurant */ }; FriendlyEats.prototype.getFilteredRestaurants = function(filters, render) { /* TODO: Retrieve filtered list of restaurants */ }; FriendlyEats.prototype.addRating = function(restaurantID, rating) { /* TODO: Retrieve add a rating to a restaurant */ };
Add pagination to the reinstated search view
# views.py from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query def search(request): # Search search_query = request.GET.get("q", None) page = request.GET.get("page", 1) if search_query: search_results = Page.objects.live().search(search_query) # Log the query so Wagtail can suggest promoted results Query.get(search_query).add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) # Render template return render( request, "core/search_results.html", { "search_query": search_query, "search_results": search_results, }, )
# views.py from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query def search(request): # Search search_query = request.GET.get("q", None) if search_query: search_results = Page.objects.live().search(search_query) # Log the query so Wagtail can suggest promoted results Query.get(search_query).add_hit() else: search_results = Page.objects.none() # Render template return render( request, "core/search_results.html", { "search_query": search_query, "search_results": search_results, }, )
Return new file name when uploading
from flask import Flask, request, jsonify, send_from_directory import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) projects = os.listdir(UPLOAD_FOLDER) return projects.__repr__() + "\n" @app.route("/sounds/<path:path>") def serve_static(path): return send_from_directory(UPLOAD_FOLDER, path) @app.route("/upload", methods=["POST"]) def upload_file(): file = request.files["sound"] if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) filename = uuid.uuid4().__str__() + ".wav" file.save(os.path.join(UPLOAD_FOLDER, filename)) return filename if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
from flask import Flask, request, jsonify, send_from_directory from werkzeug import secure_filename import os import uuid app = Flask(__name__) UPLOAD_FOLDER = "uploads/" @app.route("/") def index(): if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) projects = os.listdir(UPLOAD_FOLDER) return projects.__repr__() + "\n" @app.route("/sounds/<path:path>") def serve_static(path): return send_from_directory(UPLOAD_FOLDER, path) @app.route("/upload", methods=["POST"]) def upload_file(): file = request.files["sound"] if file: if not os.path.isdir(UPLOAD_FOLDER): os.mkdir(UPLOAD_FOLDER) filename = secure_filename(file.filename) file.save(os.path.join(UPLOAD_FOLDER, uuid.uuid4().__str__() + ".wav")) return filename if __name__ == "__main__": app.run(host = "0.0.0.0", debug=True)
Rename CMS label to Pages
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'manage.cms': { url: '/cms', redirectTo: 'manage.cms.list', template: '<ui-view></ui-view>' } }; } function navItems() { return {}; } function sidebarItems() { return { 'manage.cms': { type: 'state', state: 'manage.cms', label: 'Pages', order: 10 } }; } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'manage.cms': { url: '/cms', redirectTo: 'manage.cms.list', template: '<ui-view></ui-view>' } }; } function navItems() { return {}; } function sidebarItems() { return { 'manage.cms': { type: 'state', state: 'manage.cms', label: 'CMS', order: 10 } }; } })();
Add fastRender flag to pages/:_id
/*****************************************************************************/ /* Client and Server Routes */ /*****************************************************************************/ Router.configure({ layoutTemplate: 'MasterLayout', loadingTemplate: 'Loading', notFoundTemplate: 'NotFound' }); Router.route('/', { name: 'marketing' }); Router.route('/pages', { name: 'pages.index' }); Router.route('/pages/new', { name: 'pages.new' }); Router.route('/pages/:_id', { name: 'pages.show', fastRender: true }); Router.route('/settings', { name: 'settings.index' }); Router.route('/users/:_id', { name: 'users.show' }); var requireLogin = function () { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('AccessDenied'); } } else { this.next(); } }; Router.onBeforeAction('dataNotFound'); Router.onBeforeAction(requireLogin, { except: [ 'marketing', 'pages.show' ] });
/*****************************************************************************/ /* Client and Server Routes */ /*****************************************************************************/ Router.configure({ layoutTemplate: 'MasterLayout', loadingTemplate: 'Loading', notFoundTemplate: 'NotFound' }); Router.route('/', { name: 'marketing' }); Router.route('/pages', { name: 'pages.index' }); Router.route('/pages/new', { name: 'pages.new' }); Router.route('/pages/:_id', { name: 'pages.show' }); Router.route('/settings', { name: 'settings.index' }); Router.route('/users/:_id', { name: 'users.show' }); var requireLogin = function () { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('AccessDenied'); } } else { this.next(); } }; Router.onBeforeAction('dataNotFound'); Router.onBeforeAction(requireLogin, { except: [ 'marketing', 'pages.show' ] });
Add Python version agnostic helpers for creating byte and unicode literals.
# compatibility module for different python versions import sys if sys.version_info[:2] > (3, 0): PY2 = False PY3 = True Bytes = bytes Unicode = str basestring = str BytesLiteral = lambda x: x.encode('latin1') UnicodeLiteral = lambda x: x class_type_name = 'class' ClassType = type exception_module = 'builtins' new_class = type self_name = '__self__' from io import StringIO xrange = range else: PY2 = True PY3 = False Bytes = str Unicode = unicode basestring = basestring BytesLiteral = lambda x: x UnicodeLiteral = lambda x: x.decode('latin1') class_type_name = 'type' from types import ClassType exception_module = 'exceptions' from new import classobj as new_class self_name = 'im_self' from cStringIO import StringIO xrange = xrange try: from mock import call as mock_call except ImportError: # pragma: no cover class MockCall: pass mock_call = MockCall() try: from unittest.mock import call as unittest_mock_call except ImportError: class UnittestMockCall: pass unittest_mock_call = UnittestMockCall()
# compatibility module for different python versions import sys if sys.version_info[:2] > (3, 0): PY2 = False PY3 = True Bytes = bytes Unicode = str basestring = str class_type_name = 'class' ClassType = type exception_module = 'builtins' new_class = type self_name = '__self__' from io import StringIO xrange = range else: PY2 = True PY3 = False Bytes = str Unicode = unicode basestring = basestring class_type_name = 'type' from types import ClassType exception_module = 'exceptions' from new import classobj as new_class self_name = 'im_self' from cStringIO import StringIO xrange = xrange try: from mock import call as mock_call except ImportError: # pragma: no cover class MockCall: pass mock_call = MockCall() try: from unittest.mock import call as unittest_mock_call except ImportError: class UnittestMockCall: pass unittest_mock_call = UnittestMockCall()
Fix "Fatal error: Using $this when not in object context"
<?php namespace Arseniew\Silex\Service; class IdiormService { protected $connectionName; protected $tables = array(); public function __construct($connectionName) { $this->connectionName = $connectionName; } public function for_table($tableName) { if (!isset($this->tables[$tableName])) { $this->tables[$tableName] = \ORM::for_table($tableName, $this->connectionName); } return $this->tables[$tableName]; } public static function get_db($connectionName) { return \ORM::get_db($connectionName); } public function raw_execute($query, $parameters = array()) { return \ORM::raw_execute($query, $parameters = array(), $this->connectionName); } public static function get_last_statement() { return \ORM::get_last_statement(); } public function get_last_query() { return \ORM::get_last_query($this->connectionName); } public function get_query_log() { return \ORM::get_query_log($this->connectionName); } public static function clear_cache() { return \ORM::clear_cache(); } }
<?php namespace Arseniew\Silex\Service; class IdiormService { protected $connectionName; protected $tables = array(); public function __construct($connectionName) { $this->connectionName = $connectionName; } public function for_table($tableName) { if (!isset($this->tables[$tableName])) { $this->tables[$tableName] = \ORM::for_table($tableName, $this->connectionName); } return $this->tables[$tableName]; } public static function get_db($connectionName) { return \ORM::get_db($connectionName); } public static function raw_execute($query, $parameters = array()) { return \ORM::raw_execute($query, $parameters = array(), $this->connectionName); } public static function get_last_statement() { return \ORM::get_last_statement(); } public static function get_last_query() { return \ORM::get_last_query($this->connectionName); } public static function get_query_log() { return \ORM::get_query_log($this->connectionName); } public static function clear_cache() { return \ORM::clear_cache(); } }
testsuite: Simplify Python <3.5 fallback for TextIO (cherry picked from commit d092d8598694c23bc07cdcc504dff52fa5f33be1)
""" This module provides some type definitions and backwards compatibility shims for use in the testsuite driver. The testsuite driver can be typechecked using mypy [1]. [1] http://mypy-lang.org/ """ try: from typing import * import typing except: # The backwards compatibility stubs must live in another module lest # mypy complains. from typing_stubs import * # type: ignore #################################################### # Backwards compatibility shims # # N.B. mypy appears to typecheck as though the "then" clause of if structures # is taken. We exploit this below. # TextIO is missing on some older Pythons. if 'TextIO' not in globals(): try: TextIO = typing.TextIO except ImportError: TextIO = None # type: ignore else: TextIO = None # type: ignore #################################################### # Testsuite-specific types WayName = NewType("WayName", str) TestName = NewType("TestName", str) OutputNormalizer = Callable[[str], str] IssueNumber = NewType("IssueNumber", int) # Used by perf_notes GitHash = NewType("GitHash", str) GitRef = NewType("GitRef", str) TestEnv = NewType("TestEnv", str) MetricName = NewType("MetricName", str)
""" This module provides some type definitions and backwards compatibility shims for use in the testsuite driver. The testsuite driver can be typechecked using mypy [1]. [1] http://mypy-lang.org/ """ try: from typing import * import typing except: # The backwards compatibility stubs must live in another module lest # mypy complains. from typing_stubs import * # type: ignore #################################################### # Backwards compatibility shims # # N.B. mypy appears to typecheck as though the "then" clause of if structures # is taken. We exploit this below. # TextIO is missing on some older Pythons. if 'TextIO' in globals(): TextIO = typing.TextIO else: TextIO = None # type: ignore #################################################### # Testsuite-specific types WayName = NewType("WayName", str) TestName = NewType("TestName", str) OutputNormalizer = Callable[[str], str] IssueNumber = NewType("IssueNumber", int) # Used by perf_notes GitHash = NewType("GitHash", str) GitRef = NewType("GitRef", str) TestEnv = NewType("TestEnv", str) MetricName = NewType("MetricName", str)
Fix a few issues in the test file - Destructure actions from actionCreators - Fix createState defaults
import { describe } from 'riteway'; import dsm from '../dsm'; const SIGNED_OUT = 'signed_out'; const AUTHENTICATING = 'authenticating'; const actionStates = [ ['initialize', SIGNED_OUT, ['sign in', AUTHENTICATING // ['report error', 'error', // ['handle error', 'signed out'] // ], // ['sign-in success', 'signed in'] ] ] ]; const { reducer, actionCreators: { initialize, signIn } } = dsm({ component: 'user-authentication', description: 'authenticate user', actionStates }); const createState = ({ status = SIGNED_OUT, payload = { type: 'empty' } } = {}) => ({ status, payload }); describe('userAuthenticationReducer', async should => { { const {assert} = should('use "signed out" as initialized state'); assert({ given: '["initialize", "signed out", /*...*/', actual: reducer(), expected: createState() }); } { const {assert} = should('transition into authenticating state'); const initialState = reducer(undefined, initialize()); assert({ given: 'signed out initial state & signIn action', actual: reducer(initialState, signIn()), expected: createState({ status: 'authenticating' }) }); } });
import { describe } from 'riteway'; import dsm from '../dsm'; const actionStates = [ ['initialize', 'signed out', ['sign in', 'authenticating' // ['report error', 'error', // ['handle error', 'signed out'] // ], // ['sign-in success', 'signed in'] ] ] ]; const { initialize, reducer, signIn } = dsm({ component: 'user-authentication', description: 'authenticate user', actionStates }); const createState = ({ status = 'signed out', payload: { type = 'empty'} = {} } = {}) => ({ status, payload: { type } }); describe('userAuthenticationReducer', async should => { { const {assert} = should('use "signed out" as initialized state'); assert({ given: '["initialize", "signed out", /*...*/', actual: reducer(), expected: createState() }); } { const {assert} = should('transition into authenticating state'); const initialState = reducer(undefined, initialize()); assert({ given: 'signed out initial state & signIn action', actual: reducer(initialState, signIn()), expected: createState() }); } });
Save the claim json as properly formatted json
import json import logging class ClaimParser(object): """ Parses a generic claim. """ def __init__(self, claim: str) -> None: self.__logger = logging.getLogger(__name__) self.__orgData = claim self.__parse() def __parse(self): self.__logger.debug("Parsing claim ...") data = json.loads(self.__orgData) self.__claim_type = data["claim_type"] self.__claim = data["claim_data"] self.__issuer_did = data["claim_data"]["issuer_did"] def getField(self, field): return self.__claim["claim"][field][0] @property def schemaName(self) -> str: return self.__claim_type @property def issuerDid(self) -> str: return self.__issuer_did @property def json(self) -> str: return self.__claim
import json import logging class ClaimParser(object): """ Parses a generic claim. """ def __init__(self, claim: str) -> None: self.__logger = logging.getLogger(__name__) self.__orgData = claim self.__parse() def __parse(self): self.__logger.debug("Parsing claim ...") data = json.loads(self.__orgData) self.__claim_type = data["claim_type"] self.__claim = data["claim_data"] self.__issuer_did = data["claim_data"]["issuer_did"] def getField(self, field): return self.__claim["claim"][field][0] @property def schemaName(self) -> str: return self.__claim_type @property def issuerDid(self) -> str: return self.__issuer_did @property def json(self) -> str: return json.dumps(self.__claim)
Update color draft with favorite 'black' version
const black = '#36393B'; const red = '#FF7C7A'; const green = '#8FD5A6'; const yellow = '#FFE57F'; const blue = '#378AAD'; const magenta = '#8C82AF'; const cyan = '#8CCEC6'; const white = '#F4F1DE'; const lightBlack = '#817F823'; const lightWhite = '#FFFFFA'; module.exports = { plugins: [ ], config: { padding: '17px', fontSize: 17, fontFamily: '"Fira Mono", monospace', cursorShape: 'BLOCK', cursorColor: white, foregroundColor: lightWhite, backgroundColor: black, borderColor: lightBlack, colors: { black, red, green, yellow, blue, magenta, cyan, white, lightBlack, lightRed: red, lightGreen: green, lightYellow: yellow, lightBlue: blue, lightMagenta: magenta, lightCyan: cyan, lightWhite, }, }, };
const dimGrey = '#5C6F68'; const gunMetal = '#2A2E35'; const gunMetal2 = '#2D3047'; const purpleTaupe = '#484349'; const darkElectricBlue = '#5D737E'; const stormCloud = '#4F616B'; const outerSpace = '#404F56'; const richBlack = '#022F40'; const onyx = '#36393B'; const black = onyx; const red = '#FF7C7A'; const green = '#8FD5A6'; const yellow = '#FFE57F'; const blue = '#378AAD'; const magenta = '#8C82AF'; const cyan = '#8CCEC6'; const white = '#F4F1DE'; const lightBlack = '#817F823'; const lightWhite = '#FFFFFA'; module.exports = { plugins: [ ], config: { padding: '17px', fontSize: 17, fontFamily: '"Fira Mono", monospace', cursorShape: 'BLOCK', cursorColor: white, foregroundColor: lightWhite, backgroundColor: black, borderColor: lightBlack, colors: { black, red, green, yellow, blue, magenta, cyan, white, lightBlack, lightRed: red, lightGreen: green, lightYellow: yellow, lightBlue: blue, lightMagenta: magenta, lightCyan: cyan, lightWhite, }, }, };
Revert "set promises delay to 0ms for syncing tests" This reverts commit 0635c2e3f885433899fb773f8be4d6c1e4fda583.
// use higher values to slow down tests for debugging var promisesDelay; const syncingTestsActive = (process.argv.length > 5 && process.argv[5] == '--suite=syncing'); if (syncingTestsActive) { promisesDelay = 150; } else { promisesDelay = 0; } function delayPromises(milliseconds) { var executeFunction = browser.driver.controlFlow().execute; browser.driver.controlFlow().execute = function() { var args = arguments; executeFunction.call(browser.driver.controlFlow(), function() { return protractor.promise.delayed(milliseconds); }); return executeFunction.apply(browser.driver.controlFlow(), args); }; } console.log("Set promises delay to " + promisesDelay + " ms."); delayPromises(promisesDelay); var ECWaitTime = 20000; var shortRest = 200; module.exports = { ECWaitTime: ECWaitTime, shortRest: shortRest };
// use higher values to slow down tests for debugging var promisesDelay; // const syncingTestsActive = (process.argv.length > 5 && process.argv[5] == '--suite=syncing'); promisesDelay = 0; function delayPromises(milliseconds) { var executeFunction = browser.driver.controlFlow().execute; browser.driver.controlFlow().execute = function() { var args = arguments; executeFunction.call(browser.driver.controlFlow(), function() { return protractor.promise.delayed(milliseconds); }); return executeFunction.apply(browser.driver.controlFlow(), args); }; } console.log("Set promises delay to " + promisesDelay + " ms."); delayPromises(promisesDelay); var ECWaitTime = 20000; var shortRest = 200; module.exports = { ECWaitTime: ECWaitTime, shortRest: shortRest };
Set the default value of the checkInstalled option to false
'use babel'; export default { "prerelease": { "title": "Level of prerelease", "description": "Set the level maximum to check for the libraries versions", "type": "string", "default": "stable", "enum": ["stable", "rc", "beta", "alpha", "dev"] }, "info": { "title": "Display information", "description": "Display information of the package that have a not enough restrictive version", "type": "boolean", "default": true }, "checkInstalled": { "title": "Check installed package version", "description": "The installed package will be inspected to verify that the version satisfy the package.json dependency", "type": "boolean", "default": false }, "npmrc": { "title": "Path to NPM config file", "type": "string", "default": ".npmrc" }, "npmUrl": { "title": "NPM Package information base url", "type": "string", "default": "https://www.npmjs.com/package" } };
'use babel'; export default { "prerelease": { "title": "Level of prerelease", "description": "Set the level maximum to check for the libraries versions", "type": "string", "default": "stable", "enum": ["stable", "rc", "beta", "alpha", "dev"] }, "info": { "title": "Display information", "description": "Display information of the package that have a not enough restrictive version", "type": "boolean", "default": true }, "checkInstalled": { "title": "Check installed package version", "description": "The installed package will be inspected to verify that the version satisfy the package.json dependency", "type": "boolean", "default": true }, "npmrc": { "title": "Path to NPM config file", "type": "string", "default": ".npmrc" }, "npmUrl": { "title": "NPM Package information base url", "type": "string", "default": "https://www.npmjs.com/package" } };
Add is_active to the list of keys to be dumped as json
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from random import SystemRandom from django.conf import settings import string # Note: the code in this module must be identical in both lizard-auth-server # and lizard-auth-client! random = SystemRandom() KEY_CHARACTERS = string.letters + string.digits # Keys that can be directly copied from the User object and passed to the # client. SIMPLE_KEYS = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', ] def default_gen_secret_key(length=40): return ''.join([random.choice(KEY_CHARACTERS) for _ in range(length)]) def gen_secret_key(length=40): generator = getattr(settings, 'SSO_KEYGENERATOR', default_gen_secret_key) return generator(length)
Fix HTML email extraction regex
<?php $subject = $this->email->getHeaderValue('Subject', '<Empty Subject>'); $this->title($subject); ?> <h1 class="heading"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Outgoing emails - listing</a> &gt; <span class="sub"><?= $this->escape()->html($subject);?></span> </h1> <div class="email-headers"> <dl> <?php foreach ($this->email->getHeaders() as $header) { echo "<dt>", $this->escape()->html($header->getName()), "</dt>\r\n"; echo "<dd>&nbsp;", $this->escape()->html($header->getValue()), "</dd>\r\n"; } ?> </dl> <div class="back"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Back to email list</a> </div> </div> <p class="email-body"> <?php $html = $this->email->getHtmlContent(); if ($html !== null) { echo preg_replace('/^.*?<body>(.*?)<\/body>.*$/ims', '$1', $html); } else { echo nl2br($this->escape()->html($this->email->getTextContent())); } ?> </p>
<?php $subject = $this->email->getHeaderValue('Subject', '<Empty Subject>'); $this->title($subject); ?> <h1 class="heading"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Outgoing emails - listing</a> &gt; <span class="sub"><?= $this->escape()->html($subject);?></span> </h1> <div class="email-headers"> <dl> <?php foreach ($this->email->getHeaders() as $header) { echo "<dt>", $this->escape()->html($header->getName()), "</dt>\r\n"; echo "<dd>&nbsp;", $this->escape()->html($header->getValue()), "</dd>\r\n"; } ?> </dl> <div class="back"> <a href="<?= $this->escape()->attr($this->route('list')); ?>">Back to email list</a> </div> </div> <p class="email-body"> <?php $html = $this->email->getHtmlContent(); if ($html !== null) { echo preg_replace('/.*?<body>(.*?)<\/body>.*?/ims', '$1', $html); } else { echo nl2br($this->escape()->html($this->email->getTextContent())); } ?> </p>
Correct my cowboy fix that broke.
import sublime_plugin from bower.utils.api import API class InstallCommand(sublime_plugin.WindowCommand): def run(self, *args, **kwargs): self.list_packages() def list_packages(self): fileList = [] packages = API().get('packages') packages.reverse() for package in packages: fileList.append([package['name'], package['url']]) self.window.show_quick_panel(fileList, self.get_file) def get_file(self, index): if (index > -1): if not self.window.views(): self.window.new_file() name = self.fileList[index][0] cwd = self.window.folders()[0] self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
import sublime_plugin from bower.utils.api import API class InstallCommand(sublime_plugin.WindowCommand): def run(self, *args, **kwargs): self.list_packages() def list_packages(self): fileList = [] packages = API().get('packages') packages.reverse() for package in packages: self.fileList.append([package['name'], package['url']]) self.window.show_quick_panel(self.fileList, self.get_file) def get_file(self, index): if (index > -1): if not self.window.views(): self.window.new_file() name = self.fileList[index][0] cwd = self.window.folders()[0] self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
[x/tour] tour: Rename mux -> mu to follow convention Nearly all sync.Mutex members in the standard library are named mu, or use "mu" as part of the name. While this isn't a documented recommendation anywhere that I can find, it would seem nice to start new users with this same convention. Change-Id: I67cbe2a0052b81d8bb57d5ece0cefd2f3838f298 GitHub-Last-Rev: 31ef869d9b72e7eb08b9be9340242b0e535a175f GitHub-Pull-Request: golang/tour#813 Reviewed-on: https://go-review.googlesource.com/c/tour/+/192725 Reviewed-by: Brad Fitzpatrick <ae9783c0b0efc69cd85ab025ddd17aa44cdc4aa5@golang.org> X-Tour-Commit: 2e616b842c1127f0f4f1e49fcf2765d347bcaea1
// +build OMIT package main import ( "fmt" "sync" "time" ) // SafeCounter is safe to use concurrently. type SafeCounter struct { mu sync.Mutex v map[string]int } // Inc increments the counter for the given key. func (c *SafeCounter) Inc(key string) { c.mu.Lock() // Lock so only one goroutine at a time can access the map c.v. c.v[key]++ c.mu.Unlock() } // Value returns the current value of the counter for the given key. func (c *SafeCounter) Value(key string) int { c.mu.Lock() // Lock so only one goroutine at a time can access the map c.v. defer c.mu.Unlock() return c.v[key] } func main() { c := SafeCounter{v: make(map[string]int)} for i := 0; i < 1000; i++ { go c.Inc("somekey") } time.Sleep(time.Second) fmt.Println(c.Value("somekey")) }
// +build OMIT package main import ( "fmt" "sync" "time" ) // SafeCounter is safe to use concurrently. type SafeCounter struct { v map[string]int mux sync.Mutex } // Inc increments the counter for the given key. func (c *SafeCounter) Inc(key string) { c.mux.Lock() // Lock so only one goroutine at a time can access the map c.v. c.v[key]++ c.mux.Unlock() } // Value returns the current value of the counter for the given key. func (c *SafeCounter) Value(key string) int { c.mux.Lock() // Lock so only one goroutine at a time can access the map c.v. defer c.mux.Unlock() return c.v[key] } func main() { c := SafeCounter{v: make(map[string]int)} for i := 0; i < 1000; i++ { go c.Inc("somekey") } time.Sleep(time.Second) fmt.Println(c.Value("somekey")) }
Update test to compare dictionaries, rather than json string
from django.test import TestCase from studygroups.models import Course from .community_feedback import calculate_course_ratings import json class TestCommunityFeedback(TestCase): fixtures = ['test_courses.json', 'test_studygroups.json', 'test_applications.json', 'test_survey_responses.json'] def test_calculate_course_ratings(self): course = Course.objects.get(pk=3) self.assertEqual(course.overall_rating, 0) self.assertEqual(course.rating_step_counts, "{}") self.assertEqual(course.total_ratings, 0) calculate_course_ratings(course) expected_rating_step_counts = {"5": 2, "4": 1, "3": 0, "2": 0, "1": 0} rating_step_counts = json.loads(course.rating_step_counts) self.assertEqual(course.overall_rating, 4.67) self.assertEqual(rating_step_counts, expected_rating_step_counts) self.assertEqual(course.total_ratings, 3)
from django.test import TestCase from studygroups.models import Course from .community_feedback import calculate_course_ratings class TestCommunityFeedback(TestCase): fixtures = ['test_courses.json', 'test_studygroups.json', 'test_applications.json', 'test_survey_responses.json'] def test_calculate_course_ratings(self): course = Course.objects.get(pk=3) self.assertEqual(course.overall_rating, 0) self.assertEqual(course.rating_step_counts, "{}") self.assertEqual(course.total_ratings, 0) calculate_course_ratings(course) expected_rating_step_counts = '{"5": 2, "4": 1, "3": 0, "2": 0, "1": 0}' self.assertEqual(course.overall_rating, 4.67) self.assertEqual(course.rating_step_counts, expected_rating_step_counts) self.assertEqual(course.total_ratings, 3)
Add register command-line interface option
#!/usr/bin/env node var program = require('commander'); var autometa = require('../lib/autometa.js'); var package = require('../package.json'); program .version(package['version'], '-v, --version') .usage('[options] <Excel spreadsheet>') .option('-o, --stdout', 'place output on stdout') .option('-r, --register <template file>', 'register templates', String) .parse(process.argv); var templates = [] if(!program.args.length) { // No filename found if(program.register) { templates.push(program.register); console.log("register: " + templates); process.exit(0); } else { program.help(); } } else { // filename found if(program.stdout) { output = autometa.generate(program.args[0]); if(output) { console.log(output[1]); // Print only 1st data process.exit(0); } else { console.log("Error. Check input file."); process.exit(1); } } else if(program.register) { // Count strings as templates templates.push(program.register); templates = templates.concat(program.args); console.log("register: " + templates); process.exit(0); } else { // Only filename specified if(autometa.generateFile(program.args[0])) { // Success to generate file process.exit(0); } else { // Failed to generate file console.log("Error. Check input file."); process.exit(1); } } }
#!/usr/bin/env node var program = require('commander'); var autometa = require('../lib/autometa.js'); var package = require('../package.json'); program .version(package['version'], '-v, --version') .usage('[options] <Excel spreadsheet>') .option('-o, --stdout', 'place output on stdout') .parse(process.argv); var filename = program.args[0]; if(!program.args.length) { program.help(); } else if(program.stdout) { output = autometa.generate(filename); if(output) { console.log(output[1]); process.exit(0); } else { console.log("Error. Check input file."); process.exit(1); } } else { if(autometa.generateFile(filename)) { process.exit(0); } else { console.log("Error. Check input file."); process.exit(1); } }
Add own hostname to /etc/hosts
#!/usr/bin/python import os hostnames = eval(os.environ['hostnames']) addresses = eval(os.environ['addresses']) def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') f.write('127.0.0.1 localhost ' + os.uname()[1] + '\n\n') for idx, hostname in enumerate(hostnames): f.write(addresses[idx] + ' ' + hostname + '\n') f.write('\n') f.write('# The following lines are desirable for IPv6 capable hosts\n') f.write('::1 ip6-localhost ip6-loopback\n') f.write('fe00::0 ip6-localnet\n') f.write('ff00::0 ip6-mcastprefix\n') f.write('ff02::1 ip6-allnodes\n') f.write('ff02::2 ip6-allrouters\n') f.write('ff02::3 ip6-allhosts\n') with open('/etc/hosts', 'w') as f: write_hosts(hostnames, addresses, f)
#!/usr/bin/python import os hostnames = eval(os.environ['hostnames']) addresses = eval(os.environ['addresses']) def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') f.write('127.0.0.1 localhost\n\n') for idx, hostname in enumerate(hostnames): f.write(addresses[idx] + ' ' + hostname + '\n') f.write('\n') f.write('# The following lines are desirable for IPv6 capable hosts\n') f.write('::1 ip6-localhost ip6-loopback\n') f.write('fe00::0 ip6-localnet\n') f.write('ff00::0 ip6-mcastprefix\n') f.write('ff02::1 ip6-allnodes\n') f.write('ff02::2 ip6-allrouters\n') f.write('ff02::3 ip6-allhosts\n') with open('/etc/hosts', 'w') as f: write_hosts(hostnames, addresses, f)
Add interactiveLoop() shell for testing
import java.io.File; import java.io.BufferedReader; import java.io.IOException; import java.io.FileReader; import java.util.ArrayList; public class Engineering { public static void main(String[] args) { if (args.length < 1) { System.err.println("A file must be supplied."); System.exit(1); return; } File file = new File(args[0]); ArrayList<Student> records; try { records = readRecords(file); } catch (IOException ex) { System.err.println("Error reading file: " + file); System.exit(1); return; } interactiveLoop(records); } private static ArrayList<Student> readRecords(File file) throws IOException { ArrayList<Student> records = new ArrayList<Student>(); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { for (String line = reader.readLine(); // Forget first line. (line = reader.readLine()) != null;) { if (!line.isEmpty()) { records.add(new Student(line)); } } } return records; } private static void interactiveLoop(ArrayList<Student> records) { BufferedReader stdin = new BufferedReader(new FileInputStream( System.in)); for (String line; (line = stdin.readLine()) != null;) { System.out.println(line); } } }
import java.io.File; import java.io.BufferedReader; import java.io.IOException; import java.io.FileReader; import java.util.ArrayList; public class Engineering { public static void main(String[] args) { if (args.length < 1) { System.err.println("A file must be supplied."); System.exit(1); return; } File file = new File(args[0]); ArrayList<Student> records; try { records = readRecords(file); } catch (IOException ex) { System.err.println("Error reading file: " + file); System.exit(1); return; } } private static ArrayList<Student> readRecords(File file) throws IOException { ArrayList<Student> records = new ArrayList<Student>(); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { for (String line = reader.readLine(); // Forget first line. (line = reader.readLine()) != null;) { records.add(new Student(line)); } } return records; } }
Fix reason for logging blacklist
<?php namespace App\Http\Middleware; use Closure; use App\IpBlacklist; use Log; class IPBasedBlacklist { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $ip = $request->ip(); /*$blacklist = IpBlacklist ::where('ip_address', $ip) ->first();*/ $blacklistedIps = explode(',', env('BLACKLISTED_IPS', '')); if (!in_array($ip, $blacklistedIps)) { return $next($request); } Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), 'Not set.')); abort(503); } }
<?php namespace App\Http\Middleware; use Closure; use App\IpBlacklist; use Log; class IPBasedBlacklist { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $ip = $request->ip(); /*$blacklist = IpBlacklist ::where('ip_address', $ip) ->first();*/ $blacklistedIps = explode(',', env('BLACKLISTED_IPS', '')); if (!in_array($ip, $blacklistedIps)) { return $next($request); } Log::Info(sprintf('Blocked %s from accessing %s due to reason: %s', $ip, $request->fullUrl(), $blacklist->reason)); abort(503); } }
Disable redefined outer name pylint warning.
# coding: utf-8 from __future__ import unicode_literals, absolute_import import pytest from boxsdk.util.multipart_stream import MultipartStream @pytest.fixture(params=({}, {'data_1': b'data_1_value', 'data_2': b'data_2_value'})) def multipart_stream_data(request): return request.param @pytest.fixture(params=({}, {'file_1': b'file_1_value', 'file_2': b'file_2_value'})) def multipart_stream_files(request): return request.param def test_multipart_stream_orders_data_before_files(multipart_stream_data, multipart_stream_files): # pylint:disable=redefined-outer-name if not multipart_stream_data and not multipart_stream_files: pytest.xfail('Encoder does not support empty fields.') stream = MultipartStream(multipart_stream_data, multipart_stream_files) encoded_stream = stream.to_string() data_indices = [encoded_stream.find(value) for value in multipart_stream_data.values()] file_indices = [encoded_stream.find(value) for value in multipart_stream_files.values()] assert -1 not in data_indices assert -1 not in file_indices assert all((all((data_index < f for f in file_indices)) for data_index in data_indices))
# coding: utf-8 from __future__ import unicode_literals, absolute_import import pytest from boxsdk.util.multipart_stream import MultipartStream @pytest.fixture(params=({}, {'data_1': b'data_1_value', 'data_2': b'data_2_value'})) def multipart_stream_data(request): return request.param @pytest.fixture(params=({}, {'file_1': b'file_1_value', 'file_2': b'file_2_value'})) def multipart_stream_files(request): return request.param def test_multipart_stream_orders_data_before_files(multipart_stream_data, multipart_stream_files): if not multipart_stream_data and not multipart_stream_files: pytest.xfail('Encoder does not support empty fields.') stream = MultipartStream(multipart_stream_data, multipart_stream_files) encoded_stream = stream.to_string() data_indices = [encoded_stream.find(value) for value in multipart_stream_data.values()] file_indices = [encoded_stream.find(value) for value in multipart_stream_files.values()] assert -1 not in data_indices assert -1 not in file_indices assert all((all((data_index < f for f in file_indices)) for data_index in data_indices))
Allow shape output on /boundary/ queries
from django.conf.urls.defaults import patterns, include, url from boundaryservice.views import * urlpatterns = patterns('', url(r'^boundary-set/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'), url(r'^boundary-set/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_set_detail'), url(r'^boundary/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'), url(r'^boundary/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()), url(r'^boundary/(?P<set_slug>[\w_-]+)/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'), url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()), url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/$', BoundaryDetailView.as_view(), name='boundaryservice_boundary_detail'), url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryGeoDetailView.as_view()), )
from django.conf.urls.defaults import patterns, include, url from boundaryservice.views import * urlpatterns = patterns('', url(r'^boundary-set/$', BoundarySetListView.as_view(), name='boundaryservice_set_list'), url(r'^boundary-set/(?P<slug>[\w_-]+)/$', BoundarySetDetailView.as_view(), name='boundaryservice_set_detail'), url(r'^boundary/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'), url(r'^boundary/(?P<set_slug>[\w_-]+)/$', BoundaryListView.as_view(), name='boundaryservice_boundary_list'), url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryListView.as_view()), url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/$', BoundaryDetailView.as_view(), name='boundaryservice_boundary_detail'), url(r'^boundary/(?P<set_slug>[\w_-]+)/(?P<slug>[\w_-]+)/(?P<geo_field>shape|simple_shape|centroid)$', BoundaryGeoDetailView.as_view()), )
Make HTTP server fixture bind to an ephemeral port
import threading import time import pytest import cheroot.server import cheroot.wsgi EPHEMERAL_PORT = 0 config = { 'bind_addr': ('127.0.0.1', EPHEMERAL_PORT), 'wsgi_app': None, } def cheroot_server(server_factory): conf = config.copy() httpserver = server_factory(**conf) # create it threading.Thread(target=httpserver.safe_start).start() # spawn it while not httpserver.ready: # wait until fully initialized and bound time.sleep(0.1) yield httpserver httpserver.stop() # destroy it @pytest.fixture(scope='module') def wsgi_server(): for srv in cheroot_server(cheroot.wsgi.Server): yield srv @pytest.fixture(scope='module') def native_server(): for srv in cheroot_server(cheroot.server.HTTPServer): yield srv
import threading import time import pytest import cheroot.server import cheroot.wsgi config = { 'bind_addr': ('127.0.0.1', 54583), 'wsgi_app': None, } def cheroot_server(server_factory): conf = config.copy() httpserver = server_factory(**conf) # create it threading.Thread(target=httpserver.safe_start).start() # spawn it while not httpserver.ready: # wait until fully initialized and bound time.sleep(0.1) yield httpserver httpserver.stop() # destroy it @pytest.fixture(scope='module') def wsgi_server(): for srv in cheroot_server(cheroot.wsgi.Server): yield srv @pytest.fixture(scope='module') def native_server(): for srv in cheroot_server(cheroot.server.HTTPServer): yield srv
Use textContent instead of innerText
var html = document.getElementById("html"); var render = document.getElementById("render"); var toggle = document.getElementById("toggle"); var error = document.getElementById("error"); var code = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "javascript" }); function update() { try { var element = new Function( "with(xmgen.svg) { with (xmgen.html) { return " + code.getValue() + "}}" )(); error.textContent = ""; if (toggle.classList.contains("down")) { html.textContent = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { error.textContent = e.toString(); } } code.on("change", update); toggle.addEventListener("click", function() { if (toggle.classList.contains("down")) { toggle.classList.remove("down"); html.innerHTML = ""; } else { toggle.classList.add("down"); render.innerHTML = ""; } update(); }); update();
var html = document.getElementById("html"); var render = document.getElementById("render"); var toggle = document.getElementById("toggle"); var error = document.getElementById("error"); var code = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "javascript" }); function update() { try { var element = new Function( "with(xmgen.svg) { with (xmgen.html) { return " + code.getValue() + "}}" )(); error.innerText = ""; if (toggle.classList.contains("down")) { html.innerText = element.toString(2); CodeMirror.colorize([html], "xml"); } else { render.innerHTML = element.toString(); } } catch (e) { error.innerText = e.toString(); } } code.on("change", update); toggle.addEventListener("click", function() { if (toggle.classList.contains("down")) { toggle.classList.remove("down"); html.innerHTML = ""; } else { toggle.classList.add("down"); render.innerHTML = ""; } update(); }); update();
Use my own email as the stuff
from .common import * import dj_database_url # Settings for production environment DEBUG = False # Update database configuration with $DATABASE_URL. db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ALLOWED_HOSTS = ['floating-castle-71814.herokuapp.com'] # apparently you need to have this LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'), }, }, } EMAIL_BACKEND = 'postmark.django_backend.EmailBackend' POSTMARK_API_KEY = os.getenv('POSTMARK_API_KEY') POSTMARK_SENDER = 'ian@ianluo.com' POSTMARK_TEST_MODE = True # We can use this to just to see the json POSTMARK_TRACK_OPENS = False
from .common import * import dj_database_url # Settings for production environment DEBUG = False # Update database configuration with $DATABASE_URL. db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ALLOWED_HOSTS = ['floating-castle-71814.herokuapp.com'] # apparently you need to have this LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'ERROR'), }, }, } EMAIL_BACKEND = 'postmark.django_backend.EmailBackend' POSTMARK_API_KEY = os.getenv('POSTMARK_API_KEY') POSTMARK_SENDER = 'baattendance@baa.com' POSTMARK_TEST_MODE = True # We can use this to just to see the json POSTMARK_TRACK_OPENS = False
Add specifier for python 2 and 3 for the package
#!/usr/bin/env python import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), "r") as readme_file: readme = readme_file.read() setup( name = "outpan", version = "0.1.2", description = "Easily use Outpan.com API to get product info from their barcode", long_description = readme, py_modules = ["outpan"], author = "Bertrand Vidal", author_email = "vidal.bertrand@gmail.com", download_url = "https://pypi.python.org/pypi/outpan", url = "https://github.com/bertrandvidal/outpan_api", classifiers = [ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], install_requires = [ "requests", ], )
#!/usr/bin/env python import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst'), "r") as readme_file: readme = readme_file.read() setup( name = "outpan", version = "0.1.2", description = "Easily use Outpan.com API to get product info from their barcode", long_description = readme, py_modules = ["outpan"], author = "Bertrand Vidal", author_email = "vidal.bertrand@gmail.com", download_url = "https://pypi.python.org/pypi/outpan", url = "https://github.com/bertrandvidal/outpan_api", classifiers = [ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Operating System :: OS Independent", "Programming Language :: Python", ], install_requires = [ "requests", ], )
Remove link to server logs The handler was already removed in 66bf9a966069897ba651a596c7d2148c4d76ba1b.
<?php $path_prefix = '../'; require('../inc/common.php'); role_needed(ROLE_ADMIN); $title = 'Administration Panel'; include('admin_top.php'); include('../inc/start_html.php'); ?> <dl> <dt><a href="langs.php">Manage Languages</a></dt> <dd>Add and remove languages</dd> <dt><a href="users.php">Manage Users</a></dt> <dd>Add new users, alter user roles</dd> <dt><a href="import.php">Import Documents</a></dt> <dd>Import existing documents to the translation system.</dd> <dt><a href="docs.php">Manage Documents</a></dt> <dd>Rename or remove documents.</dd> <dt><a href="resources.php">Manage Resources</a></dt> <dd>Add, remove, modify external resources.</dd> <dt><a href="export.php">Export Documents</a></dt> <dd>Export edited and translated documents to the repository.</dd> </dl> <?php include('../inc/end_html.php'); ?>
<?php $path_prefix = '../'; require('../inc/common.php'); role_needed(ROLE_ADMIN); $title = 'Administration Panel'; include('admin_top.php'); include('../inc/start_html.php'); ?> <dl> <dt><a href="langs.php">Manage Languages</a></dt> <dd>Add and remove languages</dd> <dt><a href="users.php">Manage Users</a></dt> <dd>Add new users, alter user roles</dd> <dt><a href="import.php">Import Documents</a></dt> <dd>Import existing documents to the translation system.</dd> <dt><a href="docs.php">Manage Documents</a></dt> <dd>Rename or remove documents.</dd> <dt><a href="resources.php">Manage Resources</a></dt> <dd>Add, remove, modify external resources.</dd> <dt><a href="export.php">Export Documents</a></dt> <dd>Export edited and translated documents to the repository.</dd> <dt><a href="logs.php">Log Viewer</a></dt> <dd>View server logs.</dd> </dl> <?php include('../inc/end_html.php'); ?>
Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
import subprocess import string import shlex class Plugin: def __init__(self, command, allowedChars, insertInitialNewline=False): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars))) self.command = shlex.split(command) self.insertInitialNewline = insertInitialNewline def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() if self.insertInitialNewline: stdout = "\n" + stdout return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]}
import subprocess import string class Plugin: def __init__(self, command, allowedChars): # We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow. self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars)) self.command = command def run(self, values): sanitizedValues = [] for value in values: sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap)) result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE) stdout, stderr = result.communicate() return stdout.replace("\n", "<br>") whois = {"displayName": "Whois Lookup", "plugin": Plugin("whois", string.letters + string.digits + ".:-_")} dns_lookup = {"displayName": "DNS Lookup", "plugin": Plugin("host", string.letters + string.digits + ".:-_")} mapping = {"addr": [whois, dns_lookup], "string": [dns_lookup]}
Exclude it from coverage as these permissions are not used yet.
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask.ext.login import current_user def create(user=None): # pragma: no cover if current_user.is_authenticated(): if current_user.admin: return True else: return False else: return False def read(user=None): # pragma: no cover return True def update(user): # pragma: no cover return create(user) def delete(user): # pragma: no cover return update(user)
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyBossa is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PyBossa. If not, see <http://www.gnu.org/licenses/>. from flask.ext.login import current_user def create(user=None): if current_user.is_authenticated(): if current_user.admin: return True else: return False else: return False def read(user=None): return True def update(user): return create(user) def delete(user): return update(user)
Fix typo in Mediator pattern
<?php namespace Mediator; require_once __DIR__ . '/User.php'; require_once __DIR__ . '/Chatroom.php'; /** * 通常ユーザー * * @access public * @extends \Mediator\User * @author ku2ma2 <motorohi.tsumaniku@gmail.com> * @copyright ku2ma2 */ class UserDefault extends User { /** * メッセージ送信 * * @access public * @param string $to 受信者名 * @param string $message メッセージ * @return void */ public function sendMessage(string $to, string $message) { $this->chatroom->sendMessage($this->name, $to, $message); } /** * メッセージ受信 * * @access public * @param string $from メッセージ送信者 * @return string フォーマット化された文字列 */ public function receiveMessage(string $from, string $message) { printf("%sさん => %sさん: %s\n------------------------------\n", $from, $this->getName(), $message); } }
<?php namespace Mediator; require_once __DIR__ . '/User.php'; require_once __DIR__ . '/Chatroom.php'; /** * 発生したトラブルを表すクラス、トラブル番号(number)を持つ * * @access public * @extends \Mediator\User * @author ku2ma2 <motorohi.tsumaniku@gmail.com> * @copyright ku2ma2 */ class UserDefault extends User { /** * メッセージ送信 * * @access public * @param string $to 受信者名 * @param string $message メッセージ * @return void */ public function sendMessage(string $to, string $message) { $this->chatroom->sendMessage($this->name, $to, $message); } /** * メッセージ受信 * * @access public * @param string $from メッセージ送信者 * @return string フォーマット化された文字列 */ public function receiveMessage(string $from, string $message) { printf("%sさん => %sさん: %s\n------------------------------\n", $from, $this->getName(), $message); } }
Fix spelling test name spelling error
# -*- coding: utf-8 -*- from django.test import TestCase from .model_factories import AttributeF from ..models import AttributeArchive class TestModelAttributeArchive(TestCase): def test_archiving_attribute(self): attribute = AttributeF.create(key='A key') attribute.description = 'a new descritpion' attribute.save() attribute.key = 'a new key' attribute.save() attribute.key = 'A key' attribute.save() # test save with no changes, should not trigger model archival attribute.key = 'A key' attribute.save() self.assertEqual(AttributeArchive.objects.count(), 4) self.assertListEqual( [attr.key for attr in AttributeArchive.objects.all()], ['a_key', 'a_key', 'a_new_key', 'a_key'] ) self.assertListEqual( [attr.version for attr in AttributeArchive.objects.all()], [1, 2, 3, 4] )
# -*- coding: utf-8 -*- from django.test import TestCase from .model_factories import AttributeF from ..models import AttributeArchive class TestModelAttributeArchive(TestCase): def test_archiving_attrbute(self): attribute = AttributeF.create(key='A key') attribute.description = 'a new descritpion' attribute.save() attribute.key = 'a new key' attribute.save() attribute.key = 'A key' attribute.save() # test save with no changes, should not trigger model archival attribute.key = 'A key' attribute.save() self.assertEqual(AttributeArchive.objects.count(), 4) self.assertListEqual( [attr.key for attr in AttributeArchive.objects.all()], ['a_key', 'a_key', 'a_new_key', 'a_key'] ) self.assertListEqual( [attr.version for attr in AttributeArchive.objects.all()], [1, 2, 3, 4] )
Fix comment about the location of log-threshold flag.
// Copyright 2015 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // Author: Tobias Schottdorf package log import ( "flag" "github.com/cockroachdb/cockroach/util/log/logflags" ) func init() { logflags.InitFlags(&logging.mu, &logging.toStderr, &logging.alsoToStderr, logDir, &logging.color, &logging.verbosity, &logging.vmodule, &logging.traceLocation) // We define this flag here because stderrThreshold has the type Severity // which we can't pass to logflags without creating an import cycle. flag.Var(&logging.stderrThreshold, "log-threshold", "logs at or above this threshold go to stderr") }
// Copyright 2015 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // Author: Tobias Schottdorf package log import ( "flag" "github.com/cockroachdb/cockroach/util/log/logflags" ) func init() { logflags.InitFlags(&logging.mu, &logging.toStderr, &logging.alsoToStderr, logDir, &logging.color, &logging.verbosity, &logging.vmodule, &logging.traceLocation) // We define this flag here because stderrThreshold has the non-exported type // "severity". flag.Var(&logging.stderrThreshold, "log-threshold", "logs at or above this threshold go to stderr") }
Revert "Remove unnecessary effectArgs (use new game chat feature)" This reverts commit 691ba364132ebef3c9eb016927645232110469d4.
const DrawCard = require('../../drawcard.js'); class ShinjoTrailblazer extends DrawCard { setupCardAbilities(ability) { this.reaction({ title: 'Gain +2/+2', when: { onCardRevealed: (event, context) => event.card.isProvince && event.card.controller === context.source.controller.opponent && this.game.isDuringConflict() }, gameAction: ability.actions.cardLastingEffect({ effect: ability.effects.modifyBothSkills(2) }), effect: 'to give {0} +2{1}, +2{2}', effectArgs: () => ['military', 'political'] }); } } ShinjoTrailblazer.id = 'shinjo-trailblazer'; module.exports = ShinjoTrailblazer;
const DrawCard = require('../../drawcard.js'); class ShinjoTrailblazer extends DrawCard { setupCardAbilities(ability) { this.reaction({ title: 'Gain +2/+2', when: { onCardRevealed: (event, context) => event.card.isProvince && event.card.controller === context.source.controller.opponent && this.game.isDuringConflict() }, gameAction: ability.actions.cardLastingEffect({ effect: ability.effects.modifyBothSkills(2) }), effect: 'to give {0} +2military, +2political' }); } } ShinjoTrailblazer.id = 'shinjo-trailblazer'; module.exports = ShinjoTrailblazer;
Fix crash on certain types of error response.
package com.newsblur.network.domain; /** * A generic response to an API call that only encapsuates success versus failure. */ public class NewsBlurResponse { public boolean authenticated; public int code; public String message; public ResponseErrors errors; public String result; public boolean isError() { if (message != null) return true; if ((errors != null) && (errors.message.length > 0) && (errors.message[0] != null)) return true; return false; } /** * Gets the error message returned by the API, or defaultMessage if none was found. */ public String getErrorMessage(String defaultMessage) { if (message != null) return message; if ((errors != null) &&(errors.message != null) && (errors.message.length > 0) && (errors.message[0] != null)) return errors.message[0]; return defaultMessage; } /** * Gets the error message returned by the API, or a simple numeric error code if non was found. */ public String getErrorMessage() { return getErrorMessage(Integer.toString(code)); } }
package com.newsblur.network.domain; /** * A generic response to an API call that only encapsuates success versus failure. */ public class NewsBlurResponse { public boolean authenticated; public int code; public String message; public ResponseErrors errors; public String result; public boolean isError() { if (message != null) return true; if ((errors != null) && (errors.message.length > 0) && (errors.message[0] != null)) return true; return false; } /** * Gets the error message returned by the API, or defaultMessage if none was found. */ public String getErrorMessage(String defaultMessage) { if (message != null) return message; if ((errors != null) && (errors.message.length > 0) && (errors.message[0] != null)) return errors.message[0]; return defaultMessage; } /** * Gets the error message returned by the API, or a simple numeric error code if non was found. */ public String getErrorMessage() { return getErrorMessage(Integer.toString(code)); } }
Document the AppFactory, add the doc headers.
""" .. module:: app_factory :platform: linux :synopsis: .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): """This is the class factory for the App. - **parameters** and **types**:: :param cmd_args: The command-line args. :type cmd_args: argparse Namespace """ implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): """Returns the created App object. :return: Returns the App object. :rtype: App class. """ return App(self._system_data, self._plugins, self._time)
""" .. module:: app_factory :platform: linux :synopsis: .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/27/15 """ from zope.interface import implements from planet_alignment.app.app import App from planet_alignment.app.interface import IAppFactory from planet_alignment.config.bunch_parser import BunchParser from planet_alignment.data.system_data import SystemData from planet_alignment.mgr.plugins_mgr import PluginsManager class AppFactory(object): implements(IAppFactory) def __init__(self, cmd_args): data = BunchParser().parse(cmd_args.config) self._system_data = SystemData(data) self._plugins = PluginsManager(cmd_args.plugins) self._time = cmd_args.time def create(self): return App(self._system_data, self._plugins, self._time)
Fix URL name for submission page
from django.conf.urls.defaults import patterns, url, include from piston.resource import Resource from .views import (CreateRepoView, UpdatePasswordView, ListSubmissionView, SubmitView) from .api_handlers import RepoAuthHandler, RepoPathHandler, RepoTagListHandler urlpatterns = patterns( "", url(r'^api/repo/auth/', Resource(handler=RepoAuthHandler)), url(r'^api/repo/path/', Resource(handler=RepoPathHandler)), url(r'^api/repo/tags/', Resource(handler=RepoTagListHandler)), url(r'^competition/(?P<comp_slug>[\w-]+)/create-repo/$', CreateRepoView.as_view(), name='create_repo'), url(r'^competition/(?P<comp_slug>[\w-]+)/update-password/$', UpdatePasswordView.as_view(), name='update_repo_password'), url(r'^competition/(?P<comp_slug>[\w-]+)/submissions/$', ListSubmissionView.as_view(), name='list_submissions'), url(r'^competition/(?P<comp_slug>[\w-]+)/submit/(?P<sha>[a-f0-9]{40})/$', SubmitView.as_view(), name='submit'), url(r'^repo/', include('greta.repo_view_urls')), )
from django.conf.urls.defaults import patterns, url, include from piston.resource import Resource from .views import (CreateRepoView, UpdatePasswordView, ListSubmissionView, SubmitView) from .api_handlers import RepoAuthHandler, RepoPathHandler, RepoTagListHandler urlpatterns = patterns( "", url(r'^api/repo/auth/', Resource(handler=RepoAuthHandler)), url(r'^api/repo/path/', Resource(handler=RepoPathHandler)), url(r'^api/repo/tags/', Resource(handler=RepoTagListHandler)), url(r'^competition/(?P<comp_slug>[\w-]+)/create-repo/$', CreateRepoView.as_view(), name='create_repo'), url(r'^competition/(?P<comp_slug>[\w-]+)/update-password/$', UpdatePasswordView.as_view(), name='update_repo_password'), url(r'^competition/(?P<comp_slug>[\w-]+)/submissions/$', ListSubmissionView.as_view(), name='list_submissions'), url(r'^competition/(?P<comp_slug>[\w-]+)/submit/(?P<sha>[a-f0-9]{40})/$', SubmitView.as_view(), name='list_submissions'), url(r'^repo/', include('greta.repo_view_urls')), )
Handle queryset argument to get_object
from django.core.urlresolvers import reverse from django.views.generic import DetailView from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Section class SimpleSectionView(DetailView): context_object_name = 'section' model = Section def get_object(self, queryset=None): return self.get_section(queryset=queryset) def get_section(self, queryset=None): if queryset is None: queryset = self.get_queryset() return get_object_or_404(queryset, full_slug=self.kwargs['full_slug']) class SectionFeed(Feed): def __init__(self, section_view, *args, **kwargs): self.section_view = section_view def get_object(self, request, full_slug): return Section.objects.get(full_slug=full_slug) def title(self, section): return section.title def link(self, section): return reverse(self.section_view, kwargs={'full_slug': section.full_slug}) def description(self, section): return section.summary def items(self, section): return section.items
from django.core.urlresolvers import reverse from django.views.generic import DetailView from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from .models import Section class SimpleSectionView(DetailView): context_object_name = 'section' model = Section def get_object(self): return self.get_section() def get_section(self): return get_object_or_404(self.get_queryset(), full_slug=self.kwargs['full_slug']) class SectionFeed(Feed): def __init__(self, section_view, *args, **kwargs): self.section_view = section_view def get_object(self, request, full_slug): return Section.objects.get(full_slug=full_slug) def title(self, section): return section.title def link(self, section): return reverse(self.section_view, kwargs={'full_slug': section.full_slug}) def description(self, section): return section.summary def items(self, section): return section.items
Break lowdly on unicode errors
from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except S3CreateError as e: if e.status == 409: bucket = Bucket(conn, bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
from boto.s3.connection import S3Connection from boto.s3.bucket import Bucket from boto.exception import S3ResponseError, S3CreateError from django.conf import settings def upload(user, passwd, bucket, metadata, key, fd): conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False) while bucket.endswith('-'): bucket = bucket[:-1] try: bucket = conn.get_bucket(bucket) except S3ResponseError: try: bucket = conn.create_bucket(bucket, headers=metadata) except (S3ResponseError, UnicodeDecodeError): bucket = conn.create_bucket(bucket) except S3CreateError as e: if e.status == 409: bucket = Bucket(conn, bucket) key = bucket.new_key(key) try: key.set_contents_from_file(fd) except S3ResponseError: key.set_contents_from_file(fd) return key.generate_url(0).split('?')[0]
Add option to search for llamas
package ml.duncte123.skybot.commands.animals; import ml.duncte123.skybot.Command; import ml.duncte123.skybot.utils.AirUtils; import ml.duncte123.skybot.utils.URLConnectionReader; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import org.json.JSONArray; import org.json.JSONObject; public class LlamaCommand extends Command { @Override public boolean called(String[] args, GuildMessageReceivedEvent event) { return true; } @Override public void action(String[] args, GuildMessageReceivedEvent event) { try { String theLlama = (args.length<1 ? "random" : args[0]); String jsonString = URLConnectionReader.getText("https://lucoa.systemexit.co.uk/animals/api/llama/" + theLlama); JSONObject jsonObject = new JSONObject(jsonString); event.getChannel().sendMessage(AirUtils.embedImage(jsonObject.getString("file"))).queue(); } catch (Exception e) { e.printStackTrace(); event.getChannel().sendMessage(AirUtils.embedMessage("ERROR: " + e.getMessage())).queue(); } } @Override public String help() { return "Here is a llama"; } }
package ml.duncte123.skybot.commands.animals; import ml.duncte123.skybot.Command; import ml.duncte123.skybot.utils.AirUtils; import ml.duncte123.skybot.utils.URLConnectionReader; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import org.json.JSONArray; import org.json.JSONObject; public class LlamaCommand extends Command { @Override public boolean called(String[] args, GuildMessageReceivedEvent event) { return true; } @Override public void action(String[] args, GuildMessageReceivedEvent event) { try { String jsonString = URLConnectionReader.getText("https://lucoa.systemexit.co.uk/animals/api/llama/random"); JSONObject jsonObject = new JSONObject(jsonString); event.getChannel().sendMessage(AirUtils.embedImage(jsonObject.getString("file"))).queue(); } catch (Exception e) { e.printStackTrace(); event.getChannel().sendMessage(AirUtils.embedMessage("ERROR: " + e.getMessage())).queue(); } } @Override public String help() { return "Here is a llama"; } }
Fix arrayHelper move down when selector does not match
export const withUpdated = (arr, select, update) => ( arr.map(el => select(el) ? update(el) : el) ); export const withInsertedBefore = (arr, selectBefore, element) => { const reference = arr.findIndex(selectBefore); if (reference < 0) { return arr; } if (reference === 0) { return [element, ...arr]; } return [].concat( arr.slice(0, reference), element, arr.slice(reference, arr.length), ); }; export const moveUp = (arr, select) => { const pos = arr.findIndex(select); if (pos <= 0) { return arr; } return arr.map((el, idx) => { if (idx === pos - 1) { return arr[idx + 1]; } else if (idx === pos) { return arr[idx - 1] } else { return el; } }); }; export const moveDown = (arr, select) => { const pos = arr.findIndex(select); if (pos < 0 || pos >= arr.length - 1) { return arr; } return arr.map((el, idx) => { if (idx === pos + 1) { return arr[idx - 1]; } else if (idx === pos) { return arr[idx + 1] } else { return el; } }); };
export const withUpdated = (arr, select, update) => ( arr.map(el => select(el) ? update(el) : el) ); export const withInsertedBefore = (arr, selectBefore, element) => { const reference = arr.findIndex(selectBefore); if (reference < 0) { return arr; } if (reference === 0) { return [element, ...arr]; } return [].concat( arr.slice(0, reference), element, arr.slice(reference, arr.length), ); }; export const moveUp = (arr, select) => { const pos = arr.findIndex(select); if (pos <= 0) { return arr; } return arr.map((el, idx) => { if (idx === pos - 1) { return arr[idx + 1]; } else if (idx === pos) { return arr[idx - 1] } else { return el; } }); }; export const moveDown = (arr, select) => { const pos = arr.findIndex(select); if (pos < -1 || pos >= arr.length - 1) { return arr; } return arr.map((el, idx) => { if (idx === pos + 1) { return arr[idx - 1]; } else if (idx === pos) { return arr[idx + 1] } else { return el; } }); };
Add support for reading / writing uint8 from blocks (AKA a single byte, methods was introduced for consistency)
package dbio import ( "fmt" ) type DataBlock struct { ID uint16 Data []byte } func (db *DataBlock) ReadUint8(startingAt int) uint8 { return uint8(db.Data[startingAt]) } func (db *DataBlock) ReadUint16(startingAt int) uint16 { return DatablockByteOrder.Uint16(db.Data[startingAt : startingAt+2]) } func (db *DataBlock) ReadUint32(startingAt int) uint32 { return DatablockByteOrder.Uint32(db.Data[startingAt : startingAt+4]) } func (db *DataBlock) ReadString(startingAt, length int) string { return string(db.Data[startingAt : startingAt+length]) } func (db *DataBlock) Write(position int, v interface{}) { switch x := v.(type) { case uint8: db.Data[position] = x case []byte: lastPosition := position + len(x) i := 0 for target := position; target < lastPosition; target++ { db.Data[target] = x[i] i++ } case uint16: DatablockByteOrder.PutUint16(db.Data[position:position+2], x) case uint32: DatablockByteOrder.PutUint32(db.Data[position:position+4], x) default: panic(fmt.Sprintf("Don't know how to write %+v", x)) } }
package dbio import ( "fmt" ) type DataBlock struct { ID uint16 Data []byte } func (db *DataBlock) ReadUint16(startingAt int) uint16 { return DatablockByteOrder.Uint16(db.Data[startingAt : startingAt+2]) } func (db *DataBlock) ReadUint32(startingAt int) uint32 { return DatablockByteOrder.Uint32(db.Data[startingAt : startingAt+4]) } func (db *DataBlock) ReadString(startingAt, length int) string { return string(db.Data[startingAt : startingAt+length]) } func (db *DataBlock) Write(position int, v interface{}) { switch x := v.(type) { case []byte: lastPosition := position + len(x) i := 0 for target := position; target < lastPosition; target++ { db.Data[target] = x[i] i++ } case uint16: DatablockByteOrder.PutUint16(db.Data[position:position+2], x) case uint32: DatablockByteOrder.PutUint32(db.Data[position:position+4], x) default: panic(fmt.Sprintf("Don't know how to write %+v", x)) } }
:fire: Remove static folder from configs
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), assetsRoot: path.resolve(__dirname, '../dist'), assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, }
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
Fix the `User` not being loaded client side.
# -*- coding: utf-8 -*- import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): # NOTE: "user" won't work because it's a OneToOne field in DJango. # We need "user_id". See http://stackoverflow.com/a/15609667/654755 user_id = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
# -*- coding: utf-8 -*- import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
Remove vestigial (?) "woo" default for article slug and title fields.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_articles', '0001_initial'), ] operations = [ migrations.AddField( model_name='article', name='slug', field=models.SlugField(max_length=255), preserve_default=False, ), migrations.AddField( model_name='article', name='title', field=models.CharField(max_length=255), preserve_default=False, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('icekit_articles', '0001_initial'), ] operations = [ migrations.AddField( model_name='article', name='slug', field=models.SlugField(max_length=255, default='woo'), preserve_default=False, ), migrations.AddField( model_name='article', name='title', field=models.CharField(max_length=255, default='woo'), preserve_default=False, ), ]
Fix problem with system asking if you want to send empty answer This happens even tough you've written an answer. The problem was that we've made a change to how the text-value state is set. Previously it was set with the setState() function. However since text-value is the component's default state the updateVisual() function is called. This means that the element's value is reset. This caused in some browsers the caret to be reset to first position. Since the text-value is updated on keyup it caret was reset on every keyboard click. The idea was to solve this by setting the text-value directory in the state list. This then makes sure updateVisual() is not called. However the first commit did not make the proper change instead the change that was made caused the system to ask if the user wants to send an empty answer when the send button was clicked because it thought nothing had been entered in the text box.
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachKeyUpAction( self.node(), self.identifier() ); }; self.registerAction('keyup', function() { self._states['text-value'] = self.node().value; }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachKeyUpAction( self.node(), self.identifier() ); }; self.registerAction('keyup', function() { self.setState('text-value', self._states['text-value'] = self.node().value); }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
Define Timezone for Call Flow
<?php /* Access db of homer */ define(HOST, "localhost"); define(USER, "root"); define(PW, "root"); define(DB, "homer_users"); /* Homer connection * this user must have the same password for all Homer nodes * please define all your nodes in homer_nodes table */ define(HOMER_HOST, "localhost"); define(HOMER_USER, "homer_user"); define(HOMER_PW, "homer_password"); define(HOMER_DB, "homer_db"); define(HOMER_TABLE, "sip_capture"); /* Settings * Be shure, that you have the last version of text2pcap * text2pcap shall support -4 -6 IP headers * * Text2pcap: https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=5650 * Callflow: http://sourceforge.net/projects/callflow/ * */ define(PCAPDIR,"/var/www/html/webhomer/tmp/"); define(WEBPCAPLOC,"/webhomer/tmp/"); define(TEXT2PCAP,"/usr/sbin/text2pcap"); define(MERGECAP,"/usr/sbin/mergecap"); define(COLORTAG, 0); /* color based on callid, fromtag */ define(MODULES, 0); /* display modules in homepage flag */ define(CFLOW_CLEANUP, 1); /* Automatic Cleanup of old Cflow images */ define(CFLOW_TIMEZONE, "America/Los_Angeles"); /* Timezone that will display in Call Flow Ladder Diagram */ ?>
<?php /* Access db of homer */ define(HOST, "localhost"); define(USER, "root"); define(PW, "root"); define(DB, "homer_users"); /* Homer connection * this user must have the same password for all Homer nodes * please define all your nodes in homer_nodes table */ define(HOMER_HOST, "localhost"); define(HOMER_USER, "homer_user"); define(HOMER_PW, "homer_password"); define(HOMER_DB, "homer_db"); define(HOMER_TABLE, "sip_capture"); /* Settings * Be shure, that you have the last version of text2pcap * text2pcap shall support -4 -6 IP headers * * Text2pcap: https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=5650 * Callflow: http://sourceforge.net/projects/callflow/ * */ define(PCAPDIR,"/var/www/html/webhomer/tmp/"); define(WEBPCAPLOC,"/webhomer/tmp/"); define(TEXT2PCAP,"/usr/sbin/text2pcap"); define(MERGECAP,"/usr/sbin/mergecap"); define(COLORTAG, 0); /* color based on callid, fromtag */ define(MODULES, 0); /* display modules in homepage flag */ define(CFLOW_CLEANUP, 1); /* Automatic Cleanup of old Cflow images */ ?>
Add test for ISBN-10 checksum calculation
<?php require_once __DIR__ . '/../ISBN.class.php'; class testEuroTax extends PHPUnit_Framework_TestCase { protected $isbn; public function setUp() { $this->isbn = new ISBN('9782207258040'); } public function testIsValid() { $this->assertTrue($this->isbn->isValid()); } public function testIsNotValid() { $invalid = new ISBN('5780AAC728440'); $this->assertFalse($invalid->isValid()); } public function testFormatIsbn13() { $this->assertEquals($this->isbn->format('ISBN-13'), "978-2-207-25804-0"); } public function testFormatIsbn10() { $isbn10 = new ISBN('9783464603529'); $this->assertEquals($isbn10->format('ISBN-10'), "3-464-60352-0"); } }
<?php require_once __DIR__ . '/../ISBN.class.php'; class testEuroTax extends PHPUnit_Framework_TestCase { protected $isbn; public function setUp() { $this->isbn = new ISBN('9782207258040'); } public function testIsValid() { $this->assertTrue($this->isbn->isValid()); } public function testIsNotValid() { $invalid = new ISBN('5780AAC728440'); $this->assertFalse($invalid->isValid()); } public function testFormatIsbn13() { $this->assertEquals($this->isbn->format('ISBN-13'), "978-2-207-25804-0"); } public function testFormatIsbn10() { $this->assertEquals($this->isbn->format('ISBN-10'), "2-207-25804-1"); } }
Add temperature to cylinder constructor
package uk.co.craigwarren.gascalc.model; public class Cylinder { private double volume; private double pressure; private Gas gas; private double ambientTemperatureKelvin; public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } public double getPressure() { return pressure; } public void setPressure(double pressure) { this.pressure = pressure; } public Gas getGas() { return gas; } public void setGas(Gas gas) { this.gas = gas; } public Cylinder(double volume, double pressure, Gas gas, double tempKelvin) { if(tempKelvin == 0.0) { throw new IllegalArgumentException("Cannot mix gas at absolute zero"); } this.volume = volume; this.pressure = pressure; this.gas = gas; this.ambientTemperatureKelvin = tempKelvin; } public Cylinder(double volume, double pressure) { this(volume, pressure, Gas.air(), 20.0); } public Cylinder(double volume) { this(volume, 0); } public double getAmbientTemperatureKelvin() { return ambientTemperatureKelvin; } public void setAmbientTemperatureKelvin(double ambientTemperatureKelvin) { this.ambientTemperatureKelvin = ambientTemperatureKelvin; } }
package uk.co.craigwarren.gascalc.model; public class Cylinder { private double volume; private double pressure; private Gas gas; private double ambientTemperatureKelvin; public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } public double getPressure() { return pressure; } public void setPressure(double pressure) { this.pressure = pressure; } public Gas getGas() { return gas; } public void setGas(Gas gas) { this.gas = gas; } public Cylinder(double volume, double pressure, Gas gas) { this.volume = volume; this.pressure = pressure; this.gas = gas; } public Cylinder(double volume, double pressure) { this(volume, pressure, Gas.air()); } public Cylinder(double volume) { this(volume, 0); } public double getAmbientTemperatureKelvin() { return ambientTemperatureKelvin; } public void setAmbientTemperatureKelvin(double ambientTemperatureKelvin) { this.ambientTemperatureKelvin = ambientTemperatureKelvin; } }
Fix errors on create weekday
from django.core.exceptions import ValidationError import graphene from graphene_django import DjangoObjectType from app.timetables.models import Weekday from .utils import get_errors class WeekdayNode(DjangoObjectType): original_id = graphene.Int() class Meta: model = Weekday filter_fields = { 'name': ['icontains'] } filter_order_by = ['name', '-name'] interfaces = (graphene.relay.Node,) def resolve_original_id(self, args, context, info): return self.id class CreateWeekday(graphene.relay.ClientIDMutation): class Input: name = graphene.String(required=True) weekday = graphene.Field(WeekdayNode) errors = graphene.List(graphene.String) @classmethod def mutate_and_get_payload(cls, input, context, info): try: weekday = Weekday() weekday.name = input.get('name') weekday.full_clean() weekday.save() return CreateWeekday(weekday=weekday) except ValidationError as e: return CreateWeekday(weekday=None, errors=get_errors(e))
from django.core.exceptions import ValidationError import graphene from graphene_django import DjangoObjectType from app.timetables.models import Weekday from .utils import get_errors class WeekdayNode(DjangoObjectType): original_id = graphene.Int() class Meta: model = Weekday filter_fields = { 'name': ['icontains'] } filter_order_by = ['name', '-name'] interfaces = (graphene.relay.Node,) def resolve_original_id(self, args, context, info): return self.id class CreateWeekday(graphene.relay.ClientIDMutation): class Input: name = graphene.String(required=True) weekday = graphene.Field(WeekdayNode) errors = graphene.List(graphene.String) @classmethod def mutate_and_get_payload(cls, input, context, info): try: weekday = Weekday() weekday.name = input.get('name') weekday.full_clean() weekday.save() return Weekday(weekday=weekday) except ValidationError as e: return Weekday(weekday=None, errors=get_errors(e))
Fix variable name, add comment
/* @flow */ type GiftCategory = 'Electronics' | 'Games' | 'Home Decoration'; type GiftWish = string | Array<GiftCategory>; type User = { firstName: string, lastName?: string, giftWish?: GiftWish, }; export type Selection = { giver: User, receiver: User, }; const selectSecretSanta = ( users: Array<User>, // TODO: Think of adding restrictions as a parameter, such as: // - User X cannot give to User Y // - User A must give to User B // - User N only receives, doesn't give ): Array<Selection> => { const givers = [...users]; return users.map((receiver) => { // Possible givers only for this receiver (receiver cannot be his own giver) const receiverGivers = givers.filter(g => g !== receiver); const giver = receiverGivers[ Math.floor(Math.random() * receiverGivers.length) ]; // Take the selected giver out of the givers array givers.splice(givers.findIndex(g => g === giver), 1); return { giver, receiver, }; }); }; export default selectSecretSanta;
/* @flow */ type GiftCategory = 'Electronics' | 'Games' | 'Home Decoration'; type GiftWish = string | Array<GiftCategory>; type User = { firstName: string, lastName?: string, giftWish?: GiftWish, }; export type Selection = { giver: User, receiver: User, }; const selectSecretSanta = ( users: Array<User>, // TODO: Think of adding restrictions as a parameter, such as: // - User X cannot give to User Y // - User A must give to User B ): Array<Selection> => { const givers = [...users]; return users.map((receiver) => { // Possible givers only for this receiver (receiver cannot be his own giver) const receiverGivers = givers.filter(g => g !== receiver); const giver = receiverGiver[ Math.floor(Math.random() * receiverGiver.length) ]; // Take the selected giver out of the givers array givers.splice(givers.findIndex(g => g === giver), 1); return { giver, receiver, }; }); }; export default selectSecretSanta;
feat(quote-props): Add the `keywords: true` option Without it `{ 'boolean': 'xxx' }` fails. However, this is not valid JS.
module.exports = { rules: { 'quote-props': [2, 'as-needed', {keywords: true}], 'array-bracket-spacing': [2, 'never'], 'vars-on-top': 0, 'no-param-reassign': 0, 'max-len': [ 1, 110, 2, { "ignoreComments": true, "ignoreUrls": true } ], 'comma-dangle': [2, 'never'], 'no-use-before-define': [2, 'nofunc'], 'no-lonely-if': 2, 'handle-callback-err': 2, 'no-extra-parens': 2, 'no-path-concat': 1, 'func-style': [ 1, 'declaration' ], 'space-unary-ops': 2, 'no-mixed-requires': [ 2, true ], 'space-in-parens': [ 2, 'never' ], 'no-var': 0, 'prefer-const': 0, strict: [2, 'global'], 'object-curly-spacing': [2, 'never'], 'computed-property-spacing': [2, 'never'], 'func-names': 0, 'valid-jsdoc': [2, {requireReturnDescription: false}], 'id-length': 0 } };
module.exports = { rules: { 'quote-props': [2, 'as-needed'], 'array-bracket-spacing': [2, 'never'], 'vars-on-top': 0, 'no-param-reassign': 0, 'max-len': [ 1, 110, 2, { "ignoreComments": true, "ignoreUrls": true } ], 'comma-dangle': [2, 'never'], 'no-use-before-define': [2, 'nofunc'], 'no-lonely-if': 2, 'handle-callback-err': 2, 'no-extra-parens': 2, 'no-path-concat': 1, 'func-style': [ 1, 'declaration' ], 'space-unary-ops': 2, 'no-mixed-requires': [ 2, true ], 'space-in-parens': [ 2, 'never' ], 'no-var': 0, 'prefer-const': 0, strict: [2, 'global'], 'object-curly-spacing': [2, 'never'], 'computed-property-spacing': [2, 'never'], 'func-names': 0, 'valid-jsdoc': [2, {requireReturnDescription: false}], 'id-length': 0 } };