text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove props param to get current mobilization selector
import React, { PropTypes } from 'react' import { connect } from 'react-redux' // Global module dependencies import { SettingsPageLayout } from '../../../components/Layout' // Parent module dependencies import * as MobilizationSelectors from '../../mobilizations/selectors' // Current module dependencies import * as WidgetSelectors from '../selectors' export const SettingsContainer = ({ children, ...rest }) => ( <SettingsPageLayout> {children && React.cloneElement(children, {...rest})} </SettingsPageLayout> ) SettingsContainer.propTypes = { children: PropTypes.object, mobilization: PropTypes.object.isRequired, widget: PropTypes.object.isRequired, widgets: PropTypes.array.isRequired } const mapStateToProps = (state, props) => ({ mobilization: MobilizationSelectors.getCurrent(state), widget: WidgetSelectors.getWidget(state, props), widgets: WidgetSelectors.getList(state) }) export default connect(mapStateToProps)(SettingsContainer)
import React, { PropTypes } from 'react' import { connect } from 'react-redux' // Global module dependencies import { SettingsPageLayout } from '../../../components/Layout' // Parent module dependencies import * as MobilizationSelectors from '../../mobilizations/selectors' // Current module dependencies import * as WidgetSelectors from '../selectors' export const SettingsContainer = ({ children, ...rest }) => ( <SettingsPageLayout> {children && React.cloneElement(children, {...rest})} </SettingsPageLayout> ) SettingsContainer.propTypes = { children: PropTypes.object, mobilization: PropTypes.object.isRequired, widget: PropTypes.object.isRequired, widgets: PropTypes.array.isRequired } const mapStateToProps = (state, props) => ({ mobilization: MobilizationSelectors.getCurrent(state, props), widget: WidgetSelectors.getWidget(state, props), widgets: WidgetSelectors.getList(state) }) export default connect(mapStateToProps)(SettingsContainer)
Use kadira:blaze-layout version for Meteor 1.2. Use versin 2.1.0 of kadira:blaze-layout which adds missing jquery dependency that is required when using Meteor 1.2.
// Package metadata for Meteor.js web platform (https://www.meteor.com/) // This file is defined within the Meteor documentation at // // http://docs.meteor.com/#/full/packagejs // // and it is needed to define a Meteor package 'use strict'; Package.describe({ name: 'useraccounts:flow-routing', summary: 'UserAccounts package providing routes configuration capability via kadira:flow-router.', version: '1.12.3', git: 'https://github.com/meteor-useraccounts/flow-routing.git' }); Package.onUse(function(api) { api.versionsFrom('METEOR@1.0.3'); api.use([ 'check', 'kadira:blaze-layout', 'kadira:flow-router', 'underscore', 'useraccounts:core' ], ['client', 'server']); api.imply([ 'kadira:blaze-layout@2.1.0', 'kadira:flow-router@2.1.1', 'useraccounts:core@1.12.3' ], ['client', 'server']); api.addFiles([ 'lib/core.js', ], ['client', 'server']); api.addFiles([ 'lib/client/client.js', 'lib/client/templates_helpers/at_input.js' ], ['client']); });
// Package metadata for Meteor.js web platform (https://www.meteor.com/) // This file is defined within the Meteor documentation at // // http://docs.meteor.com/#/full/packagejs // // and it is needed to define a Meteor package 'use strict'; Package.describe({ name: 'useraccounts:flow-routing', summary: 'UserAccounts package providing routes configuration capability via kadira:flow-router.', version: '1.12.3', git: 'https://github.com/meteor-useraccounts/flow-routing.git' }); Package.onUse(function(api) { api.versionsFrom('METEOR@1.0.3'); api.use([ 'check', 'kadira:blaze-layout', 'kadira:flow-router', 'underscore', 'useraccounts:core' ], ['client', 'server']); api.imply([ 'kadira:blaze-layout@2.0.0', 'kadira:flow-router@2.1.1', 'useraccounts:core@1.12.3' ], ['client', 'server']); api.addFiles([ 'lib/core.js', ], ['client', 'server']); api.addFiles([ 'lib/client/client.js', 'lib/client/templates_helpers/at_input.js' ], ['client']); });
Fix typo on line 15
# Copyright (c) 2013 Tom McLoughlin import socket # Configuration myNick = "Bot" myIdent = "Bot" myReal = "Bot" myIRC = "irc.example.org" myPort = "6667" myChan = "#example" # only supports a single channel # Do not edit below this line socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(myIRC,myPort) socket.send( 'NICK ',myNick ) socket.send( 'USER ',myIdent, myIdent, myIdent' :',myReal'\r\n' ) socket.send( 'JOIN ',myChan ) # ok, now you can edit ^_^ while True: net = socket.recv ( 4096 ) if net.find ( 'PING' ) != -1: irc.send ( 'PONG ' + net.split() [ 1 ] + '\r\n' ) if net.find ( 'cookie' ) != -1: irc.send ( 'PRIVMSG ',myChan,' :mmmm cookies ;)\r\n' ) print net
# Copyright (c) 2013 Tom McLoughlin import socket # Configuration myNick = "Bot" myIdent = "Bot" myReal = "Bot" myIRC = "irc.example.org" myPort = "6667" myChan = "#example" # only supports a single channel # Do not edit below this line socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(myIRC,myPort) socket.send( 'NICK ',myNick )socket.send( 'USER ',myIdent, myIdent, myIdent' :',myReal'\r\n' ) socket.send( 'JOIN ',myChan ) # ok, now you can edit ^_^ while True: net = socket.recv ( 4096 ) if net.find ( 'PING' ) != -1: irc.send ( 'PONG ' + net.split() [ 1 ] + '\r\n' ) if net.find ( 'cookie' ) != -1: irc.send ( 'PRIVMSG ',myChan,' :mmmm cookies ;)\r\n' ) print net
Fix Facebook crawler crashing app when no cookies file provided
package crawlers.facebook; import org.apache.commons.io.IOUtils; import java.io.*; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import play.Logger; class FacebookSession { private static final String COOKIES_FILENAME = "/facebook_cookies"; private String cookies; FacebookSession() { InputStream secretsStream = getClass().getResourceAsStream(COOKIES_FILENAME); if (secretsStream == null) { Logger.warn("Cannot find Facebook cookies file " + COOKIES_FILENAME); return; } try { cookies = IOUtils.toString(secretsStream, "utf8").trim(); } catch (IOException e) { Logger.warn("Cannot open Facebook cookies file " + COOKIES_FILENAME); } } Connection getConnection(String uri) { Connection c = Jsoup.connect(uri); c.header("cookie", cookies); c.header("user-agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); return c; } Document getDocument(String uri) throws IOException { return getConnection(uri).execute().parse(); } }
package crawlers.facebook; import org.apache.commons.io.IOUtils; import java.io.*; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import play.Logger; class FacebookSession { private static final String COOKIES_FILENAME = "/facebook_cookies"; private String cookies; FacebookSession() { InputStream secretsStream = getClass().getResourceAsStream(COOKIES_FILENAME); try { cookies = IOUtils.toString(secretsStream, "utf8").trim(); } catch (IOException e) { Logger.warn("Cannot open Facebook cookies file " + COOKIES_FILENAME); } } Connection getConnection(String uri) { Connection c = Jsoup.connect(uri); c.header("cookie", cookies); c.header("user-agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); return c; } Document getDocument(String uri) throws IOException { return getConnection(uri).execute().parse(); } }
Hide hint button on click
// View BustinBash.Hints.View = function() {} BustinBash.Hints.View.prototype = { render: function(hint) { var source = $("#hints-template").html(); var template = Handlebars.compile(source); var context = {hint: hint} var text = template(context); $('.hints').html(text) }, hideHint: function(){ $('#hint').hide() } } // Controller BustinBash.Hints.Controller = function(view) { this.view = view; } BustinBash.Hints.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data }.bind(this)); $('#hint').on('click', function() { this.displayHint(this.data.Hint); }.bind(this)); }, displayHint: function(hint) { this.view.render(hint) this.view.hideHint() } }
// Model BustinBash.Hints.Model = function() {} // View BustinBash.Hints.View = function() {} BustinBash.Hints.View.prototype = { render: function(hint) { var source = $("#hints-template").html(); var template = Handlebars.compile(source); var context = {hint: hint} var text = template(context); $('.hints').html(text) } } // Controller BustinBash.Hints.Controller = function(view) { this.view = view; } BustinBash.Hints.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data }.bind(this)); $('#hint').on('click', function() { this.displayHint(this.data.Hint); }.bind(this)); }, displayHint: function(hint) { this.view.render(hint) } }
Add CopyToQuerySet to available imports
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.db import connection from .copy_from import CopyMapping from .copy_to import SQLCopyToCompiler, CopyToQuery __version__ = '2.0.0' class CopyQuerySet(models.QuerySet): """ Subclass of QuerySet that adds from_csv and to_csv methods. """ def from_csv(self, csv_path, mapping, **kwargs): """ Copy CSV file from the provided path to the current model using the provided mapping. """ mapping = CopyMapping(self.model, csv_path, mapping, **kwargs) mapping.save(silent=True) def to_csv(self, csv_path, *fields): """ Copy current QuerySet to CSV at provided path. """ query = self.query.clone(CopyToQuery) query.copy_to_fields = fields compiler = query.get_compiler(self.db, connection=connection) compiler.execute_sql(csv_path) CopyManager = models.Manager.from_queryset(CopyQuerySet) __all__ = ( 'CopyManager', 'CopyMapping', 'CopyToQuery', 'CopyToQuerySet', 'SQLCopyToCompiler', )
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.db import connection from .copy_from import CopyMapping from .copy_to import SQLCopyToCompiler, CopyToQuery __version__ = '2.0.0' class CopyQuerySet(models.QuerySet): """ Subclass of QuerySet that adds from_csv and to_csv methods. """ def from_csv(self, csv_path, mapping, **kwargs): """ Copy CSV file from the provided path to the current model using the provided mapping. """ mapping = CopyMapping(self.model, csv_path, mapping, **kwargs) mapping.save(silent=True) def to_csv(self, csv_path, *fields): """ Copy current QuerySet to CSV at provided path. """ query = self.query.clone(CopyToQuery) query.copy_to_fields = fields compiler = query.get_compiler(self.db, connection=connection) compiler.execute_sql(csv_path) CopyManager = models.Manager.from_queryset(CopyQuerySet) __all__ = ( 'CopyMapping', 'SQLCopyToCompiler', 'CopyToQuery', 'CopyManager', )
Fix test so that is uses regex to check the text returned.
/* jshint -W117, -W030 */ describe('dataservice', function() { beforeEach(function() { bard.appModule('app.core'); bard.inject('$http','$httpBackend','$q','dataservice','$rootScope'); }); it('exists' , function(){ expect(dataservice).to.exist; }); it('getMessageCount returns a value' , function() { dataservice.getMessageCount().then(function(data) { expect(data).to.exist; }); $rootScope.$apply(); }); it('getPeople hits the right /api/people' , function() { $httpBackend.when('GET', '/api/people').respond(200,[{}]); dataservice.getPeople().then(function(data) { expect(data).to.exist; }); $httpBackend.flush(); }); it('getPeople reports error if server fails' , function() { $httpBackend .when('GET', '/api/people') .respond(500,{description: 'you fail'}); dataservice.getPeople().catch(function(error) { expect(error.data.description).to.match(/you fail/); }); $httpBackend.flush(); }); });
/* jshint -W117, -W030 */ describe('dataservice', function() { beforeEach(function() { bard.appModule('app.core'); bard.inject('$http','$httpBackend','$q','dataservice','$rootScope'); }); it('exists' , function(){ expect(dataservice).to.exist; }); it('getMessageCount returns a value' , function() { dataservice.getMessageCount().then(function(data) { expect(data).to.exist; }); $rootScope.$apply(); }); it('getPeople hits the right /api/people' , function() { $httpBackend.when('GET', '/api/people').respond(200,[{}]); dataservice.getPeople().then(function(data) { expect(data).to.exist; }); $httpBackend.flush(); }); it('getPeople reports error if server fails' , function() { $httpBackend .when('GET', '/api/people') .respond(500,{data: {description: 'you fail'}}); dataservice.getPeople().catch(function(error) { expect(true).to.be.false; }); $httpBackend.flush(); }); });
Fix signature of test case
from hypothesis_auto import auto_pytest_magic from isort import parse from isort.settings import Config TEST_CONTENTS = """ import xyz import abc def function(): pass """ def test_file_contents(): ( in_lines, out_lines, import_index, place_imports, import_placements, as_map, imports, categorized_comments, change_count, original_line_count, line_separator, sections, section_comments, ) = parse.file_contents(TEST_CONTENTS, config=Config()) assert "\n".join(in_lines) == TEST_CONTENTS assert "import" not in "\n".join(out_lines) assert import_index == 1 assert change_count == -2 assert original_line_count == len(in_lines) auto_pytest_magic(parse.import_type) auto_pytest_magic(parse.skip_line) auto_pytest_magic(parse._strip_syntax) auto_pytest_magic(parse._infer_line_separator)
from hypothesis_auto import auto_pytest_magic from isort import parse from isort.settings import Config TEST_CONTENTS = """ import xyz import abc def function(): pass """ def test_file_contents(): ( in_lines, out_lines, import_index, place_imports, import_placements, as_map, imports, categorized_comments, first_comment_index_start, first_comment_index_end, change_count, original_line_count, line_separator, sections, section_comments, ) = parse.file_contents(TEST_CONTENTS, config=Config()) assert "\n".join(in_lines) == TEST_CONTENTS assert "import" not in "\n".join(out_lines) assert import_index == 1 assert change_count == -2 assert original_line_count == len(in_lines) auto_pytest_magic(parse.import_type) auto_pytest_magic(parse.skip_line) auto_pytest_magic(parse._strip_syntax) auto_pytest_magic(parse._infer_line_separator)
Add another example of a line that is thicker
package main import ( "../../../drawer" "fmt" "image" "image/color" "image/png" "os" ) func main() { src := image.NewRGBA(image.Rect(0, 0, 100, 100)) drawer.Fill(src, color.RGBA{0, 255, 255, 255}) ld := drawer.NewLineDrawer(src, image.Pt(100, 100), image.Pt(0, 0), color.RGBA{255, 0, 0, 255}).Draw() draw(ld, src, "negative.png") ld.SetStart(image.Pt(0, 100)).SetEnd(image.Pt(100, 0)).Draw() draw(ld, src, "positive.png") ld.SetStart(image.Pt(0, 50)).SetEnd(image.Pt(100, 50)).SetThickness(5).Draw() draw(ld, src, "thick.png") } func draw(drawer *drawer.LineDrawer, src image.Image, filename string) { out, err := os.Create(filename) if err != nil { fmt.Println(err) os.Exit(1) } defer out.Close() fmt.Println("Writing output to:", filename) err = png.Encode(out, src) if err != nil { fmt.Println(err) os.Exit(1) } }
package main import ( "../../../drawer" "fmt" "image" "image/color" "image/png" "os" ) func main() { src := image.NewRGBA(image.Rect(0, 0, 100, 100)) drawer.Fill(src, color.RGBA{0, 255, 255, 255}) start := image.Pt(100, 100) end := image.Pt(0, 0) ld := drawer.NewLineDrawer(src, start, end, color.RGBA{255, 0, 0, 255}).Draw() draw(ld, src, "negative.png") start = image.Pt(0, 100) end = image.Pt(100, 0) ld.SetStart(end).SetEnd(start).Draw() draw(ld, src, "positive.png") } func draw(drawer *drawer.LineDrawer, src image.Image, filename string) { out, err := os.Create(filename) if err != nil { fmt.Println(err) os.Exit(1) } defer out.Close() fmt.Println("Writing output to:", filename) err = png.Encode(out, src) if err != nil { fmt.Println(err) os.Exit(1) } }
Fix merge conflict with origin branch
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { // get the first character return this.replace(/^[a-z]/g, function(item, position, string) { return item.toUpper(); }); };
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { // get the first character return this.replace(/^[a-z]/g, function(item, position, string) { return item.toUpper(); }); };
Make the screen scroll less frequently …it's a bit intense
(function(GOVUK, GDM) { var $page = $("html, body"), delayInSeconds = 16, generateScrollTo = function($sections, index) { return function() { scrollPage($sections.eq(index).offset().top); setTimeout( generateScrollTo( $sections, (index + 1 == $sections.length) ? 0 : ++index ), delayInSeconds * 1000 ); }; }, scrollPage = function(offset) { $page.animate({ scrollTop: offset }); }; GOVUK.GDM.scrollThroughStatistics = function() { if (!$("#framework-statistics-big-screen").length) return; setTimeout(function() { location.reload(); }, 60 * 60 * 1000); // 1 hour generateScrollTo( $("#framework-statistics-big-screen .summary-item-heading"), 0 )(); }; }).apply(this, [GOVUK||{}, GOVUK.GDM||{}]);
(function(GOVUK, GDM) { var $page = $("html, body"), delayInSeconds = 8, generateScrollTo = function($sections, index) { return function() { scrollPage($sections.eq(index).offset().top); setTimeout( generateScrollTo( $sections, (index + 1 == $sections.length) ? 0 : ++index ), delayInSeconds * 1000 ); }; }, scrollPage = function(offset) { $page.animate({ scrollTop: offset }); }; GOVUK.GDM.scrollThroughStatistics = function() { if (!$("#framework-statistics-big-screen").length) return; setTimeout(function() { location.reload(); }, 60 * 60 * 1000); // 1 hour generateScrollTo( $("#framework-statistics-big-screen .summary-item-heading"), 0 )(); }; }).apply(this, [GOVUK||{}, GOVUK.GDM||{}]);
Reduce location cutoff and make it in seconds. Avoids issues with out of date locations.
<?php use Carbon\Carbon; class CharacterLocation { public $character_id; public $system_id; public $updated_at; public function __construct($props) { foreach ($props as $key => $value) { $this->$key = $value; } } public static function find(int $id) { $data = DB::query(Database::SELECT, 'SELECT * FROM character_location WHERE character_id=:id') ->param(':id', $id) ->execute() ->current(); if($data != null) { return new CharacterLocation($data); } return null; } public static function findWithinCutoff(int $id, int $cutOffSeconds = 15) { $cutoff = Carbon::now()->subSeconds($cutOffSeconds)->toDateTimeString(); $data = DB::query(Database::SELECT, 'SELECT * FROM character_location WHERE character_id=:id AND updated_at >= :cutoff') ->param(':id', $id) ->param(':cutoff', $cutoff) ->execute() ->current(); if($data != null) { return new CharacterLocation($data); } return null; } }
<?php use Carbon\Carbon; class CharacterLocation { public $character_id; public $system_id; public $updated_at; public function __construct($props) { foreach ($props as $key => $value) { $this->$key = $value; } } public static function find(int $id) { $data = DB::query(Database::SELECT, 'SELECT * FROM character_location WHERE character_id=:id') ->param(':id', $id) ->execute() ->current(); if($data != null) { return new CharacterLocation($data); } return null; } public static function findWithinCutoff(int $id, int $cutoffTimeMins = 1) { $cutoff = Carbon::now()->subMinutes($cutoffTimeMins)->toDateTimeString(); $data = DB::query(Database::SELECT, 'SELECT * FROM character_location WHERE character_id=:id AND updated_at >= :cutoff') ->param(':id', $id) ->param(':cutoff', $cutoff) ->execute() ->current(); if($data != null) { return new CharacterLocation($data); } return null; } }
Add missing include, and switch to exclude projects with HIDDEN status from public display
# This file is part of the FragDev Website. # # the FragDev Website is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # the FragDev Website is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>. from django.http import Http404, HttpResponse from django.shortcuts import render from django.template import loader from .models import Project def index(request): ''' Project listing ''' projects = Project.objects.exclude(status=Project.HIDDEN).order_by('-date') template = loader.get_template('projects/page-index.html') return HttpResponse(template.render({'projects': projects})) def project(request, slug): ''' Display project details ''' try: project = Project.objects.exclude(status=Project.HIDDEN).get(slug=slug) except ObjectDoesNotExist: raise Http404('Project {} does not exist' % slug) template = loader.get_template('projects/page-project.html') return HttpResponse(template.render({'project': project}))
# This file is part of the FragDev Website. # # the FragDev Website is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # the FragDev Website is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>. from django.http import Http404 from django.shortcuts import render from django.template import loader from .models import Project def index(request): ''' Project listing ''' projects = Project.objects.filter(status=Project.PUBLIC).order_by('-date') template = loader.get_template('projects/page-index.html') return HttpResponse(template.render({'projects': projects})) def project(request, slug): ''' Display project details ''' try: project = Project.objects.get(slug=slug,status=Project.PUBLIC) except ObjectDoesNotExist: raise Http404('Project {} does not exist' % slug) template = loader.get_template('projects/page-project.html') return HttpResponse(template.render({'project': project}))
Make test method name understandable
<?php namespace MS\PHPMD\Tests\Functional\CleanCode; use MS\PHPMD\Tests\Functional\AbstractProcessTest; /** * Class SuperfluousCommentTest * * @package MS\PHPMD\Tests\Functional\CleanCode */ class SuperfluousCommentTest extends AbstractProcessTest { /** * @covers MS\PHPMD\Rule\CleanCode\SuperfluousComment */ public function testSuperfluousCommentRule() { $output = $this ->runPhpmd('Service/SuperfluousComment.php', 'cleancode.xml') ->getOutput(); $this->assertNotContains('SuperfluousComment.php:42 It seems', $output); $this->assertContains('SuperfluousComment.php:10 It seems that the class has a superfluous comment description. It fits 88 percent with the name of that.', $output); $this->assertContains('SuperfluousComment.php:10 It seems that the property $name has a superfluous comment description. It fits 73 percent with the name of that.', $output); $this->assertContains('SuperfluousComment.php:24 It seems that the method has a superfluous comment description. It fits 100 percent with the name of that.', $output); $this->assertContains('SuperfluousComment.php:34 It seems that the method has a superfluous comment description. It fits 82 percent with the name of that.', $output); } }
<?php namespace MS\PHPMD\Tests\Functional\CleanCode; use MS\PHPMD\Tests\Functional\AbstractProcessTest; /** * Class SuperfluousCommentTest * * @package MS\PHPMD\Tests\Functional\CleanCode */ class SuperfluousCommentTest extends AbstractProcessTest { /** * @covers MS\PHPMD\Rule\CleanCode\SuperfluousComment */ public function testRule() { $output = $this ->runPhpmd('Service/SuperfluousComment.php', 'cleancode.xml') ->getOutput(); $this->assertNotContains('SuperfluousComment.php:42', $output); $this->assertContains('SuperfluousComment.php:10 It seems that the class has a superfluous comment description. It fits 88 percent with the name of that.', $output); $this->assertContains('SuperfluousComment.php:10 It seems that the property $name has a superfluous comment description. It fits 73 percent with the name of that.', $output); $this->assertContains('SuperfluousComment.php:24 It seems that the method has a superfluous comment description. It fits 100 percent with the name of that.', $output); $this->assertContains('SuperfluousComment.php:34 It seems that the method has a superfluous comment description. It fits 82 percent with the name of that.', $output); } }
Make it possible to define other values for the headers X-Frame-Options, X-XSS-Protection, X-Content-Type-Options if you realy want to The current implementation uses an iframe this change makes it possible to use that again
<?php namespace Common\EventListener; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; class ResponseSecurer { /** * Add some headers to the response to make our application more secure * see https://www.owasp.org/index.php/List_of_useful_HTTP_headers * * @param FilterResponseEvent $event */ public function onKernelResponse(FilterResponseEvent $event) { $headers = [ 'X-Frame-Options' => 'deny', 'X-XSS-Protection' => '1; mode=block', 'X-Content-Type-Options' => 'nosniff', ]; foreach ($headers as $header => $value) { if (!$event->getResponse()->headers->has($header)) { $event->getResponse()->headers->set($header, $value); } } } }
<?php namespace Common\EventListener; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; class ResponseSecurer { /** * Add some headers to the response to make our application more secure * see https://www.owasp.org/index.php/List_of_useful_HTTP_headers * * @param FilterResponseEvent $event */ public function onKernelResponse(FilterResponseEvent $event) { // provides clickjacking protection $event->getResponse()->headers->set('X-Frame-Options', 'deny'); // enables the XSS filter built into most recent browsers $event->getResponse()->headers->set('X-XSS-Protection', '1; mode=block'); // prevents IE and Chrome from MIME-sniffing $event->getResponse()->headers->set('X-Content-Type-Options', 'nosniff'); } }
Rename the test on watcher API to have something more specific
describe('using the watcher API to dispose and watch again', function() { require('./fixtures/bootstrap.js'); beforeEach(h.clean); afterEach(h.clean); var visible = false; var element; var watcher; beforeEach(function(done) { element = h.createTest({ style: { top: '10000px' } }); h.insertTest(element); watcher = inViewport(element, function() { scrolled = true; done(); }); }); describe('when the watcher is not active', function() { beforeEach(watcher.dispose()); beforeEach(h.scroller(0, 10000)); beforeEach(h.scroller(0, 0)); it('cb not called', function() { assert.strictEqual(calls.length, 0); }); }); describe('when the watcher is active', function() { beforeEach(watcher.watch()); beforeEach(h.scroller(0, 10000)); beforeEach(h.scroller(0, 0)); it('cb called', function() { assert.strictEqual(calls.length, 1); }); }); });
describe('asking if a visible div scrolled', function() { require('./fixtures/bootstrap.js'); beforeEach(h.clean); afterEach(h.clean); var visible = false; var element; var watcher; beforeEach(function(done) { element = h.createTest({ style: { top: '10000px' } }); h.insertTest(element); watcher = inViewport(element, function() { scrolled = true; done(); }); }); describe('when the watcher is not active', function() { beforeEach(watcher.dispose()); beforeEach(h.scroller(0, 10000)); beforeEach(h.scroller(0, 0)); it('cb not called', function() { assert.strictEqual(calls.length, 0); }); }); describe('when the watcher is active', function() { beforeEach(watcher.watch()); beforeEach(h.scroller(0, 10000)); beforeEach(h.scroller(0, 0)); it('cb called', function() { assert.strictEqual(calls.length, 1); }); }); });
Change parameter names in acquire. Add some doc.
# -*- encoding: utf-8 -*- import os import fcntl class FileLock(object): def __init__(self, fd): # the fd is borrowed, so do not close it self.fd = fd def acquire(self, ex=False, nb=True): """ Acquire a lock on the fd. :param ex (optional): default False, acquire a exclusive lock if True :param nb (optional): default True, non blocking if True :return: True if acquired """ try: lock_flags = fcntl.LOCK_EX if ex else fcntl.LOCK_SH if nb: lock_flags |= fcntl.LOCK_NB fcntl.flock(self.fd, lock_flags) return True except IOError: return False def release(self): """ Release lock on the fd. """ fcntl.flock(self.fd, fcntl.LOCK_UN)
# -*- encoding: utf-8 -*- import os import fcntl class FileLock(object): def __init__(self, fd): # the fd is borrowed, so do not close it self.fd = fd def acquire(self, write=False, block=False): try: lock_flags = fcntl.LOCK_EX if write else fcntl.LOCK_SH if not block: lock_flags |= fcntl.LOCK_NB fcntl.flock(self.fd, lock_flags) return True except IOError: return False def release(self): fcntl.flock(self.fd, fcntl.LOCK_UN)
Make sure the tumblr url fixer is location implementation agnostic
App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); App.ArrayTransform = App.RawTransform.extend({}); App.TimestampTransform = DS.NumberTransform.extend({}); App.ChoiceTransform = DS.StringTransform.extend(); App.TumblrStringTransform = DS.StringTransform.extend({ deserialize: function(serialized){ 'use strict'; var deserialized = this._super(serialized), self = this, router = this.container.lookup('router:main'), url; // return if null if (Ember.isNone(deserialized)) return null; // reformat tumblr urls appropriately return deserialized.replace(/href="http:\/\/([^\.]*).tumblr.com\/([^"]*)"/g, function(orig, blog_name, path, idx, full){ url = router.router.recognizer.generate('single_blog', {blog_name: blog_name}); url = router.get('location').formatURL(url); if (url.charAt(0) !== '/') { url = '/' + url; } return 'href="%@"'.fmt(url); }); } });
App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); App.ArrayTransform = App.RawTransform.extend({}); App.TimestampTransform = DS.NumberTransform.extend({}); App.ChoiceTransform = DS.StringTransform.extend(); App.TumblrStringTransform = DS.StringTransform.extend({ deserialize: function(serialized){ 'use strict'; var deserialized = this._super(serialized), self = this, url; // return if null if (Ember.isNone(deserialized)) return null; // reformat tumblr urls appropriately return deserialized.replace(/http:\/\/([^\.]*.tumblr.com)/g, function(orig, s){ url = /([^\.]*).*/g.exec(s); return Em.isNone(url) ? s : '/#/blog/%@'.fmt(url[1]); }); } });
Add new line in the end of the file
import networkx as nx class ConnectedComponents: """This is a class for connected component detection method to cluster event logs [1]_. .. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log clustering, in Proceedings of the International Seminar on Science and Technology, 2016, pp. 495-496. """ def __init__(self, g): """This is a constructor for ConnectedComponent class Parameters ---------- g : graph a graph to be clustered """ self.g = g def get_clusters(self): """This method find any connected component in a graph. A component represents a cluster and each component will be given a cluster identifier. Returns ------- clusters : list[list] List of cluster list, where each list contains index (line number) of event log. """ clusters = [] for components in nx.connected_components(self.g): clusters.append(components) cluster_id = 0 for cluster in clusters: for node in cluster: self.g.node[node]['cluster'] = cluster_id cluster_id += 1 return clusters
import networkx as nx class ConnectedComponents: """This is a class for connected component detection method to cluster event logs [1]_. .. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log clustering, in Proceedings of the International Seminar on Science and Technology, 2016, pp. 495-496. """ def __init__(self, g): """This is a constructor for ConnectedComponent class Parameters ---------- g : graph a graph to be clustered """ self.g = g def get_clusters(self): """This method find any connected component in a graph. A component represents a cluster and each component will be given a cluster identifier. Returns ------- clusters : list[list] List of cluster list, where each list contains index (line number) of event log. """ clusters = [] for components in nx.connected_components(self.g): clusters.append(components) cluster_id = 0 for cluster in clusters: for node in cluster: self.g.node[node]['cluster'] = cluster_id cluster_id += 1 return clusters
Update check to look for presence, not equality (order unnecessary)
import chai from 'chai'; import irc from 'irc'; import discord from 'discord.js'; import Bot from '../lib/bot'; import config from './fixtures/single-test-config.json'; import caseConfig from './fixtures/case-sensitivity-config.json'; import DiscordStub from './stubs/discord-stub'; import ClientStub from './stubs/irc-client-stub'; import { validateChannelMapping } from '../lib/validators'; chai.should(); describe('Channel Mapping', () => { before(() => { irc.Client = ClientStub; discord.Client = DiscordStub; }); it('should fail when not given proper JSON', () => { const wrongMapping = 'not json'; function wrap() { validateChannelMapping(wrongMapping); } (wrap).should.throw('Invalid channel mapping given'); }); it('should not fail if given a proper channel list as JSON', () => { const correctMapping = { '#channel': '#otherchannel' }; function wrap() { validateChannelMapping(correctMapping); } (wrap).should.not.throw(); }); it('should clear channel keys from the mapping', () => { const bot = new Bot(config); bot.channelMapping['#discord'].should.equal('#irc'); bot.invertedMapping['#irc'].should.equal('#discord'); bot.channels.should.contain('#irc channelKey'); }); it('should lowercase IRC channel names', () => { const bot = new Bot(caseConfig); bot.channelMapping['#discord'].should.equal('#irc'); bot.channelMapping['#otherDiscord'].should.equal('#otherirc'); }); });
import chai from 'chai'; import irc from 'irc'; import discord from 'discord.js'; import Bot from '../lib/bot'; import config from './fixtures/single-test-config.json'; import caseConfig from './fixtures/case-sensitivity-config.json'; import DiscordStub from './stubs/discord-stub'; import ClientStub from './stubs/irc-client-stub'; import { validateChannelMapping } from '../lib/validators'; chai.should(); describe('Channel Mapping', () => { before(() => { irc.Client = ClientStub; discord.Client = DiscordStub; }); it('should fail when not given proper JSON', () => { const wrongMapping = 'not json'; function wrap() { validateChannelMapping(wrongMapping); } (wrap).should.throw('Invalid channel mapping given'); }); it('should not fail if given a proper channel list as JSON', () => { const correctMapping = { '#channel': '#otherchannel' }; function wrap() { validateChannelMapping(correctMapping); } (wrap).should.not.throw(); }); it('should clear channel keys from the mapping', () => { const bot = new Bot(config); bot.channelMapping['#discord'].should.equal('#irc'); bot.invertedMapping['#irc'].should.equal('#discord'); bot.channels[0].should.equal('#irc channelKey'); }); it('should lowercase IRC channel names', () => { const bot = new Bot(caseConfig); bot.channelMapping['#discord'].should.equal('#irc'); bot.channelMapping['#otherDiscord'].should.equal('#otherirc'); }); });
Add a couple more items to the default whitelist.
const DEFAULT_WHITELISTED_URL_REGEXPS = [ 'abcnews.go.com\/.+', 'arstechnica.com\/.+', 'bbc.co.uk\/.+', 'bbc.com\/.+', 'business-standard.com\/.+', 'cnn.com\/.+', 'economist.com\/.+', 'forbes.com\/.+', 'guardian.co.uk\/.+', 'hollywoodreporter.com\/.+', 'huffingtonpost.com\/.+', 'independent.co.uk\/.+', 'irishtimes.com\/.+', 'newsweek.com\/.+', 'newyorker.com\/.+', 'npr.org\/.+', 'nytimes.com\/.+', 'politico.com\/.+', 'rollingstone.com\/.+', 'spiegel.de\/.+', 'theatlantic.com\/.+', 'theguardian.com\/.+', 'time.com\/.+', 'variety.com\/.+', 'washingtonpost.com\/.+', 'wired.com\/.+', 'wsj.com\/.+', ]; function saveURLsWhitelist(whitelist) { localStorage.setItem('urls-whitelist', JSON.stringify(whitelist)); } function loadURLsWhitelist() { let whitelist = localStorage.getItem('urls-whitelist'); if (whitelist) { return JSON.parse(whitelist); } return DEFAULT_WHITELISTED_URL_REGEXPS; }
const DEFAULT_WHITELISTED_URL_REGEXPS = [ 'abcnews.go.com\/.+', 'arstechnica.com\/.+', 'bbc.co.uk\/.+', 'bbc.com\/.+', 'business-standard.com\/.+', 'cnn.com\/.+', 'economist.com\/.+', 'guardian.co.uk\/.+', 'theguardian.com\/.+', 'hollywoodreporter.com\/.+', 'huffingtonpost.com\/.+', 'irishtimes.com\/.+', 'independent.co.uk\/.+', 'npr.org\/.+', 'newsweek.com\/.+', 'nytimes.com\/.+', 'politico.com\/.+', 'rollingstone.com\/.+', 'spiegel.de\/.+', 'time.com\/.+', 'theatlantic.com\/.+', 'variety.com\/.+', 'washingtonpost.com\/.+', 'wired.com\/.+', 'wsj.com\/.+', ]; function saveURLsWhitelist(whitelist) { localStorage.setItem('urls-whitelist', JSON.stringify(whitelist)); } function loadURLsWhitelist() { let whitelist = localStorage.getItem('urls-whitelist'); if (whitelist) { return JSON.parse(whitelist); } return DEFAULT_WHITELISTED_URL_REGEXPS; }
Test console method and revert to log if method not present. Handles node environment
/** * Project: LekkerApps - Logging * Copyright 2016 Ashley G Ramdass <agramdass@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export class ConsoleAppender { get trace() { return console.trace || console.log; } get debug() { return console.debug || console.log; } get info() { return console.info || console.log; } get warn() { return console.warn || console.log; } get error() { return console.error || console.log; } get binding() { return console; } } const appender = new ConsoleAppender(); export default appender;
/** * Project: LekkerApps - Logging * Copyright 2016 Ashley G Ramdass <agramdass@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export class ConsoleAppender { get trace() { return console.trace; } get debug() { return console.debug; } get info() { return console.info; } get warn() { return console.warn; } get error() { return console.error; } get binding() { return console; } } const appender = new ConsoleAppender(); export default appender;
Put example code in comment block.
// Made by Tim Caswell, https://gist.github.com/creationix/bb1474fd018076862c6b module.exports = asyncMap; // This will loop through an array calling fn(item, callback) for each item. // It assumes that the callback will always be called eventually with (err) or (null, value) // Once all the callbacks have been called, the outer callback will be called with (error, results) // where `error` is the last error to occur (if any) // and `results` is the mapped results of the initial array. function asyncMap(array, fn, callback) { var left = array.length; var results = new Array(left); var error; // Handle case of empty array if (!left) return callback(error, results); // Run all commands in parallel and wait for results. array.forEach(function (item, i) { fn(item, function (err, result) { if (err) error = err; else results[i] = result; if (!--left) callback(error, results); }); }); } /* // Usage example and test, not part of library asyncMap([1,2,3,4,5], function (num, callback) { setTimeout(function () { callback(null, num); }, Math.random() * 100); }, function (err, results) { if (err) throw err; console.log(results); }); */
// Made by Tim Caswell, https://gist.github.com/creationix/bb1474fd018076862c6b module.exports = asyncMap; // This will loop through an array calling fn(item, callback) for each item. // It assumes that the callback will always be called eventually with (err) or (null, value) // Once all the callbacks have been called, the outer callback will be called with (error, results) // where `error` is the last error to occur (if any) // and `results` is the mapped results of the initial array. function asyncMap(array, fn, callback) { var left = array.length; var results = new Array(left); var error; // Handle case of empty array if (!left) return callback(error, results); // Run all commands in parallel and wait for results. array.forEach(function (item, i) { fn(item, function (err, result) { if (err) error = err; else results[i] = result; if (!--left) callback(error, results); }); }); } // Usage example and test, not part of library asyncMap([1,2,3,4,5], function (num, callback) { setTimeout(function () { callback(null, num); }, Math.random() * 100); }, function (err, results) { if (err) throw err; console.log(results); });
Change 'goodbye' handler to use proper exit methodology. System.exit() works but is less graceful than asking the server to stop.
package com.deweysasser.example.webserver; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; /** Serve up a basic Hello World page * * @author Dewey Sasser * */ public class GoodbyePage implements HttpHandler { @Override public void handle(HttpExchange req) throws IOException { String response = "<html><h1>Goodbye Cruel World</h1>What a world<br/>What a world...</html>"; req.sendResponseHeaders(200, response.length()); OutputStream os = req.getResponseBody(); os.write(response.getBytes()); os.close(); req.getHttpContext().getServer().stop(0); } }
package com.deweysasser.example.webserver; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; /** Serve up a basic Hello World page * * @author Dewey Sasser * */ public class GoodbyePage implements HttpHandler { @Override public void handle(HttpExchange req) throws IOException { String response = "<html><h1>Goodbye Cruel World</h1>What a world<br/>What a world...</html>"; req.sendResponseHeaders(200, response.length()); OutputStream os = req.getResponseBody(); os.write(response.getBytes()); os.close(); System.exit(0); } }
chore: Add attrs as project requirement
from setuptools import setup setup( name='xwing', version='0.0.1.dev0', url='https://github.com/victorpoluceno/xwing', license='ISC', description='Xwing is a Python library writen using that help ' 'to distribute connect to a single port to other process', author='Victor Poluceno', author_email='victorpoluceno@gmail.com', packages=['xwing'], setup_requires=['pytest-runner'], tests_require=['pytest'], install_requires=['attrs==16.2.0'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Distributed Computing', 'Topic :: System :: Networking', ], scripts=['bin/xwing'] )
from setuptools import setup setup( name='xwing', version='0.0.1.dev0', url='https://github.com/victorpoluceno/xwing', license='ISC', description='Xwing is a Python library writen using that help ' 'to distribute connect to a single port to other process', author='Victor Poluceno', author_email='victorpoluceno@gmail.com', packages=['xwing'], setup_requires=['pytest-runner'], tests_require=['pytest'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Distributed Computing', 'Topic :: System :: Networking', ], scripts=['bin/xwing'] )
Fix build with newer dependencies.
from distutils.core import setup ext_files = ["pyreBloom/bloom.c"] kwargs = {} try: from Cython.Distutils import build_ext from Cython.Distutils import Extension print "Building from Cython" ext_files.append("pyreBloom/pyreBloom.pyx") kwargs['cmdclass'] = {'build_ext': build_ext} except ImportError: from distutils.core import Extension ext_files.append("pyreBloom/pyreBloom.c") print "Building from C" ext_modules = [Extension("pyreBloom", ext_files, libraries=['hiredis'], library_dirs=['/usr/local/lib'], include_dirs=['/usr/local/include'])] setup( name = 'pyreBloom', version = "1.0.1", author = "Dan Lecocq", author_email = "dan@seomoz.org", license = "MIT License", ext_modules = ext_modules, classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: C', 'Programming Language :: Cython', 'Topic :: Software Development :: Libraries :: Python Modules', ], **kwargs )
from distutils.core import setup ext_files = ["pyreBloom/bloom.c"] kwargs = {} try: from Cython.Distutils import build_ext from Cython.Distutils import Extension print "Building from Cython" ext_files.append("pyreBloom/pyreBloom.pyx") kwargs['cmdclass'] = {'build_ext': build_ext} except ImportError: from distutils.core import Extension ext_files.append("pyreBloom/pyreBloom.c") print "Building from C" ext_modules = [Extension("pyreBloom", ext_files, libraries=['hiredis'])] setup( name = 'pyreBloom', version = "1.0.1", author = "Dan Lecocq", author_email = "dan@seomoz.org", license = "MIT License", ext_modules = ext_modules, classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: C', 'Programming Language :: Cython', 'Topic :: Software Development :: Libraries :: Python Modules', ], **kwargs )
Add conditional to avoid duplicate messages, fix EachIf block.
var l10n_file = __dirname + '/../l10n/commands/say.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { if (args) { player.sayL10n(l10n, 'YOU_SAY', args); players.eachIf(function(p) { return otherPlayersInRoom(p); }, function(p) { if (p.getName() != player.getName()) p.sayL10n(l10n, 'THEY_SAY', player.getName(), args); }); return; } player.sayL10n(l10n, 'NOTHING_SAID'); return; } function otherPlayersInRoom(p) { if (p) return (p.getName() !== player.getName() && p.getLocation() === player.getLocation()); }; };
var l10n_file = __dirname + '/../l10n/commands/say.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { if (args) { player.sayL10n(l10n, 'YOU_SAY', args); players.eachIf(function(p) { otherPlayersInRoom(p); }, function(p) { p.sayL10n(l10n, 'THEY_SAY', player.getName(), args); }); return; } player.sayL10n(l10n, 'NOTHING_SAID'); return; } function otherPlayersInRoom(p) { if (p) return (p.getName() !== player.getName() && p.getLocation() === player.getLocation()); }; };
Add note that Struct's field collection is an OrderedDict
""" All the different types that the compiler handles. """ from collections import namedtuple IntegerType = namedtuple('IntegerType', []) Integer = IntegerType() ByteType = namedtuple('ByteType', []) Byte = ByteType() PointerTo = namedtuple('PointerTo', ['type']) ArrayOf = namedtuple('ArrayOf', ['type', 'count']) FunctionPointer = namedtuple('FunctionPointer', ['return_type', 'params']) TypeName = namedtuple('TypeName', ['name']) # Structure is a bit of an oddity - it can't actually be used in 'raw form' # by the user, but is always aliased in a declare block. # # Also, fields is an OrderedDict, since the order of fields matters for layout, Struct = namedtuple('Struct', ['fields']) # This is used merely to record that a function has been declared - the # actual reified type is FunctionPointer FunctionDecl = namedtuple('FunctionDecl', ['return_type', 'params']) AliasDef = namedtuple('AliasDef', ['type']) # Raw types are types which can be used as variables RAW_TYPES = (types.IntegerType, types.ByteType, types.TypeName, types.PointerTo, types.ArrayOf, types.FunctionPointer) def decay_if_array(type_obj): """ Decays arrays types into pointers. """ if isinstance(type_obj, types.ArrayOf): return type_obj.PointerTo(type_obj.type) else: return type_obj def func_decl_to_ptr(func_decl): """ Converts a function declaration to a pointer. """ return FunctionPointer(*func_decl)
""" All the different types that the compiler handles. """ from collections import namedtuple IntegerType = namedtuple('IntegerType', []) Integer = IntegerType() ByteType = namedtuple('ByteType', []) Byte = ByteType() PointerTo = namedtuple('PointerTo', ['type']) ArrayOf = namedtuple('ArrayOf', ['type', 'count']) FunctionPointer = namedtuple('FunctionPointer', ['return_type', 'params']) TypeName = namedtuple('TypeName', ['name']) # Structure is a bit of an oddity - it can't actually be used in 'raw form' # by the user, but is always aliased in a declare block Struct = namedtuple('Struct', ['fields']) # This is used merely to record that a function has been declared - the # actual reified type is FunctionPointer FunctionDecl = namedtuple('FunctionDecl', ['return_type', 'params']) AliasDef = namedtuple('AliasDef', ['type']) # Raw types are types which can be used as variables RAW_TYPES = (types.IntegerType, types.ByteType, types.TypeName, types.PointerTo, types.ArrayOf, types.FunctionPointer) def decay_if_array(type_obj): """ Decays arrays types into pointers. """ if isinstance(type_obj, types.ArrayOf): return type_obj.PointerTo(type_obj.type) else: return type_obj def func_decl_to_ptr(func_decl): """ Converts a function declaration to a pointer. """ return FunctionPointer(*func_decl)
Test Emotes: Equals assert for search by id.
<?php class ApiFastTest extends TestCase { protected $baseUrl = ''; /** * ApiFastTest constructor. */ public function __construct() { parent::__construct(); } /** * A basic functional test example. * * @return void */ public function testEmotes() { // WoTlk $this->json('GET', '/api/v1/dbc/emotes/')->seeJson( ["id" => 0, "emote" => "ONESHOT_NONE"] ); $this->json('GET', '/api/v1/dbc/emotes/3')->seeJsonEquals( ["id" => 3, "emote" => "ONESHOT_WAVE(DNR)"] ); // Wod $this->json('GET', '/api/v1/dbc/emotes/?version=wod')->seeJson( ["id" => 577, "emote" => "ONESHOT_ATTACK1H"] ); $this->json('GET', '/api/v1/dbc/emotes/619/?version=wod')->seeJsonEquals( ["id" => 619, "emote" => "STATE_PARRY_UNARMED"] ); } }
<?php class ApiFastTest extends TestCase { protected $baseUrl = ''; /** * ApiFastTest constructor. */ public function __construct() { parent::__construct(); } /** * A basic functional test example. * * @return void */ public function testEmotes() { // WoTlk $this->json('GET', '/api/v1/dbc/emotes/')->seeJson( ["id" => 0, "emote" => "ONESHOT_NONE"] ); $this->json('GET', '/api/v1/dbc/emotes/3')->seeJson( ["id" => 3, "emote" => "ONESHOT_WAVE(DNR)"] ); // Wod $this->json('GET', '/api/v1/dbc/emotes/?version=wod')->seeJson( ["id" => 577, "emote" => "ONESHOT_ATTACK1H"] ); $this->json('GET', '/api/v1/dbc/emotes//?version=wod')->seeJson( ["id" => 619, "emote" => "STATE_PARRY_UNARMED"] ); } }
Allow API access from anywhere
<?php require_once("../../lib/dao/DrugDAO.class.php"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Origin: *"); if (isset($_REQUEST['n'])) { $num = max($_REQUEST['n'], 1); } else { $num = 1; } if (isset($_REQUEST['form'])) { $form = $_REQUEST['form']; } $dao = new DrugDAO(); if (isset($form)) { $drugnames = $dao->getRandomDrugOfForm($form, $num); } else { $drugnames = $dao->getRandomDrug($num); } $drugs = array(); $fcon = file("../../namegen/drugnames.txt"); foreach ($drugnames as $drug) { $newdrug["drug"] = strtolower($drug); $newdrug["name"] = strtolower(rtrim($fcon[array_rand($fcon)])); $alldata = $dao->getDrugData($drug); // $alldata has data for others forms, make sure we only get those of $form if it is set do { $data = $alldata[array_rand($alldata)]; } while (isset($form) && strpos(strtolower($data["form"]), $form) === false); $newdrug["form"] = strtolower($data["form"]); $newdrug["strength"] = $data["strength"]; $newdrug["container"] = strtolower($data["container"]); $drugs[] = $newdrug; } echo json_encode(array("drugs" => $drugs));
<?php require_once("../../lib/dao/DrugDAO.class.php"); header("Content-Type: application/json; charset=UTF-8"); if (isset($_REQUEST['n'])) { $num = max($_REQUEST['n'], 1); } else { $num = 1; } if (isset($_REQUEST['form'])) { $form = $_REQUEST['form']; } $dao = new DrugDAO(); if (isset($form)) { $drugnames = $dao->getRandomDrugOfForm($form, $num); } else { $drugnames = $dao->getRandomDrug($num); } $drugs = array(); $fcon = file("../../namegen/drugnames.txt"); foreach ($drugnames as $drug) { $newdrug["drug"] = strtolower($drug); $newdrug["name"] = strtolower(rtrim($fcon[array_rand($fcon)])); $alldata = $dao->getDrugData($drug); // $alldata has data for others forms, make sure we only get those of $form if it is set do { $data = $alldata[array_rand($alldata)]; } while (isset($form) && strpos(strtolower($data["form"]), $form) === false); $newdrug["form"] = strtolower($data["form"]); $newdrug["strength"] = $data["strength"]; $newdrug["container"] = strtolower($data["container"]); $drugs[] = $newdrug; } echo json_encode(array("drugs" => $drugs));
Remove git status! when check semver.valid result
(function () { const semver = require('semver') /** * Install plugin * @param app * @param axios */ function plugin(app, axios) { if (plugin.installed) { return } if (!axios) { console.error('You have to install axios') return } if (semver.valid(app.version) == null) { console.error('Unkown vue version') return } plugin.installed = true; if (semver.lt(app.version, '3.0.0')) { Object.defineProperties(app.prototype, { axios: { get: function get() { return axios; } }, $http: { get: function get() { return axios; } } }); } else { app.config.globalProperties.axios = axios; app.config.globalProperties.$http = axios; } app.axios = axios; app.$http = axios; } if (typeof exports == "object") { module.exports = plugin } else if (typeof define == "function" && define.amd) { define([], function(){ return plugin }) } else if (window.Vue && window.axios) { Vue.use(plugin, window.axios) } })();
(function () { const semver = require('semver') /** * Install plugin * @param app * @param axios */ function plugin(app, axios) { if (plugin.installed) { return } if (!axios) { console.error('You have to install axios') return } if (!!!semver.valid(app.version)) { console.error('Unkown vue version') return } plugin.installed = true; if (semver.lt(app.version, '3.0.0')) { Object.defineProperties(app.prototype, { axios: { get: function get() { return axios; } }, $http: { get: function get() { return axios; } } }); } else { app.config.globalProperties.axios = axios; app.config.globalProperties.$http = axios; } app.axios = axios; app.$http = axios; } if (typeof exports == "object") { module.exports = plugin } else if (typeof define == "function" && define.amd) { define([], function(){ return plugin }) } else if (window.Vue && window.axios) { Vue.use(plugin, window.axios) } })();
Regex: Remove leading and trailing .* With no pinning of the pattern to the start or end of a string, the leading and trailing `.*` are redundant.
<?php namespace WP_CLI; /** * Class AutoloadSplitter. * * This class is used to provide the splitting logic to the * `wp-cli/autoload-splitter` Composer plugin. * * @package WP_CLI */ class AutoloadSplitter { /** * Check whether the current class should be split out into a separate * autoloader. * * Note: `class` in this context refers to all PHP autoloadable elements: * - classes * - interfaces * - traits * * @param string $class Fully qualified name of the current class. * @param string $code Path to the code file that declares the class. * * @return bool Whether to split out the class into a separate autoloader. */ public function __invoke( $class, $code ) { return 1 === preg_match( '/\/wp-cli\/\w*(?:-\w*)*-command\//', $code ) || 1 === preg_match( '/\/php\/commands\/src\//', $code ); } }
<?php namespace WP_CLI; /** * Class AutoloadSplitter. * * This class is used to provide the splitting logic to the * `wp-cli/autoload-splitter` Composer plugin. * * @package WP_CLI */ class AutoloadSplitter { /** * Check whether the current class should be split out into a separate * autoloader. * * Note: `class` in this context refers to all PHP autoloadable elements: * - classes * - interfaces * - traits * * @param string $class Fully qualified name of the current class. * @param string $code Path to the code file that declares the class. * * @return bool Whether to split out the class into a separate autoloader. */ public function __invoke( $class, $code ) { return 1 === preg_match( '/.*\/wp-cli\/\w*(?:-\w*)*-command\/.*/', $code ) || 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code ); } }
Add Check for numba in base anaconda distribution. If not found issue meaningful warning message
""" Import the main names to top level. """ try: import numba except: raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.") from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
""" Import the main names to top level. """ from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
Set ignoreHidden to false to allow TinyMCE editor validation to function properly.
/* --- description: Monkey patching the Form.Validator to alter its behavior and extend it into doing more requires: - MooTools More license: @TODO ... */ if(!Koowa) var Koowa = {}; (function($){ Koowa.Validator = new Class({ Extends: Form.Validator.Inline, options: { //Needed to make the TinyMCE editor validation function properly ignoreHidden: false, onShowAdvice: function(input, advice) { advice.addEvent('click', function(){ input.focus(); }); } } }); })(document.id);
/* --- description: Monkey patching the Form.Validator to alter its behavior and extend it into doing more requires: - MooTools More license: @TODO ... */ if(!Koowa) var Koowa = {}; (function($){ Koowa.Validator = new Class({ Extends: Form.Validator.Inline, options: { onShowAdvice: function(input, advice) { advice.addEvent('click', function(){ input.focus(); }); } } }); })(document.id);
Add constructor and implement MyViewHolder constructor
package pl.komunikator.komunikator; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import pl.komunikator.komunikator.entity.User; /** * Created by adrian on 19.04.2017. */ public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> { private List<User> userList; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView name, email; public ImageView photo; public MyViewHolder(View view) { super(view); name = (TextView) view.findViewById(R.id.contactName); email = (TextView) view.findViewById(R.id.contactEmail); photo = (ImageView) view.findViewById(R.id.contactImageView); } } public SearchedUsersAdapter(List<User> userList) { this.userList = userList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } }
package pl.komunikator.komunikator; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import pl.komunikator.komunikator.entity.User; /** * Created by adrian on 19.04.2017. */ public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> { private List<User> userList; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView name, email; public ImageView photo; public MyViewHolder(View view) { super(view); } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } }
Apply style changes to maintenance emails
@extends('layout.emails') @section('preheader') {!! trans('cachet.subscriber.email.maintenance.html-preheader', ['app_name' => Setting::get('app_name')]) !!} @stop @section('content') <div style="text-align: center; border-bottom: 1px solid black; height: 100%;"> <h2> <a href="http://status.clouda.ca/" style="color: #2a92e5;text-decoration: none;hover: initial;">{!! trans('cachet.subscriber.email.maintenance.html', ['app_name' => Setting::get('app_name')]) !!}</a> </h2> </div> <h3> {!! $status !!} </h3> <p> {!! $htmlContent !!} </p> <p> <small><a href="{{ $unsubscribeLink }}">{!! trans('cachet.subscriber.email.unsubscribe') !!}</a></small> </p> @stop
@extends('layout.emails') @section('preheader') {!! trans('cachet.subscriber.email.maintenance.html-preheader', ['app_name' => Setting::get('app_name')]) !!} @stop @section('content') {!! trans('cachet.subscriber.email.maintenance.html', ['app_name' => Setting::get('app_name')]) !!} <p> {!! $status !!} </p> <p> {!! $htmlContent !!} </p> @if(Setting::get('show_support')) <p>{!! trans('cachet.powered_by', ['app' => Setting::get('app_name')]) !!}</p> @endif <p> <small><a href="{{ $unsubscribeLink }}">{!! trans('cachet.subscriber.email.unsubscribe') !!}</a></small> </p> @stop
Fix logout logger no username
<?php /** * Created by PhpStorm. * User: rahman * Date: 11/5/14 * Time: 8:47 AM */ Event::listen('auth.login', function($user) { Event::fire('logger', array(array('login',array('username'=>$user->username),3))); }); Event::listen('auth.logout', function($user) { $username = $user ? $user->username : '-'; Event::fire('logger', array(array('logout',array('username'=>$username),3))); }); Event::listen('logger', function($log) { $log = array( 'event_name'=> $log[0], 'custom_parameter'=> json_encode($log[1]), 'verbose_level' => $log[2], 'ip_address' => Request::getClientIp(), 'request_uri' => Request::url(), ); $logger = Logger::create($log); $freshTimestamp = new \Carbon\Carbon(); $log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL; File::append(Config::get('settings.log_file'),$log_string); });
<?php /** * Created by PhpStorm. * User: rahman * Date: 11/5/14 * Time: 8:47 AM */ Event::listen('auth.login', function($user) { Event::fire('logger', array(array('login',array('username'=>$user->username),3))); }); Event::listen('auth.logout', function($user) { $username = $user ? $user->username : '-'; Event::fire('logger', array(array('logout',array('username'=>$user->username),3))); }); Event::listen('logger', function($log) { $log = array( 'event_name'=> $log[0], 'custom_parameter'=> json_encode($log[1]), 'verbose_level' => $log[2], 'ip_address' => Request::getClientIp(), 'request_uri' => Request::url(), ); $logger = Logger::create($log); $freshTimestamp = new \Carbon\Carbon(); $log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL; File::append(Config::get('settings.log_file'),$log_string); });
Configure eslint - make 4 space indent mandatory.
// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, // https://github.com/standard/standard/blob/master/docs/RULES-en.md extends: 'standard', // required to lint *.vue files plugins: [ 'html' ], // add your custom rules here 'rules': { // allow paren-less arrow functions 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, // let me use 4 spaces... please! 'indent': ['error', 4] } }
// https://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, // https://github.com/standard/standard/blob/master/docs/RULES-en.md extends: 'standard', // required to lint *.vue files plugins: [ 'html' ], // add your custom rules here 'rules': { // allow paren-less arrow functions 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 0, // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, // let me use 4 spaces... please! 'indent': 0 } }
Remove unnecessary and incorrect import
package org.amc.servlet.listener; /** * * @author Adrian Mclaughlin * @version 1 */ import org.apache.log4j.Logger; import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener public class APLSessionListener implements HttpSessionListener { private static Logger logger=Logger.getLogger(APLSessionListener.class); public static int count=0; @Override public void sessionCreated(HttpSessionEvent arg0) { synchronized(this) { count++; String address=""; logger.info("(Create) There are "+count+" sessions"); updateSerlvetContext(arg0); } } @Override public void sessionDestroyed(HttpSessionEvent arg0) { synchronized(this) { if(count>0) { count--; } logger.info("(Destroy) There are "+count+" sessions"); updateSerlvetContext(arg0); } } private void updateSerlvetContext(HttpSessionEvent arg0) { synchronized(arg0.getSession().getServletContext()) { ServletContext context=arg0.getSession().getServletContext(); context.setAttribute("session_count", count); } } }
package org.amc.servlet.listener; /** * * @author Adrian Mclaughlin * @version 1 */ import org.apache.log4j.Logger; import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.sun.security.auth.UserPrincipal; @WebListener public class APLSessionListener implements HttpSessionListener { private static Logger logger=Logger.getLogger(APLSessionListener.class); public static int count=0; @Override public void sessionCreated(HttpSessionEvent arg0) { synchronized(this) { count++; String address=""; logger.info("(Create) There are "+count+" sessions"); updateSerlvetContext(arg0); } } @Override public void sessionDestroyed(HttpSessionEvent arg0) { synchronized(this) { if(count>0) { count--; } logger.info("(Destroy) There are "+count+" sessions"); updateSerlvetContext(arg0); } } private void updateSerlvetContext(HttpSessionEvent arg0) { synchronized(arg0.getSession().getServletContext()) { ServletContext context=arg0.getSession().getServletContext(); context.setAttribute("session_count", count); } } }
Restructure the creation of the AST
'use strict'; const fs = require('fs'); const util = require('util'); const _ = require('lodash'); const LineTokens = require('./LineTokens'); const AbstractSyntaxTree = require('./AbstractSyntaxTree'); class MUMPSCompiler { readFile(fileName) { return fs.readFileSync(fileName, 'utf8').split('\n'); } compile(fileName) { this.lines = this.readFile(fileName); this.tokens = this.lines.map((line, index) => (new LineTokens(line, index))); this.abstractSyntaxTree = new AbstractSyntaxTree(this.tokens); console.log(util.inspect(this.abstractSyntaxTree, { depth: null, colors: true })); } } module.exports = MUMPSCompiler; // We can also just run this script straight-up. if (require.main === module) { const options = {}; const args = process.argv.slice(2); const fileName = args[0] || ''; const compiler = new MUMPSCompiler(); compiler.compile(fileName); }
'use strict'; const fs = require('fs'); const util = require('util'); const _ = require('lodash'); const LineTokens = require('./LineTokens'); const AbstractSyntaxTree = require('./AbstractSyntaxTree'); class MUMPSCompiler { readFile(fileName) { return fs.readFileSync(fileName, 'utf8').split('\n'); } compile(fileName) { this.lines = this.readFile(fileName); this.tokens = this.lines.map((line, index) => (new LineTokens(line, index))); this.abstractSyntaxTrees = this.tokens.map(tokens => (new AbstractSyntaxTree(tokens))); console.log(util.inspect(this.abstractSyntaxTrees, { depth: null, colors: true })); } } module.exports = MUMPSCompiler; // We can also just run this script straight-up. if (require.main === module) { const options = {}; const args = process.argv.slice(2); const fileName = args[0] || ''; const compiler = new MUMPSCompiler(); compiler.compile(fileName); }
Add category id filtering to subcategories
from django.shortcuts import render from django.views.generic import TemplateView from rest_framework import viewsets, filters from books.models import Book, Category, SubCategory from books.serializers import BookSerializer, CategorySerializer, SubCategorySerializer class HomeTemplateView(TemplateView, ): template_name = 'home.html' class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title', 'subcategory__category__name', 'subcategory__name') class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer filter_backends = (filters.SearchFilter,) search_fields = ('name', ) class SubCategoryViewSet(viewsets.ModelViewSet): queryset = SubCategory.objects.all() serializer_class = SubCategorySerializer filter_backends = (filters.SearchFilter,) search_fields = ('name, category__name', ) def get_queryset(self): queryset = SubCategory.objects.all() category = self.request.query_params.get('category', None) if category is not None: queryset = queryset.filter(category_id=category) return queryset
from django.shortcuts import render from django.views.generic import TemplateView from rest_framework import viewsets, filters from books.models import Book, Category, SubCategory from books.serializers import BookSerializer, CategorySerializer, SubCategorySerializer class HomeTemplateView(TemplateView, ): template_name = 'home.html' class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title', 'subcategory__category__name', 'subcategory__name') class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer filter_backends = (filters.SearchFilter,) search_fields = ('name', ) class SubCategoryViewSet(viewsets.ModelViewSet): queryset = SubCategory.objects.all() serializer_class = SubCategorySerializer filter_backends = (filters.SearchFilter,) search_fields = ('category__name', )
Use process.cwd() to serve static files
var express = require('express'), bodyParser = require('body-parser'), session = require('express-session'), passport = require('passport'), jwt = require('jwt-simple'); var User = require('../app/models/user.server.model'); module.exports = function() { var app = express(); // Use middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static(process.cwd() + '/public')); app.use(session( { secret: 'IHopeNobodyCanGuessThisSecret', saveUninitialized: false, resave: false } )); app.use(passport.initialize()); app.use(passport.session()); // Include passport config require('./passport')(app, passport, jwt); // Include all routes require('../app/routes/users.server.routes')(app, passport); require('../app/routes/emails.server.routes')(app); return app; }
var express = require('express'), bodyParser = require('body-parser'), session = require('express-session'), passport = require('passport'), jwt = require('jwt-simple'); var User = require('../app/models/user.server.model'); module.exports = function() { var app = express(); // Use middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static('public')); app.use(session( { secret: 'IHopeNobodyCanGuessThisSecret', saveUninitialized: false, resave: false } )); app.use(passport.initialize()); app.use(passport.session()); // Include passport config require('./passport')(app, passport, jwt); // Include all routes require('../app/routes/users.server.routes')(app, passport); require('../app/routes/emails.server.routes')(app); return app; }
[FIX] Send logging output to stdout Fixes #557
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ The mriqc package provides a series of :abbr:`NR (no-reference)`, :abbr:`IQMs (image quality metrics)` to used in :abbr:`QAPs (quality assessment protocols)` for :abbr:`MRI (magnetic resonance imaging)`. """ from __future__ import print_function, division, absolute_import, unicode_literals import sys import logging from .__about__ import ( __version__, __author__, __email__, __maintainer__, __copyright__, __credits__, __license__, __status__, __description__, __longdesc__, __url__, __download__, ) LOG_FORMAT = '%(asctime)s %(name)s:%(levelname)s %(message)s' MRIQC_LOG = logging.getLogger() logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format=LOG_FORMAT, ) DEFAULTS = { 'ants_nthreads': 6, 'float32': False }
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ The mriqc package provides a series of :abbr:`NR (no-reference)`, :abbr:`IQMs (image quality metrics)` to used in :abbr:`QAPs (quality assessment protocols)` for :abbr:`MRI (magnetic resonance imaging)`. """ from __future__ import print_function, division, absolute_import, unicode_literals import logging from .__about__ import ( __version__, __author__, __email__, __maintainer__, __copyright__, __credits__, __license__, __status__, __description__, __longdesc__, __url__, __download__, ) LOG_FORMAT = '%(asctime)s %(name)s:%(levelname)s %(message)s' logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT) MRIQC_LOG = logging.getLogger() DEFAULTS = { 'ants_nthreads': 6, 'float32': False }
Change URL from ScraperWiki > source
from distutils.core import setup setup(name='dshelpers', version='1.1.0', description="Provides some helpers functions used by the ScraperWiki Data Services team.", long_description="Provides some helpers functions used by the ScraperWiki Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], author="ScraperWiki Limited", author_email='dataservices@scraperwiki.com', url='https://github.com/scraperwiki/data-services-helpers', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], )
from distutils.core import setup setup(name='dshelpers', version='1.1.0', description="Provides some helpers functions used by the ScraperWiki Data Services team.", long_description="Provides some helpers functions used by the ScraperWiki Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], author="ScraperWiki Limited", author_email='dataservices@scraperwiki.com', url='http://scraperwiki.com', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], )
Set the default prefix for ProjectSurveys to gsoc_program.
#!/usr/bin/python2.5 # # Copyright 2009 the Melange 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. """This module contains the ProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.survey import Survey class ProjectSurvey(Survey): """Survey for Students that have a StudentProject. """ def __init__(self, *args, **kwargs): super(ProjectSurvey, self).__init__(*args, **kwargs) self.prefix = 'gsoc_program' self.taking_access = 'student'
#!/usr/bin/python2.5 # # Copyright 2009 the Melange 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. """This module contains the ProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.survey import Survey class ProjectSurvey(Survey): """Survey for Students that have a StudentProject. """ def __init__(self, *args, **kwargs): super(ProjectSurvey, self).__init__(*args, **kwargs) # TODO: prefix has to be set to gsoc_program once data has been transferred self.prefix = 'program' self.taking_access = 'student'
Fix Strict error again :)
<?php /* * This file is part of PsySH * * (c) 2012 Justin Hileman * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Psy\Formatter; use Psy\Formatter\RecursiveFormatter; /** * A pretty-printer for arrays.. */ class ArrayFormatter extends RecursiveFormatter { /** * Format the array. * * @param array $array * * @return string */ public static function format($array) { if (empty($array)) { return '[]'; } $formatted = array_map(array(__CLASS__, 'formatValue'), $array); $template = sprintf('[%s%s%%s%s ]', PHP_EOL, str_repeat(' ', 7), PHP_EOL); $glue = sprintf(',%s%s', PHP_EOL, str_repeat(' ', 7)); return sprintf($template, implode($glue, $formatted)); } /** * Format a reference to the array. * * @param array $array * * @return string */ public static function formatRef($array) { return sprintf('Array(%d)', count($array)); } }
<?php /* * This file is part of PsySH * * (c) 2012 Justin Hileman * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Psy\Formatter; use Psy\Formatter\RecursiveFormatter; /** * A pretty-printer for arrays.. */ class ArrayFormatter extends RecursiveFormatter { /** * Format the array. * * @param array $array * * @return string */ public static function format(array $array) { if (empty($array)) { return '[]'; } $formatted = array_map(array(__CLASS__, 'formatValue'), $array); $template = sprintf('[%s%s%%s%s ]', PHP_EOL, str_repeat(' ', 7), PHP_EOL); $glue = sprintf(',%s%s', PHP_EOL, str_repeat(' ', 7)); return sprintf($template, implode($glue, $formatted)); } /** * Format a reference to the array. * * @param array $array * * @return string */ public static function formatRef(array $array) { return sprintf('Array(%d)', count($array)); } }
Disable drag and drop event for document
'use strict'; function init() { // Disable drag + drop event for document. document.addEventListener('dragover', function(event) { event.preventDefault(); return false; }, false); document.addEventListener('drop', function(event) { event.preventDefault(); return false; }, false); // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); return false; }; }; window.onload = init;
'use strict'; function init() { // Drag and Drop holder. const holder = document.getElementById('holder'); // Placehold text in holder. const dragText = document.getElementById('drag-text'); holder.ondragover = function() { return false; }; holder.ondragleave = holder.ondragend = function() { return false; }; holder.ondrop = function(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; console.log('File you dragged here is', file.path); // Remove exitng video. const existingVideo = holder.getElementsByTagName('video')[0]; if (existingVideo) { existingVideo.remove(); }; dragText.className += ' hidden'; const video = document.createElement("video"); video.setAttribute('controls', ''); video.setAttribute("width", '100%'); video.setAttribute('height', '100%'); const source = document.createElement("source"); source.setAttribute('src', file.path); video.appendChild(source); holder.appendChild(video); return false; }; }; window.onload = init;
Add test to ensure only one conn object is created
# coding: utf-8 from pysuru.base import BaseAPI, ObjectMixin def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_baseapi_conn_should_return_same_object(): api = BaseAPI(None, None) obj1 = api.conn obj2 = api.conn assert obj1 is obj2 def test_build_url_should_return_full_api_endpoint(): api = BaseAPI('http://example.com/', None) assert 'http://example.com/apis' == api.build_url('/apis') api = BaseAPI('http://example.com', None) assert 'http://example.com/apis' == api.build_url('/apis') def test_baseobject_create_should_ignore_unknown_fields(): data = {'field1': 'value1', 'unknown': 'ignored'} created = _DummyObject.create(**data) assert created.attrs['field1'] == 'value1' assert 'unknown' not in created.attrs class _DummyObject(ObjectMixin): _fields = ('field1', 'field2') def __init__(self, **kwargs): self.attrs = kwargs
# coding: utf-8 from pysuru.base import BaseAPI, ObjectMixin def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_build_url_should_return_full_api_endpoint(): api = BaseAPI('http://example.com/', None) assert 'http://example.com/apis' == api.build_url('/apis') api = BaseAPI('http://example.com', None) assert 'http://example.com/apis' == api.build_url('/apis') def test_baseobject_create_should_ignore_unknown_fields(): data = {'field1': 'value1', 'unknown': 'ignored'} created = _DummyObject.create(**data) assert created.attrs['field1'] == 'value1' assert 'unknown' not in created.attrs class _DummyObject(ObjectMixin): _fields = ('field1', 'field2') def __init__(self, **kwargs): self.attrs = kwargs
Add docblock for fromIncomingIrcMessage function Signed-off-by: Yoshi2889 <77953cd64cc4736aae27fa116356e02d2d97f7ce@gmail.com>
<?php /* WildPHP - a modular and easily extendable IRC bot written in PHP Copyright (C) 2016 WildPHP This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace WildPHP\Core\Connection\IncomingIrcMessages; use WildPHP\Core\Connection\IncomingIrcMessage; interface BaseMessage { /** * @param IncomingIrcMessage $incomingIrcMessage * @return mixed */ public static function fromIncomingIrcMessage(IncomingIrcMessage $incomingIrcMessage); }
<?php /* WildPHP - a modular and easily extendable IRC bot written in PHP Copyright (C) 2016 WildPHP This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace WildPHP\Core\Connection\IncomingIrcMessages; use WildPHP\Core\Connection\IncomingIrcMessage; interface BaseMessage { public static function fromIncomingIrcMessage(IncomingIrcMessage $incomingIrcMessage); }
Rearrange express config according to docs
var express = require('express'), path = require('path'), config = require('config'), setupPassport = require('./setupPassport'), flash = require('connect-flash'), appRouter = require('./routers/appRouter.js')(express), session = require('express-session'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), jsonParser = bodyParser.json(), expressJwt = require('express-jwt'), db = require('./model/models') var app = express() app.use(jsonParser) app.use(bodyParser.urlencoded({ extended: true })) setupPassport(app) // is there a better way to do this? app.use('/', express.static(path.join(__dirname, '/public'))) app.use('/styles', express.static(path.join(__dirname, '/styles'))) app.use('/', appRouter) app.set('views', __dirname + '/views') app.set('port', process.env.PORT || 8080) db.sync().then(() => app.listen(app.get('port'))) console.log(`Server started on port ${app.get('port')}`) module.exports.getApp = app
var express = require('express'), path = require('path'), config = require('config'), setupPassport = require('./setupPassport'), flash = require('connect-flash'), appRouter = require('./routers/appRouter.js')(express), session = require('express-session'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), jsonParser = bodyParser.json(), expressJwt = require('express-jwt'), db = require('./model/models') var app = express() app.set('views', __dirname + '/views') app.set('port', process.env.PORT || 8080) app.use(jsonParser) app.use(bodyParser.urlencoded({ extended: true })) app.use('/', express.static(path.join(__dirname, '/public'))) app.use('/styles', express.static(path.join(__dirname, '/styles'))) app.use('/', appRouter) setupPassport(app) // is there a better way to do this? db.sync().then(() => app.listen(app.get('port'))) console.log(`Server started on port ${app.get('port')}`) module.exports.getApp = app
Update display of font size and line height
function RGBToHex(RGB) { const RGBParts = RGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); const HexArr = []; delete RGBParts[0]; RGBParts.forEach((value) => { let hex = parseInt(value, 10).toString(16); if (hex.length === 1) { hex = `0${hex}`; } HexArr.push(hex); }); return `#${HexArr.join('')}`; } function isRGB(value) { return !!value.match(/^rgb\(/); } const fontanelloFont = chrome.contextMenus.create({ title: 'Fontanello font', contexts: ['selection'], }); const fontanelloSize = chrome.contextMenus.create({ title: 'Fontanello size', contexts: ['selection'], }); const fontanelloColor = chrome.contextMenus.create({ title: 'Fontanello color', contexts: ['selection'], }); chrome.runtime.onMessage.addListener((fontInfo) => { chrome.contextMenus.update(fontanelloFont, { title: fontInfo.font, }); chrome.contextMenus.update(fontanelloSize, { title: `${fontInfo.fontSize} / ${fontInfo.lineHeight}` + ' ' + `(${parseInt(fontInfo.lineHeight, 10) / parseInt(fontInfo.fontSize, 10)})`, }); chrome.contextMenus.update(fontanelloColor, { title: isRGB(fontInfo.color) ? RGBToHex(fontInfo.color) : fontInfo.color, }); });
function RGBToHex(RGB) { const RGBParts = RGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); const HexArr = []; delete RGBParts[0]; RGBParts.forEach((value) => { let hex = parseInt(value, 10).toString(16); if (hex.length === 1) { hex = `0${hex}`; } HexArr.push(hex); }); return `#${HexArr.join('')}`; } function isRGB(value) { return !!value.match(/^rgb\(/); } const fontanelloFont = chrome.contextMenus.create({ title: 'Fontanello font', contexts: ['selection'], }); const fontanelloSize = chrome.contextMenus.create({ title: 'Fontanello size', contexts: ['selection'], }); const fontanelloColor = chrome.contextMenus.create({ title: 'Fontanello color', contexts: ['selection'], }); chrome.runtime.onMessage.addListener((fontInfo) => { chrome.contextMenus.update(fontanelloFont, { title: fontInfo.font, }); chrome.contextMenus.update(fontanelloSize, { title: `${fontInfo.fontSize} / ${fontInfo.lineHeight}`, }); chrome.contextMenus.update(fontanelloColor, { title: isRGB(fontInfo.color) ? RGBToHex(fontInfo.color) : fontInfo.color, }); });
Add docs-live to perform demo-runs
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs") @nox.session(name="docs-live") def docs_live(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-autobuild", "-b", "html", "docs/", "build/docs")
"""Development automation.""" import nox def _install_this_editable(session, *, extras=None): if extras is None: extras = [] session.install("flit") session.run( "flit", "install", "-s", "--deps=production", "--extras", ",".join(extras), silent=True, ) @nox.session def lint(session): session.install("pre-commit") session.run("pre-commit", "run", "--all-files", *session.posargs) @nox.session(python=["3.6", "3.7", "3.8"]) def test(session): _install_this_editable(session, extras=["test"]) default_args = ["--cov-report", "term", "--cov", "sphinx_autobuild"] args = session.posargs or default_args session.run("pytest", *args) @nox.session def docs(session): _install_this_editable(session, extras=["docs"]) session.run("sphinx-build", "-b", "html", "docs/", "build/docs")
Add missing injection for minified MainCtrl
function MainCtrl($scope, $routeParams, $route, $location) { $scope.checkLocation = function() { if (!$location.path().startsWith('/login')) { $scope.hideAdminNav = false; $scope.dontAskForPassword = false; } else { $scope.hideAdminNav = true; $scope.dontAskForPassword = true; } }; $scope.checkLocation(); // bug in angular prevents this from firing when the back button is used // (fixed in 1.1.5) - see https://github.com/angular/angular.js/pull/2206 $scope.$on('$locationChangeStart', function(ev, oldloc, newloc) { $scope.checkLocation(); }); } MainCtrl.$inject = [ '$scope', '$routeParams', '$route', '$location' ];
function MainCtrl($scope, $routeParams, $route, $location) { $scope.checkLocation = function() { if (!$location.path().startsWith('/login')) { $scope.hideAdminNav = false; $scope.dontAskForPassword = false; } else { $scope.hideAdminNav = true; $scope.dontAskForPassword = true; } }; $scope.checkLocation(); // bug in angular prevents this from firing when the back button is used // (fixed in 1.1.5) - see https://github.com/angular/angular.js/pull/2206 $scope.$on('$locationChangeStart', function(ev, oldloc, newloc) { $scope.checkLocation(); }); }
Test everything with stress test.
#!/usr/bin/env python # Copyright 2007 Albert Strasheim <fullung@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from test_openwire_async import * from test_openwire_sync import * from test_stomp_async import * from test_stomp_sync import * from test_types import * if __name__ == '__main__': testLoader = unittest.defaultTestLoader module = __import__('__main__') test = testLoader.loadTestsFromModule(module) testRunner = unittest.TextTestRunner(verbosity=2) for i in xrange(100): result = testRunner.run(test)
#!/usr/bin/env python # Copyright 2007 Albert Strasheim <fullung@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest if __name__ == '__main__': testLoader = unittest.defaultTestLoader module = __import__('__main__') test = testLoader.loadTestsFromModule(module) testRunner = unittest.TextTestRunner(verbosity=2) for i in xrange(100): result = testRunner.run(test)
Fix wrong mail server in settings
# -*- coding: utf-8 -*- """ talkoohakemisto.settings.production ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains application settings specific to a production environment running on Heroku. """ import os from .base import * # flake8: noqa # # Generic # ------- # If a secret key is set, cryptographic components can use this to sign cookies # and other things. Set this to a complex random value when you want to use the # secure cookie for instance. SECRET_KEY = os.environ['SECRET_KEY'] # The debug flag. Set this to True to enable debugging of the application. In # debug mode the debugger will kick in when an unhandled exception ocurrs and # the integrated server will automatically reload the application if changes in # the code are detected. DEBUG = 'DEBUG' in os.environ # Controls if the cookie should be set with the secure flag. Defaults # to ``False``. SESSION_COOKIE_SECURE = True # # SQLAlchemy # ---------- SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] # # Email configuration # ------------------- MAIL_SERVER = 'smtp.mandrillapp.com' MAIL_USERNAME = os.environ['MANDRILL_USERNAME'] MAIL_PASSWORD = os.environ['MANDRILL_APIKEY'] MAIL_PORT = 587 MAIL_USE_TLS = True
# -*- coding: utf-8 -*- """ talkoohakemisto.settings.production ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains application settings specific to a production environment running on Heroku. """ import os from .base import * # flake8: noqa # # Generic # ------- # If a secret key is set, cryptographic components can use this to sign cookies # and other things. Set this to a complex random value when you want to use the # secure cookie for instance. SECRET_KEY = os.environ['SECRET_KEY'] # The debug flag. Set this to True to enable debugging of the application. In # debug mode the debugger will kick in when an unhandled exception ocurrs and # the integrated server will automatically reload the application if changes in # the code are detected. DEBUG = 'DEBUG' in os.environ # Controls if the cookie should be set with the secure flag. Defaults # to ``False``. SESSION_COOKIE_SECURE = True # # SQLAlchemy # ---------- SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] # # Email configuration # ------------------- MAIL_SERVER = 'smtp.mandrillapp.net' MAIL_USERNAME = os.environ['MANDRILL_USERNAME'] MAIL_PASSWORD = os.environ['MANDRILL_APIKEY'] MAIL_PORT = 587 MAIL_USE_TLS = True
[codestyle] Fix bad indentation in the JSONH parser
'use strict'; var JSONH = require('jsonh'); /** * Message encoder. * * @param {Mixed} data The data that needs to be transformed in to a string. * @param {Function} fn Completion callback. * @api public */ exports.encoder = function encoder(data, fn) { var err; try { data = JSONH.stringify(data); } catch (e) { err = e; } fn(err, data); }; /** * Message encoder. * * @param {Mixed} data The data that needs to be transformed in to a string. * @param {Function} fn Completion callback. * @api public */ exports.decoder = function decoder(data, fn) { var err; try { data = JSONH.parse(data); } catch (e) { err = e; } fn(err, data); }; // // Expose the library so it can be added in our Primus module. // exports.library = require('fs').readFileSync(require.resolve('jsonh'), 'utf-8');
'use strict'; var JSONH = require('jsonh'); /** * Message encoder. * * @param {Mixed} data The data that needs to be transformed in to a string. * @param {Function} fn Completion callback. * @api public */ exports.encoder = function encoder(data, fn) { var err; try { data = JSONH.stringify(data); } catch (e) { err = e; } fn(err, data); }; /** * Message encoder. * * @param {Mixed} data The data that needs to be transformed in to a string. * @param {Function} fn Completion callback. * @api public */ exports.decoder = function decoder(data, fn) { var err; try { data = JSONH.parse(data); } catch (e) { err = e; } fn(err, data); }; // // Expose the library so it can be added in our Primus module. // exports.library = require('fs').readFileSync(require.resolve('jsonh'), 'utf-8');
Add false positive login test
<?php require_once('Autoload.php'); class SQLAuthTest extends PHPUnit_Framework_TestCase { public function testSQLAuthenticator() { $GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/travis/helpers'; if(!isset(FlipsideSettings::$dataset['auth'])) { $params = array('dsn'=>'mysql:host=localhost;dbname=auth', 'host'=>'localhost', 'user'=>'root', 'pass'=>''); FlipsideSettings::$dataset['auth'] = array('type'=>'SQLDataSet', 'params'=>$params); } $params = array('current'=>true, 'pending'=>false, 'supplement'=>false, 'current_data_set'=>'auth'); $auth = new \Auth\SQLAuthenticator($params); $this->assertFalse($auth->login('test', 'test')); } } /* vim: set tabstop=4 shiftwidth=4 expandtab: */ ?>
<?php require_once('Autoload.php'); class SQLAuthTest extends PHPUnit_Framework_TestCase { public function testSQLAuthenticator() { $GLOBALS['FLIPSIDE_SETTINGS_LOC'] = './tests/travis/helpers'; if(!isset(FlipsideSettings::$dataset['auth'])) { $params = array('dsn'=>'mysql:host=localhost;dbname=auth', 'host'=>'localhost', 'user'=>'root', 'pass'=>''); FlipsideSettings::$dataset['auth'] = array('type'=>'SQLDataSet', 'params'=>$params); } $params = array('current'=>true, 'pending'=>false, 'supplement'=>false, 'current_data_set'=>'auth'); $auth = new \Auth\SQLAuthenticator($params); } } /* vim: set tabstop=4 shiftwidth=4 expandtab: */ ?>
Fix URL/player.ui.mode sync issues on page load.
angular.module("sim/Simulation.js", [ "sim/model/Player.js", "sim/ui/ActionBar.js", "sim/ui/Explore.js", "sim/ui/Rest.js", "sim/ui/Status.js" ]). controller("Simulation", Simulation); function Simulation($scope, $location, Player) { // TODO(philharnish): See ngViewDirective for scope $destroy and // creation pattern. $scope.tabs = ["explore", "rest"]; $scope.player = new Player("50b6f69be4b0dbae32c8ece1"); $scope.$watch( function() { // Wait until player is initialized before setting the mode. return $scope.player.initialized() && $location.path().split("/").pop(); }, function(path) { if (path) { $scope.player.ui.mode(path); } }); }
angular.module("sim/Simulation.js", [ "sim/model/Player.js", "sim/ui/ActionBar.js", "sim/ui/Explore.js", "sim/ui/Rest.js", "sim/ui/Status.js" ]). controller("Simulation", Simulation); function Simulation($scope, $location, Player) { // TODO(philharnish): See ngViewDirective for scope $destroy and // creation pattern. $scope.tabs = ["explore", "rest"]; $scope.player = new Player("50b6f69be4b0dbae32c8ece1"); $scope.$watch( function () { // Requires closure since $location.path must not take arguments // and we'd rather have the last piece of the path regardless. return $location.path().split("/").pop(); }, function (path) { // Requires closure since setMode is not bound to player. $scope.player.ui.mode(path); }); }
Add some fallback code when looking for our prefs object.
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: # try looking for all variants of RFB_PREFS_NAME for k, v in bpy.context.preferences.addons.items(): if RFB_PREFS_NAME in k: return v return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
from ..rman_constants import RFB_PREFS_NAME import bpy def get_addon_prefs(): try: addon = bpy.context.preferences.addons[RFB_PREFS_NAME] return addon.preferences except: return None def get_pref(pref_name='', default=None): """ Return the value of a preference Args: pref_name (str) - name of the preference to look up default (AnyType) - default to return, if pref_name doesn't exist Returns: (AnyType) - preference value. """ prefs = get_addon_prefs() if not prefs: return default return getattr(prefs, pref_name, default) def get_bl_temp_dir(): return bpy.context.preferences.filepaths.temporary_directory
:wrench: Add post fixture on reference
<?php namespace OAuthBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use WordPressBundle\Entity\Post; class LoadPostData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $post1 = new Post(); $post1->setPostAuthor(1); $post1->setPostDate(new \DateTime("now")); $post1->setPostDateGmt(new \DateTime("now")); $post1->setPostContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam eligendi provident quam eveniet sint nesciunt consequuntur reprehenderit velit est molestiae, quisquam, repellendus, aliquid delectus natus! Et optio asperiores, commodi dignissimos."); $post1->setPostTitle("Lorem ipsum"); $post1->setPostExcerpt("lorem ipsum dolor sit"); $post1->setPostModified(new \DateTime("now")); $post1->setPostModifiedGmt(new \DateTime("now")); $this->addReference('post-1', $post1); $manager->persist($post1); $manager->flush(); } public function getOrder(){ return 1; } }
<?php namespace OAuthBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use WordPressBundle\Entity\Post; class LoadPostData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $post1 = new Post(); $post1->setPostAuthor(1); $post1->setPostDate(new \DateTime("now")); $post1->setPostDateGmt(new \DateTime("now")); $post1->setPostContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam eligendi provident quam eveniet sint nesciunt consequuntur reprehenderit velit est molestiae, quisquam, repellendus, aliquid delectus natus! Et optio asperiores, commodi dignissimos."); $post1->setPostTitle("Lorem ipsum"); $post1->setPostExcerpt("lorem ipsum dolor sit"); $post1->setPostModified(new \DateTime("now")); $post1->setPostModifiedGmt(new \DateTime("now")); $manager->persist($post1); $manager->flush(); } public function getOrder(){ return 1; } }
Improve deprecation notices for new template events system
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\UiBundle\Block; use Sonata\BlockBundle\Event\BlockEvent; use Sonata\BlockBundle\Model\Block; final class BlockEventListener { /** @var string */ private $template; public function __construct(string $template) { @trigger_error( sprintf('Using "%s" to add blocks to the templates is deprecated since Sylius 1.7 and will be removed in Sylius 2.0. Use "sylius_ui" configuration instead.', self::class), \E_USER_DEPRECATED ); $this->template = $template; } public function onBlockEvent(BlockEvent $event): void { $block = new Block(); $block->setId(uniqid('', true)); $block->setSettings(array_replace($event->getSettings(), [ 'template' => $this->template, ])); $block->setType('sonata.block.service.template'); $event->addBlock($block); } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\UiBundle\Block; use Sonata\BlockBundle\Event\BlockEvent; use Sonata\BlockBundle\Model\Block; final class BlockEventListener { /** @var string */ private $template; public function __construct(string $template) { @trigger_error( sprintf('Using "%s" to add blocks to the templates is deprecated since Sylius 1.7. Use "sylius_ui" configuration instead.', self::class), \E_USER_DEPRECATED ); $this->template = $template; } public function onBlockEvent(BlockEvent $event): void { $block = new Block(); $block->setId(uniqid('', true)); $block->setSettings(array_replace($event->getSettings(), [ 'template' => $this->template, ])); $block->setType('sonata.block.service.template'); $event->addBlock($block); } }
Remove email from User API Test
import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
import pytest from django.test import RequestFactory from {{ cookiecutter.project_slug }}.users.api.views import UserViewSet from {{ cookiecutter.project_slug }}.users.models import User pytestmark = pytest.mark.django_db class TestUserViewSet: def test_get_queryset(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request assert user in view.get_queryset() def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = rf.get("/fake-url/") request.user = user view.request = request response = view.me(request) assert response.data == { "username": user.username, "email": user.email, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", }
Add a way to inflect by count
<?php namespace PragmaRX\Support\Inflectors; class Inflector { protected static $localizedInflectors = [ 'en' => 'PragmaRX\Support\Inflectors\En', 'pt' => 'PragmaRX\Support\Inflectors\PtBr', ]; public function inflect($word, $count) { if ($count > 1) { return $this->plural($word); } return $this->singular($word); } public static function plural($word) { $inflector = static::getInflector(); return $inflector->plural($word); } public static function singular($word) { $inflector = static::getInflector(); return $inflector->singular($word); } private static function getInflector() { $inflector = static::$localizedInflectors['en']; if (function_exists('app')) { $locale = app()->make('translator')->getLocale(); foreach (static::$localizedInflectors as $lang => $class) { if (starts_with($locale, $lang)) { $inflector = $class; } } } return new $inflector; } }
<?php namespace PragmaRX\Support\Inflectors; class Inflector { protected static $localizedInflectors = [ 'en' => 'PragmaRX\Support\Inflectors\En', 'pt' => 'PragmaRX\Support\Inflectors\PtBr', ]; public static function plural($word) { $inflector = static::getInflector(); return $inflector->plural($word); } public static function singular($word) { $inflector = static::getInflector(); return $inflector->singular($word); } private static function getInflector() { $inflector = static::$localizedInflectors['en']; if (function_exists('app')) { $locale = app()->make('translator')->getLocale(); foreach (static::$localizedInflectors as $lang => $class) { if (starts_with($locale, $lang)) { $inflector = $class; } } } return new $inflector; } }
Remove mfr parameter from init_app
""" Update User.comments_viewed_timestamp field & comments model. Accompanies https://github.com/CenterForOpenScience/osf.io/pull/1762 """ from modularodm import Q from framework.auth.core import User from website.models import Comment from website.app import init_app import logging from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(): init_app(routes=False, set_backends=True) update_comments_viewed_timestamp() update_comments() def update_comments_viewed_timestamp(): users = User.find(Q('comments_viewed_timestamp', 'ne', None) | Q('comments_viewed_timestamp', 'ne', {})) for user in users: if user.comments_viewed_timestamp: for node in user.comments_viewed_timestamp: user.comments_viewed_timestamp[node] = {'node': user.comments_viewed_timestamp[node]} user.save() def update_comments(): comments = Comment.find() for comment in comments: comment.root_target = comment.node comment.page = Comment.OVERVIEW comment.is_hidden = False comment.save() if __name__ == '__main__': script_utils.add_file_logger(logger, __file__) main()
""" Update User.comments_viewed_timestamp field & comments model. Accompanies https://github.com/CenterForOpenScience/osf.io/pull/1762 """ from modularodm import Q from framework.auth.core import User from website.models import Comment from website.app import init_app import logging from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(): init_app(routes=False, set_backends=True, mfr=False) update_comments_viewed_timestamp() update_comments() def update_comments_viewed_timestamp(): users = User.find(Q('comments_viewed_timestamp', 'ne', None) | Q('comments_viewed_timestamp', 'ne', {})) for user in users: if user.comments_viewed_timestamp: for node in user.comments_viewed_timestamp: user.comments_viewed_timestamp[node] = {'node': user.comments_viewed_timestamp[node]} user.save() def update_comments(): comments = Comment.find() for comment in comments: comment.root_target = comment.node comment.page = Comment.OVERVIEW comment.is_hidden = False comment.save() if __name__ == '__main__': script_utils.add_file_logger(logger, __file__) main()
Revert "Updated semantic ui dependency." This reverts commit 32d815b9e0415822d4721eb86cf94d2ff46be786.
// Meteor package definition. Package.describe({ name: 'aramk:notifications', version: '0.2.0', summary: 'A notification widget.', git: 'https://github.com/aramk/meteor-notifications.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@0.9.0'); api.use([ 'coffeescript', 'underscore', 'templating', 'less', 'reactive-var@1.0.4', 'tracker@1.0.5', 'aramk:utility@0.8.6', 'aldeed:simple-schema@1.3.2', 'aldeed:collection2@2.3.3' ], 'client'); api.use([ 'semantic:ui-css@1.11.5' ], {weak: true}); api.imply('semantic:ui-css'); api.export('Notifications', 'client'); api.addFiles([ 'src/Notifications.coffee', 'src/notification.html', 'src/notification.coffee', 'src/notificationBar.html', 'src/notificationBar.coffee', 'src/notificationBar.less' ], 'client'); });
// Meteor package definition. Package.describe({ name: 'aramk:notifications', version: '0.2.0', summary: 'A notification widget.', git: 'https://github.com/aramk/meteor-notifications.git' }); Package.onUse(function (api) { api.versionsFrom('METEOR@0.9.0'); api.use([ 'coffeescript', 'underscore', 'templating', 'less', 'reactive-var@1.0.4', 'tracker@1.0.5', 'aramk:utility@0.8.6', 'aldeed:simple-schema@1.3.2', 'aldeed:collection2@2.3.3' ], 'client'); api.use([ 'semantic:ui-css@2.0.8' ], {weak: true}); api.imply('semantic:ui-css'); api.export('Notifications', 'client'); api.addFiles([ 'src/Notifications.coffee', 'src/notification.html', 'src/notification.coffee', 'src/notificationBar.html', 'src/notificationBar.coffee', 'src/notificationBar.less' ], 'client'); });
ui: Sort the album list after loading it
define(['jquery'], function($) { function Sidebar() { var sidebar = this; $('#sidebar-toggle-button').click(function() { sidebar.toggle(); }); sidebar.loadAlbums(); } Sidebar.prototype = { toggle: function() { $(document.body).toggleClass('sidebar-toggled'); }, loadAlbums: function() { var sidebar = this; var albumList = $('#album-list'); $.getJSON('/albums/', function(data) { data.sort(sidebar.albumCompareFunc); $.each(data, function(idx, album) { var li = document.createElement('li'); var a = document.createElement('a'); a.appendChild(document.createTextNode(album.name)); a.href = '#browse:' + album.name; li.appendChild(a); albumList.append(li); }); }); }, albumCompareFunc: function(a, b) { return a.name.localeCompare(b.name); } }; return Sidebar; }); // define
define(['jquery'], function($) { function Sidebar() { var sidebar = this; $('#sidebar-toggle-button').click(function() { sidebar.toggle(); }); sidebar.loadAlbums(); } Sidebar.prototype = { toggle: function() { $(document.body).toggleClass('sidebar-toggled'); }, loadAlbums: function() { var albumList = $('#album-list'); $.getJSON('/albums/', function(data) { $.each(data, function(idx, album) { var li = document.createElement('li'); var a = document.createElement('a'); a.appendChild(document.createTextNode(album.name)); a.href = '#browse:' + album.name; li.appendChild(a); albumList.append(li); }); }); } }; return Sidebar; }); // define
[tests] Remove test for deprecated createmultsig option
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], []] def run_test(self): # This test should be used to verify correct behaviour of deprecated # RPC methods with and without the -deprecatedrpc flags. For example: # # self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") # assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) # self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) # # There are currently no deprecated RPC methods in master, so this # test is currently empty. pass if __name__ == '__main__': DeprecatedRpcTest().main()
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_raises_rpc_error class DeprecatedRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True self.extra_args = [[], ["-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("Make sure that -deprecatedrpc=createmultisig allows it to take addresses") assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) if __name__ == '__main__': DeprecatedRpcTest().main()
Allow method URL to be an empty string
var _ = require('lodash'); module.exports = function (methodName, config) { // Ensure the minimum parameters have been passed if (!methodName || !_.isString(methodName)) { throw new Error('The first parameter passed to `addMethod` should be a string.'); } // If a function is inputted as the `config`, then just return - there's // really not much to validate. if (_.isFunction(config)) { return; } if (!config || !_.isObject(config)) { throw new Error('The `config` object should be an object.'); } // Check to see if the method has already been declared if (!_.isUndefined(this[methodName])) { throw new Error('Method `'+methodName+'` has already been declared.'); } // Ensure the config parameters have been specified correctly if (!config.url && config.url !== '') { throw new Error('The `url` config parameter should be declared.'); } if (!config.method || !_.isString(config.method)) { throw new Error('The `method` config parameter should be declared as string.'); } var method = config.method.toLowerCase(); var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ]; if (allowedMethods.indexOf(method) === -1) { throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', ')); } };
var _ = require('lodash'); module.exports = function (methodName, config) { // Ensure the minimum parameters have been passed if (!methodName || !_.isString(methodName)) { throw new Error('The first parameter passed to `addMethod` should be a string.'); } // If a function is inputted as the `config`, then just return - there's // really not much to validate. if (_.isFunction(config)) { return; } if (!config || !_.isObject(config)) { throw new Error('The `config` object should be an object.'); } // Check to see if the method has already been declared if (!_.isUndefined(this[methodName])) { throw new Error('Method `'+methodName+'` has already been declared.'); } // Ensure the config parameters have been specified correctly if (!config.url) { throw new Error('The `url` config parameter should be declared.'); } if (!config.method || !_.isString(config.method)) { throw new Error('The `method` config parameter should be declared as string.'); } var method = config.method.toLowerCase(); var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ]; if (allowedMethods.indexOf(method) === -1) { throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', ')); } };
Use try clause for config in optimizer
"""Module for optimized functions Some methods performed in Python may be slowing down solvers. In this optimization module we place optimized functions that are to be used instead of default Python methods. Some methods are implemented solely in Cython and only called from within the regular Python modules. """ import os import importlib from functools import wraps from . import cython try: from . import numba except ModuleNotFoundError: numba = None def optimizer(func): """Decorator used to wrap calls to optimized versions of functions.""" from shenfun.config import config mod = 'cython' verbose = False try: mod = config['optimization']['mode'] verbose = config['optimization']['verbose'] except KeyError: pass if mod.lower() not in ('cython', 'numba'): # Use python function if verbose: print(func.__name__ + ' not optimized') return func mod = importlib.import_module('shenfun.optimization.'+mod.lower()) fun = getattr(mod, func.__name__, func) if verbose: if fun is func: print(fun.__name__ + ' not optimized') @wraps(func) def wrapped_function(*args, **kwargs): u0 = fun(*args, **kwargs) return u0 return wrapped_function
"""Module for optimized functions Some methods performed in Python may be slowing down solvers. In this optimization module we place optimized functions that are to be used instead of default Python methods. Some methods are implemented solely in Cython and only called from within the regular Python modules. """ import os import importlib from functools import wraps from . import cython try: from . import numba except ModuleNotFoundError: numba = None def optimizer(func): """Decorator used to wrap calls to optimized versions of functions.""" from shenfun.config import config mod = config['optimization']['mode'] verbose = config['optimization']['verbose'] if mod.lower() not in ('cython', 'numba'): # Use python function if verbose: print(func.__name__ + ' not optimized') return func mod = importlib.import_module('shenfun.optimization.'+mod.lower()) fun = getattr(mod, func.__name__, func) if verbose: if fun is func: print(fun.__name__ + ' not optimized') @wraps(func) def wrapped_function(*args, **kwargs): u0 = fun(*args, **kwargs) return u0 return wrapped_function
Allow to run tests against the pecl client
<?php namespace Tarantool\Tests\Integration; use Tarantool\Client as TarantoolClient; use Tarantool\Connection\SocketConnection; use Tarantool\Tests\Adapter\Tarantool; trait Client { /** * @var TarantoolClient */ private static $client; /** * @beforeClass */ public static function setUpClient() { self::$client = self::createClient(); } /** * @afterClass */ public static function tearDownClient() { self::$client = null; } protected static function createClient($host = null, $port = null) { $host = null === $host ? getenv('TARANTOOL_HOST') : $host; $port = null === $port ? getenv('TARANTOOL_PORT') : $port; if (getenv('TARANTOOL_CLIENT_PECL')) { return new Tarantool($host, $port); } return new TarantoolClient(new SocketConnection($host, $port)); } protected static function getTotalSelectCalls() { $response = self::$client->evaluate('return box.stat().SELECT.total'); return $response->getData()[0]; } }
<?php namespace Tarantool\Tests\Integration; use Tarantool\Client as TarantoolClient; use Tarantool\Connection\SocketConnection; trait Client { /** * @var TarantoolClient */ private static $client; /** * @beforeClass */ public static function setUpClient() { self::$client = self::createClient(); } /** * @afterClass */ public static function tearDownClient() { self::$client = null; } protected static function createClient($host = null, $port = null) { $host = null === $host ? getenv('TARANTOOL_HOST') : $host; $port = null === $port ? getenv('TARANTOOL_PORT') : $port; return new TarantoolClient(new SocketConnection($host, $port)); } protected static function getTotalSelectCalls() { $response = self::$client->evaluate('return box.stat().SELECT.total'); return $response->getData()[0]; } }
Replace `var` with `let` to increase code consistency
"use strict"; import generator from "./generator_function.js"; import asyncGenerator from "./async_generator_function"; it('should correctly import generator function', () => { expect(typeof generator).toBe("function"); }); it('should correctly build the correct function string', () => { expect(generator.toString().indexOf('function* ')).toBe(0); // 0 }); it('should correctly provide the generator function interface', () => { let gen = generator(); expect(gen.next().value).toBe(0); expect(gen.next().value).toBe(1); expect(gen.next().value).toBe(2); }); it('should correctly import async generator function', () => { expect(typeof asyncGenerator).toBe("function"); }); it('should correctly build the correct async function string', () => { expect(asyncGenerator.toString().indexOf('async function* ')).toBe(0); }); it('should correctly provide the async generator function interface', async () => { let gen = asyncGenerator(1, 5); let start = 0; for await (let value of gen) { start += 1; expect(value).toBe(start); } });
import generator from "./generator_function.js"; import asyncGenerator from "./async_generator_function"; it('should correctly import generator function', () => { expect(typeof generator).toBe("function"); }); it('should correctly build the correct function string', () => { expect(generator.toString().indexOf('function* ')).toBe(0); // 0 }); it('should correctly provide the generator function interface', () => { var gen = generator(); expect(gen.next().value).toBe(0); expect(gen.next().value).toBe(1); expect(gen.next().value).toBe(2); }); it('should correctly import async generator function', () => { expect(typeof asyncGenerator).toBe("function"); }); it('should correctly build the correct async function string', () => { expect(asyncGenerator.toString().indexOf('async function* ')).toBe(0); }); it('should correctly provide the async generator function interface', async () => { let gen = asyncGenerator(1, 5); let start = 0; for await (let value of gen) { start += 1; expect(value).toBe(start); } });
Simplify buildLink for Edit History support
<?php class SV_ConversationImprovements_XenForo_Route_Prefix_Conversations extends XFCP_SV_ConversationImprovements_XenForo_Route_Prefix_Conversations { public function buildLink($originalPrefix, $outputPrefix, $action, $extension, $data, array &$extraParams) { if (isset($data['message_id']) && !isset($extraParams['m']) && !isset($extraParams['message_id']) && ($action == 'message')) { $extraParams['message_id'] = $data['message_id']; } return parent::buildLink($originalPrefix, $outputPrefix, $action, $extension, $data, $extraParams); } }
<?php class SV_ConversationImprovements_XenForo_Route_Prefix_Conversations extends XFCP_SV_ConversationImprovements_XenForo_Route_Prefix_Conversations { public function buildLink($originalPrefix, $outputPrefix, $action, $extension, $data, array &$extraParams) { if (isset($data['message_id']) && !isset($extraParams['message_id']) && ($action != 'message' || $action == 'like' || $action == 'message-history' || $action == 'ip' || $action == 'preview' )) { $extraParams['message_id'] = $data['message_id']; } return parent::buildLink($originalPrefix, $outputPrefix, $action, $extension, $data, $extraParams); } }
Add Searchable Mixin for API
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from django.db.models.deletion import ProtectedError from rest_framework import status from rest_framework.filters import SearchFilter from rest_framework.response import Response class PermissionHelperMixin(object): """ Mixin to return a helper text to admin users in permission configuration. """ @classmethod def get_help_text(cls): raise NotImplementedError() class ProtectedModelViewSetMixin(object): """ Mixin to catch ProtectedError exceptions and return a reasonable response error to the user. """ def destroy(self, request, *args, **kwargs): try: return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs) except ProtectedError as exc: ref_obj = exc.protected_objects[0].__class__.__name__ msg = "This object can not be deleted because it is referenced by {}".format(ref_obj) return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST) class SearchableMixin(object): """ Mixin to give search capabilities for `ViewSet` """ filter_backends = (SearchFilter,) search_fields = ("=id",)
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the OSL-3.0 license found in the # LICENSE file in the root directory of this source tree. from django.db.models.deletion import ProtectedError from rest_framework import status from rest_framework.response import Response class PermissionHelperMixin(object): """ Mixin to return a helper text to admin users in permission configuration. """ @classmethod def get_help_text(cls): raise NotImplementedError() class ProtectedModelViewSetMixin(object): """ Mixin to catch ProtectedError exceptions and return a reasonable response error to the user. """ def destroy(self, request, *args, **kwargs): try: return super(ProtectedModelViewSetMixin, self).destroy(request, *args, **kwargs) except ProtectedError as exc: ref_obj = exc.protected_objects[0].__class__.__name__ msg = "This object can not be deleted because it is referenced by {}".format(ref_obj) return Response(data={"error": msg}, status=status.HTTP_400_BAD_REQUEST)
Address review comment: Document return type.
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with the existing known state. https://clusterhq.atlassian.net/browse/FLOC-1269 will deal with semantics of expiring data, which should happen so stale information isn't treated as correct. """ def __init__(self): self._nodes = {} def update_node_state(self, hostname, node_state): """ Update the state of a given node. :param unicode hostname: The node's identifier. :param NodeState node_state: The state of the node. """ self._nodes[hostname] = node_state def as_deployment(self): """ Return cluster state as a Deployment object. :return Deployment: Current state of the cluster. """ return Deployment(nodes=frozenset([ Node(hostname=hostname, applications=frozenset( node_state.running + node_state.not_running)) for hostname, node_state in self._nodes.items()]))
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Combine and retrieve current cluster state. """ from twisted.application.service import Service from ._model import Deployment, Node class ClusterStateService(Service): """ Store known current cluster state, and combine partial updates with the existing known state. https://clusterhq.atlassian.net/browse/FLOC-1269 will deal with semantics of expiring data, which should happen so stale information isn't treated as correct. """ def __init__(self): self._nodes = {} def update_node_state(self, hostname, node_state): """ Update the state of a given node. :param unicode hostname: The node's identifier. :param NodeState node_state: The state of the node. """ self._nodes[hostname] = node_state def as_deployment(self): """ Return cluster state as a Deployment object. """ return Deployment(nodes=frozenset([ Node(hostname=hostname, applications=frozenset( node_state.running + node_state.not_running)) for hostname, node_state in self._nodes.items()]))
Fix spec in which order of loading was different in travis server
<?php namespace Spec\PHPSpec\Loader; use \PHPSpec\Loader\DirectoryLoader, \PHPSpec\Util\SpecIterator; class DescribeDirectoryLoader extends \PHPSpec\Context { function itLoadsAllExampleGroupsUnderADirectory() { $loader = new DirectoryLoader; $examples = $loader->load(__DIR__ . '/_files/Bar'); $this->spec(count($examples))->should->be(3); foreach ($examples as $example) { $class = get_class($example); if (!in_array($class, array('DescribeA', 'DescribeB', 'DescribeC'))) { $this->fail("$class is not meant to be loaded"); } } } }
<?php namespace Spec\PHPSpec\Loader; use \PHPSpec\Loader\DirectoryLoader, \PHPSpec\Util\SpecIterator; class DescribeDirectoryLoader extends \PHPSpec\Context { function itLoadsAllExampleGroupsUnderADirectory() { $loader = new DirectoryLoader; $examples = $loader->load(__DIR__ . '/_files/Bar'); $examples = new SpecIterator($examples); $i = array('A', 'B', 'C'); $examples -> withEach ( function ($example) use (&$i) { $example->should->beAnInstanceOf('Describe' . current($i)); next($i); }); } }
Check for oninput support instead of browser type
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { var inputEvents = "input"; if (!("oninput" in document || "oninput" in $("<input>")[0])) { inputEvents += " keyup"; } jQuery.fn.restrict = function(sanitizationFunc) { $(this).bind(inputEvents, function(e) { $(this).val(sanitizationFunc($(this).val())); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); } })(jQuery);
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { jQuery.fn.restrict = function(sanitizationFunc) { $(this).bind($.browser.msie ? "keyup" : "input", function(e) { $(this).val(sanitizationFunc($(this).val())); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); } })(jQuery);
Remove superfluous license headers (OKAPI-109)
package org.folio.okapi.bean; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class Permission { private String permissionName; private String displayName; private String description; private String[] subPermissions; public Permission() { } public Permission(Permission other) { this.permissionName = other.permissionName; this.displayName = other.displayName; this.description = other.description; this.subPermissions = other.subPermissions; } public String getPermissionName() { return permissionName; } public void setPermissionName(String permissionName) { this.permissionName = permissionName; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String[] getSubPermissions() { return subPermissions; } public void setSubPermissions(String[] subPermissions) { this.subPermissions = subPermissions; } }
/* * Copyright (c) 2015-2017, Index Data * All rights reserved. * See the file LICENSE for details. */ package org.folio.okapi.bean; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class Permission { private String permissionName; private String displayName; private String description; private String[] subPermissions; public Permission() { } public Permission(Permission other) { this.permissionName = other.permissionName; this.displayName = other.displayName; this.description = other.description; this.subPermissions = other.subPermissions; } public String getPermissionName() { return permissionName; } public void setPermissionName(String permissionName) { this.permissionName = permissionName; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String[] getSubPermissions() { return subPermissions; } public void setSubPermissions(String[] subPermissions) { this.subPermissions = subPermissions; } }
Change Flask interface to 0.0.0.0
from flask import Flask class Driver: ''' Holds the driver state so the flasked script can change behaviour based on what the user injects via HTTP ''' name = 'nobody' def start(self, name): self.name = name return self.name def stop(self): self.name = 'nobody' return self.name app = Flask('proxapp') app.host = '0.0.0.0' driver = Driver() def register(context): context.app_registry.add(app, 'proxapp', 5000) return context @app.route('/') def index(): return 'Try /start/:driver or /stop/:driver instead' @app.route('/stop') def stop_driver(): driver.stop() return 'No drivers running\n' @app.route('/<driver_name>/start') def start_driver(driver_name): print(driver.start(driver_name)) return '{} driver started\n'.format(driver_name)
from flask import Flask class Driver: ''' Holds the driver state so the flasked script can change behaviour based on what the user injects via HTTP ''' name = 'nobody' def start(self, name): self.name = name return self.name def stop(self): self.name = 'nobody' return self.name app = Flask('proxapp') driver = Driver() def register(context): context.app_registry.add(app, 'proxapp', 5000) return context @app.route('/') def index(): return 'Try /start/:driver or /stop/:driver instead' @app.route('/stop') def stop_driver(): driver.stop() return 'No drivers running\n' @app.route('/<driver_name>/start') def start_driver(driver_name): print(driver.start(driver_name)) return '{} driver started\n'.format(driver_name)
Add crm_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-80638551c5a66adf0a49181f6ff6ae283ced3709
{ "name" : "Customer & Supplier Relationship Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_crm.html", "category" : "Generic Modules/CRM & SRM", "description": """The Tiny ERP case and request tracker enables a group of people to intelligently and efficiently manage tasks, issues, and requests. It manages key tasks such as communication, identification, prioritization, assignment, resolution and notification. Tiny ERP ensures that all cases are successfly tracked by users, customers and suppliers. It can automatically send reminders, escalate the request, trigger specific methods and lots of others actions based on your enterprise own rules. The greatest thing about this system is that users don't need to do anything special. They can just send email to the request tracker. Tiny ERP will take care of thanking them for their message, automatically routing it to the appropriate staff, and making sure all future correspondence gets to the right place. The CRM module has a email gateway for the synchronisation interface between mails and Tiny ERP.""", "depends" : ["base", "account"], "init_xml" : ["crm_data.xml"], "demo_xml" : ["crm_demo.xml"], "update_xml" : ["crm_view.xml", "crm_report.xml", "crm_wizard.xml","crm_security.xml"], "active": False, "installable": True }
{ "name" : "Customer & Supplier Relationship Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_crm.html", "category" : "Generic Modules/CRM & SRM", "description": """The Tiny ERP case and request tracker enables a group of people to intelligently and efficiently manage tasks, issues, and requests. It manages key tasks such as communication, identification, prioritization, assignment, resolution and notification. Tiny ERP ensures that all cases are successfly tracked by users, customers and suppliers. It can automatically send reminders, escalate the request, trigger specific methods and lots of others actions based on your enterprise own rules. The greatest thing about this system is that users don't need to do anything special. They can just send email to the request tracker. Tiny ERP will take care of thanking them for their message, automatically routing it to the appropriate staff, and making sure all future correspondence gets to the right place. The CRM module has a email gateway for the synchronisation interface between mails and Tiny ERP.""", "depends" : ["base", "account"], "init_xml" : ["crm_data.xml"], "demo_xml" : ["crm_demo.xml"], "update_xml" : ["crm_view.xml", "crm_report.xml", "crm_wizard.xml"], "active": False, "installable": True }
Set default load speed to 250 ms
$(function(){ $('.cd-slideshow').each(function(){ var $this = this; var pageSpeed = ifDataExists($this, 'page-speed', 5000); var fadeSpeed = ifDataExists($this, 'fade-speed', 1000); $('> :gt(0)', $this).hide(); if (!$('> :eq(0)', $this).hasClass('cd-loader')) { $('> :eq(0)', $this).css('display', 'block'); } setInterval(function(){$('> :first-child',$this).fadeOut(fadeSpeed).next().fadeIn(fadeSpeed).end().appendTo($this);}, pageSpeed); }) $(".cd-loader").each(function() { var $this = $(this); $this.on("load", handleLoad); if (this.complete) { $this.off("load", handleLoad); handleLoad.call(this); } }); function handleLoad(){ var loadSpeed = ifDataExists(this, 'load-speed', 250); $(this).fadeIn(loadSpeed); } function ifDataExists(saveThis, data, defaultValue){ if ($(saveThis).attr('data-' + data)) { return $(saveThis).data(data); } return defaultValue; } });
$(function(){ $('.cd-slideshow').each(function(){ var $this = this; var pageSpeed = ifDataExists($this, 'page-speed', 5000); var fadeSpeed = ifDataExists($this, 'fade-speed', 1000); $('> :gt(0)', $this).hide(); if (!$('> :eq(0)', $this).hasClass('cd-loader')) { $('> :eq(0)', $this).css('display', 'block'); } setInterval(function(){$('> :first-child',$this).fadeOut(fadeSpeed).next().fadeIn(fadeSpeed).end().appendTo($this);}, pageSpeed); }) $(".cd-loader").each(function() { var $this = $(this); $this.on("load", handleLoad); if (this.complete) { $this.off("load", handleLoad); handleLoad.call(this); } }); function handleLoad(){ var loadSpeed = ifDataExists(this, 'load-speed', 750); $(this).fadeIn(loadSpeed); } function ifDataExists(saveThis, data, defaultValue){ if ($(saveThis).attr('data-' + data)) { return $(saveThis).data(data); } return defaultValue; } });
Improve error message for type mismatch.
package flow import ( "fmt" "go/types" "github.com/dustin/go-humanize" ) func cardinalityMismatchError(source, dest ComponentID, sourceSig, destSig *types.Tuple) error { return fmt.Errorf(` As I infer the types of values flowing through your program, I see a mismatch in this connection. %[1]s -> %[2]s There are %[3]d results coming from %[1]s: %[4]s But %[2]s is expecting %[5]d argument[s]: %[6]s HINT: These should have identical length and types. `, source, dest, sourceSig.Len(), sourceSig, destSig.Len(), destSig) } func typeMismatchError(source, dest ComponentID, argIndex int, sourceType, endType types.Type) error { return fmt.Errorf(` As I infer the types of values flowing through your program, I see a mismatch in this connection. %[1]s -> %[2]s The %[3]s result of %[1]s has type: %[4]s But the %[3]s argument of %[2]s has type: %[5]s HINT: These should have identical types. `, source, dest, humanize.Ordinal(argIndex+1), sourceType, endType) }
package flow import ( "fmt" "go/types" "github.com/dustin/go-humanize" ) func cardinalityMismatchError(source, dest ComponentID, sourceSig, destSig *types.Tuple) error { return fmt.Errorf(` As I infer the types of values flowing through your program, I see a mismatch in this connection. %[1]s -> %[2]s There are %[3]d results coming from %[1]s: %[4]s But %[2]s is expecting %[5]d argument[s]: %[6]s HINT: These should have identical length and types. `, source, dest, sourceSig.Len(), sourceSig, destSig.Len(), destSig) } func typeMismatchError(source, dest ComponentID, argIndex int, sourceType, endType types.Type) error { return fmt.Errorf(` As I infer the types of values flowing through your program, I see a mismatch in this connection. %[1]s -> %[2]s The %[3]s result of %[1]s has type: %[4]s But the %[3]s argument of %[2]s has type: %[5]s HINT: These should have identical types. `, source, dest, humanize.Ordinal(argIndex), sourceType, endType) }
Support Grappelli in inline ckeditor initialisation.
$(function() { initialiseCKEditor(); initialiseCKEditorInInlinedForms(); function initialiseCKEditorInInlinedForms() { $(".add-row a, .grp-add-handler").click(function () { initialiseCKEditor(); return true; }); } }); function initialiseCKEditor() { $('textarea[data-type=ckeditortype]').each(function(){ if($(this).data('processed') == "0" && $(this).attr('id').indexOf('__prefix__') == -1){ $(this).data('processed',"1"); CKEDITOR.replace($(this).attr('id'), $(this).data('config')); } }); }
$(function() { initialiseCKEditor(); initialiseCKEditorInInlinedForms(); function initialiseCKEditorInInlinedForms() { $(".add-row a").click(function () { initialiseCKEditor(); return true; }); } }); function initialiseCKEditor() { $('textarea[data-type=ckeditortype]').each(function(){ if($(this).data('processed') == "0" && $(this).attr('id').indexOf('__prefix__') == -1){ $(this).data('processed',"1"); CKEDITOR.replace($(this).attr('id'), $(this).data('config')); } }); }
Remove assert_ functions from nose.
"""Tests directories set in the permamodel package definition file.""" import os from .. import data_directory, examples_directory, permamodel_directory, tests_directory def test_permamodel_directory_is_set(): assert permamodel_directory is not None def test_data_directory_is_set(): assert data_directory is not None def test_examples_directory_is_set(): assert examples_directory is not None def test_tests_directory_is_set(): assert tests_directory is not None def test_permamodel_directory_exists(): assert os.path.isdir(permamodel_directory) def test_data_directory_exists(): assert os.path.isdir(data_directory) def test_examples_directory_exists(): assert os.path.isdir(examples_directory) def test_tests_directory_exists(): assert os.path.isdir(tests_directory)
"""Tests directories set in the permamodel package definition file.""" import os from nose.tools import assert_true from .. import (permamodel_directory, data_directory, examples_directory, tests_directory) def test_permamodel_directory_is_set(): assert(permamodel_directory is not None) def test_data_directory_is_set(): assert(data_directory is not None) def test_examples_directory_is_set(): assert(examples_directory is not None) def test_tests_directory_is_set(): assert(tests_directory is not None) def test_permamodel_directory_exists(): assert_true(os.path.isdir(permamodel_directory)) def test_data_directory_exists(): assert_true(os.path.isdir(data_directory)) def test_examples_directory_exists(): assert_true(os.path.isdir(examples_directory)) def test_tests_directory_exists(): assert_true(os.path.isdir(tests_directory))
Use consistent capitalization in comments
/** * App Dependencies. */ var loopback = require('loopback') , app = module.exports = loopback() , fs = require('fs') , path = require('path') , request = require('request') , TaskEmitter = require('strong-task-emitter'); // Expose a rest api app.use(loopback.rest()); // Add static files app.use(loopback.static(path.join(__dirname, 'public'))); // Require models fs .readdirSync(path.join(__dirname, './models')) .filter(function (m) { return path.extname(m) === '.js'; }) .forEach(function (m) { // expose model over rest app.model(require('./models/' + m)); }); // Enable docs app.docs({basePath: 'http://localhost:3000'}); // Start the server app.listen(3000);
/** * App Dependencies. */ var loopback = require('loopback') , app = module.exports = loopback() , fs = require('fs') , path = require('path') , request = require('request') , TaskEmitter = require('strong-task-emitter'); // expose a rest api app.use(loopback.rest()); // Add static files app.use(loopback.static(path.join(__dirname, 'public'))); // require models fs .readdirSync(path.join(__dirname, './models')) .filter(function (m) { return path.extname(m) === '.js'; }) .forEach(function (m) { // expose model over rest app.model(require('./models/' + m)); }); // enable docs app.docs({basePath: 'http://localhost:3000'}); // start the server app.listen(3000);
Add alerts for web sockets
var hostname = window.location.hostname; var wsaddr = "wss://".concat(hostname, ":1234/api"); /* * Useful functions */ function map_alert(message) { $('body').prepend('<div style="padding: 5px; z-index: 10; position: absolute; right: 0; left: 0;"> <div id="inner-message" class="alert alert-info alert-dismissible show"><button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span></button>' + message + '</div></div>'); $(".alert-dismissible").delay(3000).fadeOut("slow", function () { $(this).remove(); }); } function message_handler(event) { map_alert(event.data); } /* * Initialize the page SVG and controls */ var width = $(document).width(); var height = $(document).height(); // Disable the scroll bar document.documentElement.style.overflow = 'hidden'; // Only for IE document.body.scroll = 'no'; var zoom = d3.zoom() .scaleExtent([1, 8]) .on("zoom", zoomed); var svg = d3.select("svg") .attr("width", width) .attr("height", height) g = svg.append("g"); function zoomed () { g.attr("transform", d3.event.transform); } svg.call(zoom); g.append("svg:image") .attr("xlink:href", "images/US.svg") /* * Connect to the web socket */ var paladinws = new PaladinWebSocket(wsaddr); paladinws.ws.onmessage = message_handler; map_alert("Connected to " + wsaddr);
var hostname = window.location.hostname; var wsaddr = "wss://".concat(hostname, ":1234/api"); console.log("Connecting to " + wsaddr); var paladinws = new PaladinWebSocket(wsaddr); var width = $(document).width(); var height = $(document).height(); // Disable the scroll bar document.documentElement.style.overflow = 'hidden'; // Only for IE document.body.scroll = 'no'; var zoom = d3.zoom() .scaleExtent([1, 8]) .on("zoom", zoomed); var svg = d3.select("svg") .attr("width", width) .attr("height", height) g = svg.append("g"); function zoomed () { g.attr("transform", d3.event.transform); } svg.call(zoom); g.append("svg:image") .attr("xlink:href", "images/US.svg")
Add require to test example.
import test from 'ava'; import examplesLoader from '../loaders/examples.loader'; test('should return valid, parsable JS', t => { let exampleMarkdown = ` # header const _ = require('lodash'); <div/> text \`\`\` <span/> \`\`\` `; let result = examplesLoader.call({}, exampleMarkdown); t.truthy(result); t.notThrows(() => new Function(result), SyntaxError); // eslint-disable-line no-new-func }); // componentName query option test('should replace all occurrences of __COMPONENT__ with provided query.componentName', t => { const exampleMarkdown = ` <div> <__COMPONENT__> <span>text</span> <span>Name of component: __COMPONENT__</span> </__COMPONENT__> <__COMPONENT__ /> </div> `; const result = examplesLoader.call({ query: '?componentName=FooComponent' }, exampleMarkdown); t.notRegex(result, /__COMPONENT__/); t.regex(result, /FooComponent/); t.is(result.match(/FooComponent/g).length, 4); });
import test from 'ava'; import examplesLoader from '../loaders/examples.loader'; test('should return valid, parsable JS', t => { let exampleMarkdown = ` # header <div/> text \`\`\` <span/> \`\`\` `; let result = examplesLoader.call({}, exampleMarkdown); t.truthy(result); t.notThrows(() => new Function(result), SyntaxError); // eslint-disable-line no-new-func }); // componentName query option test('should replace all occurrences of __COMPONENT__ with provided query.componentName', t => { const exampleMarkdown = ` <div> <__COMPONENT__> <span>text</span> <span>Name of component: __COMPONENT__</span> </__COMPONENT__> <__COMPONENT__ /> </div> `; const result = examplesLoader.call({ query: '?componentName=FooComponent' }, exampleMarkdown); t.notRegex(result, /__COMPONENT__/); t.regex(result, /FooComponent/); t.is(result.match(/FooComponent/g).length, 4); });
Support Python 3.6 event loops in this example
import sys from pythonosc.osc_server import AsyncIOOSCUDPServer from pythonosc.dispatcher import Dispatcher import asyncio def filter_handler(address, *args): print(f"{address}: {args}") dispatcher = Dispatcher() dispatcher.map("/filter", filter_handler) ip = "127.0.0.1" port = 1337 async def loop(): """Example main loop that only runs for 10 iterations before finishing""" for i in range(10): print(f"Loop {i}") await asyncio.sleep(1) async def init_main(): server = AsyncIOOSCUDPServer((ip, port), dispatcher, asyncio.get_event_loop()) transport, protocol = await server.create_serve_endpoint() # Create datagram endpoint and start serving await loop() # Enter main loop of program transport.close() # Clean up serve endpoint if sys.version_info >= (3, 7): asyncio.run(init_main()) else: # TODO(python-upgrade): drop this once 3.6 is no longer supported event_loop = asyncio.get_event_loop() event_loop.run_until_complete(init_main()) event_loop.close()
from pythonosc.osc_server import AsyncIOOSCUDPServer from pythonosc.dispatcher import Dispatcher import asyncio def filter_handler(address, *args): print(f"{address}: {args}") dispatcher = Dispatcher() dispatcher.map("/filter", filter_handler) ip = "127.0.0.1" port = 1337 async def loop(): """Example main loop that only runs for 10 iterations before finishing""" for i in range(10): print(f"Loop {i}") await asyncio.sleep(1) async def init_main(): server = AsyncIOOSCUDPServer((ip, port), dispatcher, asyncio.get_event_loop()) transport, protocol = await server.create_serve_endpoint() # Create datagram endpoint and start serving await loop() # Enter main loop of program transport.close() # Clean up serve endpoint asyncio.run(init_main())
Set to 1.1 for new release
from setuptools import find_packages, setup import sys if 'install' in sys.argv: import webbrowser webbrowser.open('https://www.youtube.com/watch?v=NMZcwXh7HDA', new=2, autoraise=True) setup( name='rdalal', version='1.1', description='Install some sweet Rehan', author='Will Kahn-Greene', author_email='willkg@bluesock.org', url='https://github.com/willkg/rdalal', zip_safe=True, packages=find_packages(), entry_points=""" [console_scripts] rdalal=rdalal.cmdline:run """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
from setuptools import find_packages, setup import sys if 'install' in sys.argv: import webbrowser webbrowser.open('https://www.youtube.com/watch?v=NMZcwXh7HDA', new=2, autoraise=True) setup( name='rdalal', version='1.0', description='Install some sweet Rehan', author='Will Kahn-Greene', author_email='willkg@bluesock.org', url='https://github.com/willkg/rdalal', zip_safe=True, packages=find_packages(), entry_points=""" [console_scripts] rdalal=rdalal.cmdline:run """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: Unix', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Fix wrong link in JS sources
/*! * JS-Tricks main script */ (function (w, d) { // Touch detection ( ͡ᵔ ͜ʖ ͡ᵔ) // @see http://js-tricks.com/detect-touch-devices-using-javascript if('ontouchstart' in window) { var htmlEl = d.getElementsByTagName('html')[0]; var htmlElClasses = htmlEl.className; htmlEl.className += (htmlElClasses.length ? ' ' : '') + 'touch'; } // Add "language-*" classes to <pre> elements d.addEventListener('DOMContentLoaded', function () { Array.prototype.forEach.call(d.querySelectorAll('pre > code'), function (node) { var parentNode = node.parentNode; var nodeClasses = node.className.split(' '); for (var i = 0; i < nodeClasses.length; i++) { if (nodeClasses[i].match(/^language-/)) { // Native IE9 support for ClassList would be a dream here... var parentNodeClassName = parentNode.className; parentNode.className += (parentNodeClassName.length ? ' ' : '') + nodeClasses[i]; break; } } }); }); })(window, document);
/*! * JS-Tricks main script */ (function (w, d) { // Touch detection ( ͡ᵔ ͜ʖ ͡ᵔ) // @see http://localhost:8080/detect-touch-devices-using-javascript if('ontouchstart' in window) { var htmlEl = d.getElementsByTagName('html')[0]; var htmlElClasses = htmlEl.className; htmlEl.className += (htmlElClasses.length ? ' ' : '') + 'touch'; } // Add "language-*" classes to <pre> elements d.addEventListener('DOMContentLoaded', function () { Array.prototype.forEach.call(d.querySelectorAll('pre > code'), function (node) { var parentNode = node.parentNode; var nodeClasses = node.className.split(' '); for (var i = 0; i < nodeClasses.length; i++) { if (nodeClasses[i].match(/^language-/)) { // Native IE9 support for ClassList would be a dream here... var parentNodeClassName = parentNode.className; parentNode.className += (parentNodeClassName.length ? ' ' : '') + nodeClasses[i]; break; } } }); }); })(window, document);
Make mock Model class extend object for Python 2 compat
from django.test import TestCase as BaseTestCase from django.test import RequestFactory from permissions import PermissionsRegistry as BasePermissionsRegistry class PermissionsRegistry(BasePermissionsRegistry): def _get_user_model(self): return User def _get_model_instance(self, model, **kwargs): return model(**kwargs) class Model(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class User(Model): def __init__(self, **kwargs): kwargs.setdefault('permissions', []) super(User, self).__init__(**kwargs) def is_anonymous(self): return False class AnonymousUser(User): def is_anonymous(self): return True class TestCase(BaseTestCase): def setUp(self): self.registry = PermissionsRegistry() self.request_factory = RequestFactory()
from django.test import TestCase as BaseTestCase from django.test import RequestFactory from permissions import PermissionsRegistry as BasePermissionsRegistry class PermissionsRegistry(BasePermissionsRegistry): def _get_user_model(self): return User def _get_model_instance(self, model, **kwargs): return model(**kwargs) class Model: def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class User(Model): def __init__(self, **kwargs): kwargs.setdefault('permissions', []) super(User, self).__init__(**kwargs) def is_anonymous(self): return False class AnonymousUser(User): def is_anonymous(self): return True class TestCase(BaseTestCase): def setUp(self): self.registry = PermissionsRegistry() self.request_factory = RequestFactory()
Fix a check for an empty mediaType We need it for the old attachments.
define(["app/app"], function(App) { "use strict"; App.Attachment = DS.Model.extend({ file: DS.attr('file'), // FormData File object url: DS.attr('string'), thumbnailUrl: DS.attr('string'), fileName: DS.attr('string'), fileSize: DS.attr('number'), mediaType: DS.attr('string'), createdAt: DS.attr('string'), updatedAt: DS.attr('string'), createdBy: DS.belongsTo('user'), post: DS.belongsTo('post'), isImage: function() { return this.get('mediaType') === 'image' || Ember.isEmpty(this.get('mediaType')) }.property('mediaType'), isGeneral: function() { return this.get('mediaType') === 'general' }.property('mediaType'), isAudio: function() { return this.get('mediaType') === 'audio' }.property('mediaType'), formatSize: function() { var decimals = 1 var bytes = this.get('fileSize') if (bytes == 0) return '0 Byte' var k = 1000 var dm = decimals + 1 || 3 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] var i = Math.floor(Math.log(bytes) / Math.log(k)) return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i] }.property('fileSize') }) })
define(["app/app"], function(App) { "use strict"; App.Attachment = DS.Model.extend({ file: DS.attr('file'), // FormData File object url: DS.attr('string'), thumbnailUrl: DS.attr('string'), fileName: DS.attr('string'), fileSize: DS.attr('number'), mediaType: DS.attr('string'), createdAt: DS.attr('string'), updatedAt: DS.attr('string'), createdBy: DS.belongsTo('user'), post: DS.belongsTo('post'), isImage: function() { return this.get('mediaType') === 'image' || this.get('mediaType') === null }.property('mediaType'), isGeneral: function() { return this.get('mediaType') === 'general' }.property('mediaType'), isAudio: function() { return this.get('mediaType') === 'audio' }.property('mediaType'), formatSize: function() { var decimals = 1 var bytes = this.get('fileSize') if (bytes == 0) return '0 Byte' var k = 1000 var dm = decimals + 1 || 3 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] var i = Math.floor(Math.log(bytes) / Math.log(k)) return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i] }.property('fileSize') }) })
po: Append string into .pot file When more than one item was returned, then `potData` would be appended as array and not as string.
// Extract the title from cockpit's manifest.json and append it to a .pot file // This assumes the .pot file already exists. const fs = require("fs"); const jsel = require("jsel"); if (process.argv.length != 4) { console.error("Usage: add-title <manifest.json> <POT-file>"); process.exit(1); } var manifestJsonName = process.argv[2]; var outputPOTName = process.argv[3]; var manifest = JSON.parse(fs.readFileSync(manifestJsonName, "utf8")); // Anything in a "label" property is translatable // For each, output the string itself as the msgid, and an // empty msgstr (because it's a .pot) var dom = jsel(manifest); var potData = dom.selectAll("//@label").map(label => { return ` #: ${manifestJsonName} msgid "${label}" msgstr "" `; }); fs.appendFileSync(outputPOTName, potData.join(""), "utf8");
// Extract the title from cockpit's manifest.json and append it to a .pot file // This assumes the .pot file already exists. const fs = require("fs"); const jsel = require("jsel"); if (process.argv.length != 4) { console.error("Usage: add-title <manifest.json> <POT-file>"); process.exit(1); } var manifestJsonName = process.argv[2]; var outputPOTName = process.argv[3]; var manifest = JSON.parse(fs.readFileSync(manifestJsonName, "utf8")); // Anything in a "label" property is translatable // For each, output the string itself as the msgid, and an // empty msgstr (because it's a .pot) var dom = jsel(manifest); var potData = dom.selectAll("//@label").map(label => { return ` #: ${manifestJsonName} msgid "${label}" msgstr "" `; }); fs.appendFileSync(outputPOTName, potData, "utf8");
Resolve upmerge conflict in composer
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Shipping\Resolver; use Sylius\Component\Registry\PrioritizedServiceRegistryInterface; use Sylius\Component\Shipping\Model\ShippingSubjectInterface; final class CompositeMethodsResolver implements ShippingMethodsResolverInterface { public function __construct(private PrioritizedServiceRegistryInterface $resolversRegistry) { } public function getSupportedMethods(ShippingSubjectInterface $subject): array { /** @var ShippingMethodsResolverInterface $resolver */ foreach ($this->resolversRegistry->all() as $resolver) { if ($resolver->supports($subject)) { return $resolver->getSupportedMethods($subject); } } return []; } public function supports(ShippingSubjectInterface $subject): bool { /** @var ShippingMethodsResolverInterface $resolver */ foreach ($this->resolversRegistry->all() as $resolver) { if ($resolver->supports($subject)) { return true; } } return false; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Shipping\Resolver; use Sylius\Component\Registry\PrioritizedServiceRegistryInterface; use Sylius\Component\Shipping\Model\ShippingSubjectInterface; final class CompositeMethodsResolver implements ShippingMethodsResolverInterface { public function __construct(private PrioritizedServiceRegistryInterface $resolversRegistry) { } public function getSupportedMethods(ShippingSubjectInterface $shippingSubject): array { /** @var ShippingMethodsResolverInterface $resolver */ foreach ($this->resolversRegistry->all() as $resolver) { if ($resolver->supports($shippingSubject)) { return $resolver->getSupportedMethods($shippingSubject); } } return []; } public function supports(ShippingSubjectInterface $subject): bool { /** @var ShippingMethodsResolverInterface $resolver */ foreach ($this->resolversRegistry->all() as $resolver) { if ($resolver->supports($subject)) { return true; } } return false; } }
Use resources for harvest reports
<?php namespace OGetIt\HarvestReport; use OGetIt\Common\OGetIt_Resources; class OGetIt_HarvestReport { /** * @var string */ private $_coordinates; /** * @var OGetIt_Resources */ private $_resources; /** * @param unknown $coordinates Format; 1:100:10 * @param integer $metal * @param integer $crystal */ public function __construct($coordinates, $metal, $crystal) { $this->_coordinates = $coordinates; $this->_resources = new OGetIt_Resources($metal, $crystal, 0); } /** * @return string */ public function getCoordinates() { return $this->_coordinates; } /** * @return integer */ public function getMetal() { return $this->_resources->getMetal(); } /** * @return integer */ public function getCrystal() { return $this->_resources->getCrystal(); } /** * @return OGetIt_Resources */ public function getResources() { return $this->_resources; } }
<?php namespace OGetIt\HarvestReport; class OGetIt_HarvestReport { /** * @var string */ private $_coordinates; /** * @var integer */ private $_metal; /** * @var integer */ private $_crystal; /** * @param unknown $coordinates Format; 1:100:10 * @param integer $metal * @param integer $crystal */ public function __construct($coordinates, $metal, $crystal) { $this->_coordinates = $coordinates; $this->_metal = $metal; $this->_crystal = $crystal; } /** * @return string */ public function getCoordinates() { return $this->_coordinates; } /** * @return integer */ public function getMetal() { return $this->_metal; } /** * @return integer */ public function getCrystal() { return $this->_crystal; } }
Change the appium package name.
from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, "README.rst")) as f: long_description = f.read() classifiers = ["License :: OSI Approved :: Apache Software License", "Topic :: Software Development :: Testing", "Operating System :: Microsoft :: Windows", "Operating System :: MacOS :: MacOS X"] + [ ("Programming Language :: Python :: %s" % x) for x in "2.7 3.4".split()] def main(): setup( name="easyium", description="easy use of selenium and appium", long_description=long_description, install_requires = ['selenium>=2.52.0', 'appium-python-client>=0.21'], version="1.1.5", keywords="selenium appium test testing framework automation", author="Karl Gong", author_email="karl.gong@outlook.com", url="https://github.com/KarlGong/easyium-python", license="Apache", classifiers=classifiers, packages=["easyium"], zip_safe=False, ) if __name__ == "__main__": main()
from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, "README.rst")) as f: long_description = f.read() classifiers = ["License :: OSI Approved :: Apache Software License", "Topic :: Software Development :: Testing", "Operating System :: Microsoft :: Windows", "Operating System :: MacOS :: MacOS X"] + [ ("Programming Language :: Python :: %s" % x) for x in "2.7 3.4".split()] def main(): setup( name="easyium", description="easy use of selenium and appium", long_description=long_description, install_requires = ['selenium>=2.52.0', 'appium>=0.21'], version="1.1.5", keywords="selenium appium test testing framework automation", author="Karl Gong", author_email="karl.gong@outlook.com", url="https://github.com/KarlGong/easyium-python", license="Apache", classifiers=classifiers, packages=["easyium"], zip_safe=False, ) if __name__ == "__main__": main()
Handle xpress deprecate warning regarding req.param()
var express = require('express') var router = express.Router() router.get('/', function (req, res, next) { console.log('Cookies: ', req.cookies) if (Object.keys(req.cookies).indexOf('username') !== -1) { return res.redirect('/studies') } else { res.render('index', { title: 'Choose a new username / Enter your username' }) } }) router.post('/login', function (req, res, next) { if (req.body.username.length) { res.cookie('username', req.body.username, { httpOnly: false, secure: false, maxAge: 432000000 }) res.redirect('/studies') } else { res.redirect('/') } }) router.get('/logout', function (req, res, next) { res.clearCookie('username') res.redirect('/') }) module.exports = router
var express = require('express') var router = express.Router() router.get('/', function (req, res, next) { console.log('Cookies: ', req.cookies) if (Object.keys(req.cookies).indexOf('username') !== -1) { return res.redirect('/studies') } else { res.render('index', { title: 'Choose a new username / Enter your username' }) } }) router.post('/login', function (req, res, next) { if (req.param('username').length) { res.cookie('username', req.param('username'), { httpOnly: false, secure: false, maxAge: 432000000 }) res.redirect('/studies') } else { res.redirect('/') } }) router.get('/logout', function (req, res, next) { res.clearCookie('username') res.redirect('/') }) module.exports = router
Fix current tab styling on workspace summary page
;(function($, ns) { ns.WorkspaceSummaryPage = chorus.pages.Base.extend({ crumbs : function() { return [ { label: t("breadcrumbs.home"), url: "#/" }, { label: this.model.get("name") } ] }, setup : function(workspaceId) { // chorus.router supplies arguments to setup this.model = new chorus.models.Workspace({id : workspaceId}); this.model.fetch(); this.breadcrumbs = new chorus.views.WorkspaceBreadcrumbsView({model: this.model}); this.subNav = new chorus.views.SubNav({workspace : this.model, tab: "summary"}) this.sidebar = new chorus.views.WorkspaceSummarySidebar({model: this.model}); this.mainContent = new chorus.views.MainContentView({ model: this.model, content : new chorus.views.WorkspaceDetail({model: this.model }), contentHeader : new chorus.views.StaticTemplate("plain_text", {text: "Summary"}), }); } }); })(jQuery, chorus.pages);
;(function($, ns) { ns.WorkspaceSummaryPage = chorus.pages.Base.extend({ crumbs : function() { return [ { label: t("breadcrumbs.home"), url: "#/" }, { label: this.model.get("name") } ] }, setup : function(workspaceId) { // chorus.router supplies arguments to setup this.model = new chorus.models.Workspace({id : workspaceId}); this.model.fetch(); this.breadcrumbs = new chorus.views.WorkspaceBreadcrumbsView({model: this.model}); this.subNav = new chorus.views.SubNav({workspace : this.model, tab: "Summary"}) this.sidebar = new chorus.views.WorkspaceSummarySidebar({model: this.model}); this.mainContent = new chorus.views.MainContentView({ model: this.model, content : new chorus.views.WorkspaceDetail({model: this.model }), contentHeader : new chorus.views.StaticTemplate("plain_text", {text: "Summary"}), }); } }); })(jQuery, chorus.pages);
Fix deprecated warning for ts-jest
var semver = require('semver'); function getSupportedTypescriptTarget() { var nodeVersion = process.versions.node; if (semver.gt(nodeVersion, '7.6.0')) { return 'es2017' } else if (semver.gt(nodeVersion, '7.0.0')) { return 'es2016'; } else if (semver.gt(nodeVersion, '6.0.0')) { return 'es2015'; } else if (semver.gt(nodeVersion, '4.0.0')) { return 'es5'; } else { return 'es3'; } } module.exports = { mapCoverage: true, testEnvironment: 'node', moduleFileExtensions: ['js', 'json', 'ts'], transform: { '.ts': '<rootDir>/node_modules/ts-jest/preprocessor.js' }, testMatch: [ '**/__tests__/**/*.ts' ], testPathIgnorePatterns: [ '<rootDir>/(node_modules|dist)', '_\\w*.\\w+$' ], collectCoverageFrom: [ 'src/**/*.ts', '!src/**/*.d.ts' ], globals: { 'ts-jest': { tsConfigFile: { target: getSupportedTypescriptTarget(), module: 'commonjs' } } } };
var semver = require('semver'); function getSupportedTypescriptTarget() { var nodeVersion = process.versions.node; if (semver.gt(nodeVersion, '7.6.0')) { return 'es2017' } else if (semver.gt(nodeVersion, '7.0.0')) { return 'es2016'; } else if (semver.gt(nodeVersion, '6.0.0')) { return 'es2015'; } else if (semver.gt(nodeVersion, '4.0.0')) { return 'es5'; } else { return 'es3'; } } module.exports = { mapCoverage: true, testEnvironment: 'node', moduleFileExtensions: ['js', 'json', 'ts'], transform: { '.ts': '<rootDir>/node_modules/ts-jest/preprocessor.js' }, testMatch: [ '**/__tests__/**/*.ts' ], testPathIgnorePatterns: [ '<rootDir>/(node_modules|dist)', '_\\w*.\\w+$' ], collectCoverageFrom: [ 'src/**/*.ts', '!src/**/*.d.ts' ], globals: { __TS_CONFIG__: { target: getSupportedTypescriptTarget(), module: 'commonjs' } } };
Fix infinite loop at root dir if nothing is found
package main import ( "fmt" "os" "os/exec" "path/filepath" ) const FILE string = "Makefile" const PROG string = "make" /* TODO: add stopping at homedir configurable filename for aliases? */ func main() { checkDir, err := os.Getwd() if err != nil { fmt.Println("Error getting working directory:", err) os.Exit(1) } for { if existsAtPath(checkDir) { os.Exit(runAt(checkDir)) } else if checkDir == "/" { fmt.Println("Unable to find", FILE) os.Exit(1) } else { newdir := filepath.Dir(checkDir) checkDir = newdir } } } func runAt(dir string) int { cmd := exec.Command(PROG, os.Args[1:]...) cmd.Dir = dir cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { fmt.Println(PROG, "exited with error", err) return 1 } else { return 0 } } func existsAtPath(dir string) bool { path := filepath.Join(dir, FILE) if _, err := os.Stat(path); os.IsNotExist(err) { return false } return true }
package main import ( "fmt" "log" "os" "os/exec" "path/filepath" ) const FILE string = "Makefile" const PROG string = "make" /* TODO: add stopping at homedir configurable filename for aliases? */ func main() { checkDir, err := os.Getwd() if err != nil { log.Fatal(err) } for { //fmt.Println("Checking:", checkDir) if existsAtPath(checkDir) { //fmt.Println("FOUND IT in", checkDir) os.Exit(runAt(checkDir)) } else { newdir := filepath.Dir(checkDir) //fmt.Println("Moving to:", newdir) checkDir = newdir } } } func runAt(dir string) int { cmd := exec.Command(PROG, os.Args[1:]...) cmd.Dir = dir cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { fmt.Printf("exit with errr %v\n", err) return 1 } else { return 0 } } func existsAtPath(dir string) bool { path := filepath.Join(dir, FILE) if _, err := os.Stat(path); os.IsNotExist(err) { return false } //fmt.Println("found:", path) return true }
Fix babel-runtime/regenerator import in tools runtime setup. Fixes #7181.
// Install ES2015-complaint polyfills for Object, Array, String, Function, // Symbol, Map, and Set, patching the native implementations if available. require("meteor-ecmascript-runtime"); // Install a global ES2015-compliant Promise constructor that knows how to // run all its callbacks in Fibers. var Promise = global.Promise = global.Promise || require("promise/lib/es6-extensions"); require("meteor-promise").makeCompatible(Promise, require("fibers")); // Verify that the babel-runtime package is available to be required. // The .join("/") prevents babel-plugin-transform-runtime from // "intelligently" converting this to an import statement. var regenerator = require([ "babel-runtime", "regenerator" ].join("/")); // Use Promise.asyncApply to wrap calls to runtime.async so that the // entire async function will run in its own Fiber, not just the code that // comes after the first await. var realAsync = regenerator.async; regenerator.async = function () { return Promise.asyncApply(realAsync, regenerator, arguments); }; // Install global.meteorBabelHelpers so that the compiler doesn't need to // add boilerplate at the top of every file. require("meteor-babel").defineHelpers(); // Installs source map support with a hook to add functions to look for // source maps in custom places. require('./source-map-retriever-stack.js');
// Install ES2015-complaint polyfills for Object, Array, String, Function, // Symbol, Map, and Set, patching the native implementations if available. require("meteor-ecmascript-runtime"); // Install a global ES2015-compliant Promise constructor that knows how to // run all its callbacks in Fibers. var Promise = global.Promise = global.Promise || require("promise/lib/es6-extensions"); require("meteor-promise").makeCompatible(Promise, require("fibers")); // Verify that the babel-runtime package is available to be required. // The .join("/") prevents babel-plugin-transform-runtime from // "intelligently" converting this to an import statement. var regenerator = require([ "babel-runtime", "regenerator" ].join("/")).default; // Use Promise.asyncApply to wrap calls to runtime.async so that the // entire async function will run in its own Fiber, not just the code that // comes after the first await. var realAsync = regenerator.async; regenerator.async = function () { return Promise.asyncApply(realAsync, regenerator, arguments); }; // Install global.meteorBabelHelpers so that the compiler doesn't need to // add boilerplate at the top of every file. require("meteor-babel").defineHelpers(); // Installs source map support with a hook to add functions to look for // source maps in custom places. require('./source-map-retriever-stack.js');