text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
fix: Exclude current record while validating duplicate employee
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.model.naming import set_name_by_naming_series class Instructor(Document): def autoname(self): naming_method = frappe.db.get_value("Education Settings", None, "instructor_created_by") if not naming_method: frappe.throw(_("Please setup Instructor Naming System in Education > Education Settings")) else: if naming_method == 'Naming Series': set_name_by_naming_series(self) elif naming_method == 'Employee Number': if not self.employee: frappe.throw(_("Please select Employee")) self.name = self.employee elif naming_method == 'Full Name': self.name = self.instructor_name def validate(self): self.validate_duplicate_employee() def validate_duplicate_employee(self): if self.employee and frappe.db.get_value("Instructor", {'employee': self.employee, 'name': ['!=', self.name]}, 'name'): frappe.throw(_("Employee ID is linked with another instructor"))
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.model.naming import set_name_by_naming_series class Instructor(Document): def autoname(self): naming_method = frappe.db.get_value("Education Settings", None, "instructor_created_by") if not naming_method: frappe.throw(_("Please setup Instructor Naming System in Education > Education Settings")) else: if naming_method == 'Naming Series': set_name_by_naming_series(self) elif naming_method == 'Employee Number': if not self.employee: frappe.throw(_("Please select Employee")) self.name = self.employee elif naming_method == 'Full Name': self.name = self.instructor_name def validate(self): self.validate_duplicate_employee() def validate_duplicate_employee(self): if self.employee and frappe.db.get_value("Instructor", {'employee': self.employee}, 'name'): frappe.throw(_("Employee ID is linked with another instructor"))
Consolidate the two pieces of state into a single atom This helps readability of the code by knowing there is only one variable that contains the state and only one variable that can be mutated. This means if you refactor the code into multiple files you only have to pass this one variable into the functions from the other file.
var mercury = require("mercury") var frameList = require("./views/frame-list") var frameEditor = require("./views/frame-editor") var frameData = require("./data/frames") // Load the data var initialFrameData = frameData.load() // Create the default view using the frame set var frameListEditor = frameList(frames) var state = mercury.hash({ frames: mercury.hash(initialFrameData), editor: frameList }) // When the data changes, save it state.frames(frameData.save) // Show the frame editor frameListEditor.onSelectFrame(function (frameId) { var editor = frameEditor(state.frames[frameId]) editor.onExit(function () { // Restore the frame list state.editor.set(frameList) }) }) function render(state) { // This is a mercury partial rendered with editor.state instead // of globalSoup.state // The immutable internal event list is also passed in // Event listeners are obviously not serializable, but // they can expose their state (listener set) return h(state.editor.partial()) } // setup the loop and go. mercury.app(document.body, render, state)
var mercury = require("mercury") var frameList = require("./views/frame-list") var frameEditor = require("./views/frame-editor") var frameData = require("./data/frames") // Load the data var initialFrameData = frameData.load() var frames = mercury.hash(initialFrameData) // When the data changes, save it frames(frameData.save) // Create the default view using the frame set var frameListEditor = frameList(frames) var state = mercury.hash({ frames: frames, editor: frameList }) // Show the frame editor frameListEditor.onSelectFrame(function (frameId) { var editor = frameEditor(frames[frameId]) editor.onExit(function () { // Restore the frame list state.editor.set(frameList) }) }) function render(state) { // This is a mercury partial rendered with editor.state instead // of globalSoup.state // The immutable internal event list is also passed in // Event listeners are obviously not serializable, but // they can expose their state (listener set) return h(state.editor.partial()) } // setup the loop and go. mercury.app(document.body, render, state)
Include filters to package data
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-salmonella", version='0.6.1', author='Lincoln Loop: Seth Buntin, Yann Malet', author_email='info@lincolnloop.com', description=("raw_id_fields widget replacement that handles display of an object's " "string value on change and can be overridden via a template."), packages=find_packages(), package_data={'salmonella': [ 'static/salmonella/js/*.js', 'static/salmonella/img/*.gif', 'templates/salmonella/*.html', 'templates/salmonella/admin/*.html', 'templates/salmonella/admin/widgets/*.html', 'templates/salmonella/admin/filters/*.html' ]}, include_package_data=True, url="http://github.com/lincolnloop/django-salmonella/", zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-salmonella", version='0.6.1', author='Lincoln Loop: Seth Buntin, Yann Malet', author_email='info@lincolnloop.com', description=("raw_id_fields widget replacement that handles display of an object's " "string value on change and can be overridden via a template."), packages=find_packages(), package_data={'salmonella': [ 'static/salmonella/js/*.js', 'static/salmonella/img/*.gif', 'templates/salmonella/*.html', 'templates/salmonella/admin/*.html', 'templates/salmonella/admin/widgets/*.html' ]}, include_package_data=True, url="http://github.com/lincolnloop/django-salmonella/", zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Fix bug where cancel messages weren't received.
/* eslint-env worker */ /* eslint-disable camelcase */ 'use strict'; var build = require('../build'); var UglifyJS = require('uglify-js'); var zlib = require('zlib'); var running = false; var canceled = false; var startBuild = function (options) { running = true; var stats = {}; var buildOutput = build(options); stats.uncompressed = buildOutput.length; var uglifyOutput = UglifyJS.minify(buildOutput, { fromString: true, mangle: { screw_ie8: !options.ie }, output: { screw_ie8: !options.ie }, compress: { screw_ie8: !options.ie } }).code; stats.uglified = uglifyOutput.length; var gzipOutput = zlib.gzipSync(uglifyOutput); // eslint-disable-line no-sync stats.uglifiedGzipped = gzipOutput.length; // Allow a cancelation event to fire. setTimeout(function () { if (canceled) { canceled = false; } else { postMessage({ name: 'complete', output: buildOutput, stats: stats }); } running = false; }); }; onmessage = function (event) { if (event.data.name === 'build') { startBuild(event.data.options); } else if (event.data.name === 'cancel') { if (running) { canceled = true; } } };
/* eslint-env worker */ /* eslint-disable camelcase */ 'use strict'; var build = require('../build'); var UglifyJS = require('uglify-js'); var zlib = require('zlib'); var running = false; var canceled = false; var startBuild = function (options) { running = true; var stats = {}; var buildOutput = build(options); stats.uncompressed = buildOutput.length; var uglifyOutput = UglifyJS.minify(buildOutput, { fromString: true, mangle: { screw_ie8: !options.ie }, output: { screw_ie8: !options.ie }, compress: { screw_ie8: !options.ie } }).code; stats.uglified = uglifyOutput.length; var gzipOutput = zlib.gzipSync(uglifyOutput); // eslint-disable-line no-sync stats.uglifiedGzipped = gzipOutput.length; // Allow a cancelation event to fire. setTimeout(function () { if (canceled) { canceled = false; } else { postMessage({ name: 'complete', output: buildOutput, stats: stats }); } running = false; }); }; onmessage = function (event) { if (event.data.name === 'build') { startBuild(event.data.options); } else if (event.data.name === 'canceled') { if (running) { canceled = true; } } };
Check error with instance of Closes #22 Signed-off-by: Dominic Bartl <a9662aa7a7b7ac6326ee7732d0f7f2070642dd85@gmail.com>
/** * Download tool for Unicode CLDR JSON data * * Copyright 2013 Rafael Xavier de Souza * Released under the MIT license * https://github.com/rxaviers/cldr-data-downloader/blob/master/LICENSE-MIT */ "use strict"; var assert = require("assert"); var fs = require("fs"); var url = require("url"); module.exports = { deepEqual: function(a, b) { try { assert.deepEqual(a, b); } catch (error) { if (error instanceof assert.AssertionError) { return false; } throw error; } return true; }, isUrl: function(urlOrPath) { urlOrPath = url.parse(urlOrPath); return urlOrPath.hostname ? true : false; }, readJSON: function(filepath) { return JSON.parse(fs.readFileSync(filepath)); } };
/** * Download tool for Unicode CLDR JSON data * * Copyright 2013 Rafael Xavier de Souza * Released under the MIT license * https://github.com/rxaviers/cldr-data-downloader/blob/master/LICENSE-MIT */ "use strict"; var assert = require("assert"); var fs = require("fs"); var url = require("url"); module.exports = { deepEqual: function(a, b) { try { assert.deepEqual(a, b); } catch (error) { if (error.name === "AssertionError") { return false; } throw error; } return true; }, isUrl: function(urlOrPath) { urlOrPath = url.parse(urlOrPath); return urlOrPath.hostname ? true : false; }, readJSON: function(filepath) { return JSON.parse(fs.readFileSync(filepath)); } };
Fix Bird Feeder Reader URL.
import urllib from base.constants import CONSTANTS import session class IndexHandler(session.SessionApiHandler): def _get_signed_in(self): twitter_user = self._api.GetUser(self._session.twitter_id) timeline_feed_url = self._get_path( 'feed/timeline/%s' % self._session.feed_id) timeline_reader_url = \ 'http://www.google.com/reader/view/feed/%s' % urllib.quote( CONSTANTS.APP_URL + timeline_feed_url) self._write_template('birdfeeder/index-signed-in.html', { 'twitter_user': twitter_user, 'sign_out_path': self._get_path('sign-out'), 'timeline_feed_url': timeline_feed_url, 'timeline_reader_url': timeline_reader_url, }) def _get_signed_out(self): self._write_template('birdfeeder/index-signed-out.html', { 'sign_in_path': self._get_path('sign-in'), })
import urllib from base.constants import CONSTANTS import session class IndexHandler(session.SessionApiHandler): def _get_signed_in(self): twitter_user = self._api.GetUser(self._session.twitter_id) timeline_feed_url = self._get_path( 'feed/timeline/%s' % self._session.feed_id) timeline_reader_url = \ 'http://www.google.com/reader/view/%s' % urllib.quote( CONSTANTS.APP_URL + timeline_feed_url) self._write_template('birdfeeder/index-signed-in.html', { 'twitter_user': twitter_user, 'sign_out_path': self._get_path('sign-out'), 'timeline_feed_url': timeline_feed_url, 'timeline_reader_url': timeline_reader_url, }) def _get_signed_out(self): self._write_template('birdfeeder/index-signed-out.html', { 'sign_in_path': self._get_path('sign-in'), })
Clean up test code a little more
/* Configure nock interceptor for backend service */ import features from '../fixtures/features.js'; import client from '../fixtures/client.js'; import productArea from '../fixtures/productarea.js'; /* Returns a regex that will match /api/endpoint with optional trailing slash or query parameters */ function collection(endpoint, base='') { return RegExp(base + `/api/${endpoint}/?(\\?([^0-9].*))*$`); } /* Return path part of url */ function strip(url) { return url.replace(/^http:\/\/localhost:8000/, ''); } /* Mock api using fetch-mock */ export default function (fetchMock) { // Intercept all calls to fetch fetchMock.greed = 'bad'; fetchMock.mock(collection('features'), features); fetchMock.mock(collection('client'), client); fetchMock.mock(collection('productarea'), productArea); const setup = (el) => fetchMock.mock(strip(el.url), el); features.results.forEach(setup); client.results.forEach(setup); productArea.results.forEach(setup); }
/* Configure nock interceptor for backend service */ import features from '../fixtures/features.js'; import client from '../fixtures/client.js'; import productArea from '../fixtures/productarea.js'; /* Returns a regex that will match /api/endpoint with optional trailing slash or query parameters */ function collection(endpoint, base='') { return RegExp(base + `/api/${endpoint}/?(\\?([^0-9].*))*$`); } /* Return path part of url */ function strip(url) { return url.replace(/^http:\/\/localhost:8000/, ''); } /* Mock api using fetch-mock */ export default function (fetchMock) { // Intercept all calls to fetch fetchMock.greed = 'bad'; fetchMock.mock(collection('features'), features); fetchMock.mock(collection('client'), client); fetchMock.mock(collection('productarea'), productArea); features.results.forEach((feature) => { const url = strip(feature.url); fetchMock.mock(url, feature); }); client.results.forEach((client) => { const url = strip(client.url); fetchMock.mock(url, client); }); productArea.results.forEach((area) => { const url = strip(area.url); fetchMock.mock(url, area); }); }
Return http status code 400 (Bad Request) unless flask gives an error code
"""blueprint.py""" import flask from werkzeug.exceptions import HTTPException from werkzeug.exceptions import default_exceptions from jsonrpcserver import exceptions from jsonrpcserver import logger from jsonrpcserver import bp def error(e, response_str): """Ensure we always respond with jsonrpc, such as on 400 or other bad request""" response = flask.Response(response_str, mimetype='application/json') response.status_code = (e.code if isinstance(e, HTTPException) else 400) logger.info('<-- {} {}'.format(response.status_code, response_str)) return response def invalid_request(e): """Status codes 400-499""" return error(e, str(exceptions.InvalidRequest())) def internal_error(e): """Any error other than status codes 400-499""" return error(e, str(exceptions.InternalError())) # Override flask internal error handlers, to return as jsonrpc for code in default_exceptions.keys(): if 400 <= code <= 499: bp.app_errorhandler(code)(invalid_request) else: bp.app_errorhandler(code)(internal_error) # Catch RPCHandler exceptions and return jsonrpc @bp.app_errorhandler(exceptions.RPCHandlerException) def handler_error(e): """RPCHandlerExceptions: responds with json""" return error(e, str(e))
"""blueprint.py""" import flask from werkzeug.exceptions import HTTPException from werkzeug.exceptions import default_exceptions from jsonrpcserver import exceptions from jsonrpcserver import logger from jsonrpcserver import bp def error(e, response_str): """Ensure we always respond with jsonrpc, such as on 400 or other bad request""" response = flask.Response(response_str, mimetype='application/json') response.status_code = (e.code if isinstance(e, HTTPException) else 500) logger.info('<-- {} {}'.format(response.status_code, response_str)) return response def invalid_request(e): """Status codes 400-499""" return error(e, str(exceptions.InvalidRequest())) def internal_error(e): """Any error other than status codes 400-499""" return error(e, str(exceptions.InternalError())) # Override flask internal error handlers, to return as jsonrpc for code in default_exceptions.keys(): if 400 <= code <= 499: bp.app_errorhandler(code)(invalid_request) else: bp.app_errorhandler(code)(internal_error) # Catch RPCHandler exceptions and return jsonrpc @bp.app_errorhandler(exceptions.RPCHandlerException) def handler_error(e): """RPCHandlerExceptions: responds with json""" return error(e, str(e))
Fix quoteWidth bug; minor cleanup
$(function () { // vars for carousel var $textCarousel = $('#testimonial-list'); var textCount = $textCarousel.children().length; var quoteWidth = $('.carousel-wrap li').first().width(); console.log(quoteWidth); var wrapWidth = (textCount * quoteWidth) + quoteWidth; console.log(wrapWidth); $textCarousel.css('width', wrapWidth); var animationTime = 750; // milliseconds for clients carousel var fadeTime = 500; // prev & next btns for testimonials $('#prv-testimonial').on('click', function(){ var $last = $('#testimonial-list li:last'); $last.remove().css({ 'margin-left': '-1106px' }); $('#testimonial-list li:first').before($last); $last.fadeOut(fadeTime, function(){ //$last.animate({ 'margin-left': '0px' }, animationTime, 'swing', function(){ // $last.css('opacity', '1'); //}); }); }); $('#nxt-testimonial').on('click', function(){ var $first = $('#testimonial-list li:first'); $first.animate({ 'margin-left': '-1106px' }, animationTime, function() { $first.remove().css({ 'margin-left': '0px' }); $('#testimonial-list li:last').after($first); }); }); });
$(function(){ // vars for testimonials carousel var $txtcarousel = $('#testimonial-list'); var txtcount = $txtcarousel.children().length; var quoteWidth = $('.carousel-wrap li').get(0).css("width"); var wrapwidth = (txtcount * quoteWidth) + quoteWidth; // 700px width for each testimonial item $txtcarousel.css('width',wrapwidth); var animtime = 750; // milliseconds for clients carousel var fadetime = 500; // prev & next btns for testimonials $('#prv-testimonial').on('click', function(){ var $last = $('#testimonial-list li:last'); $last.remove().css({ 'margin-left': '-1106px' }); $('#testimonial-list li:first').before($last); $last.fadeOut(fadetime, function(){ //$last.animate({ 'margin-left': '0px' }, animtime, 'swing', function(){ // $last.css('opacity', '1'); //}); }); }); $('#nxt-testimonial').on('click', function(){ var $first = $('#testimonial-list li:first'); $first.animate({ 'margin-left': '-1106px' }, animtime, function() { $first.remove().css({ 'margin-left': '0px' }); $('#testimonial-list li:last').after($first); }); }); });
Add missing $q service to User
var angularMeteorUser = angular.module('angular-meteor.user', ['angular-meteor.utils']); angularMeteorUser.run(['$rootScope', '$meteorUtils', '$q', function($rootScope, $meteorUtils, $q){ var currentUserDefer; $meteorUtils.autorun($rootScope, function(){ if (Meteor.user) { $rootScope.currentUser = Meteor.user(); $rootScope.loggingIn = Meteor.loggingIn(); } // if there is no currentUserDefer (on first autorun) // or it is already resolved, but the Meteor.user() is changing if (!currentUserDefer || Meteor.loggingIn() ) { currentUserDefer = $q.defer(); $rootScope.currentUserPromise = currentUserDefer.promise; } if ( !Meteor.loggingIn() ) { currentUserDefer.resolve( Meteor.user() ); } }); }]);
var angularMeteorUser = angular.module('angular-meteor.user', ['angular-meteor.utils']); angularMeteorUser.run(['$rootScope', '$meteorUtils', function($rootScope, $meteorUtils){ var currentUserDefer; $meteorUtils.autorun($rootScope, function(){ if (Meteor.user) { $rootScope.currentUser = Meteor.user(); $rootScope.loggingIn = Meteor.loggingIn(); } // if there is no currentUserDefer (on first autorun) // or it is already resolved, but the Meteor.user() is changing if (!currentUserDefer || Meteor.loggingIn() ) { currentUserDefer = $q.defer(); $rootScope.currentUserPromise = currentUserDefer.promise; } if ( !Meteor.loggingIn() ) { currentUserDefer.resolve( Meteor.user() ); } }); }]);
PLAT-10694: Add linux batch for doc conversion
<?php /** * @package plugins.document * @subpackage lib */ class KOperationEnginePdfCreatorLinux extends KOperationEnginePdfCreator { // List of supported file types protected $SUPPORTED_FILE_TYPES = array( 'Microsoft Word', 'Microsoft PowerPoint', 'Microsoft Excel', 'OpenDocument Text', 'PDF document', 'Rich Text Format data', ); protected function getCmdLine() { if(isset($this->configFilePath)) { $xml = file_get_contents($this->configFilePath); $xml = str_replace( array(KDLCmdlinePlaceholders::OutDir,KDLCmdlinePlaceholders::OutFileName), array($this->outDir,$this->outFilePath), $xml); file_put_contents($this->configFilePath, $xml); } $outDir = dirname($this->outFilePath); $command = "HOME=/tmp && lowriter --headless --convert-to pdf $this->inFilePath --outdir $outDir"; return "$command >> \"{$this->logFilePath}\" 2>&1"; } protected function getKillPopupsPath() { return NULL; } }
<?php /** * @package plugins.document * @subpackage lib */ class KOperationEnginePdfCreatorLinux extends KOperationEnginePdfCreator { // List of supported file types protected $SUPPORTED_FILE_TYPES = array( 'Microsoft Word', 'Microsoft PowerPoint', 'Microsoft Excel', 'OpenDocument Text', 'PDF document', 'Rich Text Format data', ); protected function getCmdLine() { if(isset($this->configFilePath)) { $xml = file_get_contents($this->configFilePath); $xml = str_replace( array(KDLCmdlinePlaceholders::OutDir,KDLCmdlinePlaceholders::OutFileName), array($this->outDir,$this->outFilePath), $xml); file_put_contents($this->configFilePath, $xml); } $outDir = dirname($this->outFilePath); $command = "HOME=/tmp && lowriter --headless --convert-to pdf $this->inFilePath --outdir $outDir"; return "$command >> \"{$this->logFilePath}\" 2>&1"; } protected function getKillPopupsPath() { return NULL; } }
Use of product.template instead of product.product in bundle line
# -*- encoding: utf-8 -*- from openerp import fields, models, _ import openerp.addons.decimal_precision as dp class product_bundle(models.Model): _name = 'product.bundle' _description = 'Product bundle' name = fields.Char(_('Name'), help=_('Product bundle name'), required=True) bundle_line_ids = fields.Many2many( 'product.bundle.line', 'product_bundle_product_bundle_line', 'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines')) class product_bundle_line(models.Model): _name = 'product.bundle.line' _description = 'Product bundle line' product_id = fields.Many2one( 'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True) quantity = fields.Float( string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'), required=True, default=1) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- encoding: utf-8 -*- from openerp import fields, models, _ import openerp.addons.decimal_precision as dp class product_bundle(models.Model): _name = 'product.bundle' _description = 'Product bundle' name = fields.Char(_('Name'), help=_('Product bundle name'), required=True) bundle_line_ids = fields.Many2many( 'product.bundle.line', 'product_bundle_product_bundle_line', 'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines')) class product_bundle_line(models.Model): _name = 'product.bundle.line' _description = 'Product bundle line' product_id = fields.Many2one('product.template', string=_('Product'), required=True) quantity = fields.Float( string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'), required=True, default=1) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Replace all extra characters with commas in queries; improves matching
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import re import traceback from bottle import route, run, get, request, response, abort from db import search, info @route('/v1/pois.json') def pois_v1(): global _db filter = request.query.get('filter', None) if filter is None: abort(501, "Unfiltered searches not allowed.") filter = re.sub('[\W_]+', ',', filter) result = search(database=_db, verbose=False, query=filter) response.content_type = 'application/json' return json.dumps(result, ensure_ascii=False) if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option("--host", dest="host", help="bind to HOST", metavar="HOST", default="localhost") parser.add_option("--port", dest="port", help="bind to PORT", metavar="PORT", type="int", default=8022) parser.add_option("-d", "--database", dest="db", help="use database FILE", metavar="FILE", default="paikkis.db") opts, args = parser.parse_args() _db = opts.db run(host=opts.host, port=opts.port)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import traceback from bottle import route, run, get, request, response, abort from db import search, info @route('/v1/pois.json') def pois_v1(): global _db filter = request.query.get('filter', None) if filter is None: abort(501, "Unfiltered searches not allowed.") result = search(database=_db, verbose=False, query=filter) response.content_type = 'application/json' return json.dumps(result, ensure_ascii=False) if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option("--host", dest="host", help="bind to HOST", metavar="HOST", default="localhost") parser.add_option("--port", dest="port", help="bind to PORT", metavar="PORT", type="int", default=8022) parser.add_option("-d", "--database", dest="db", help="use database FILE", metavar="FILE", default="paikkis.db") opts, args = parser.parse_args() _db = opts.db run(host=opts.host, port=opts.port)
Use the redistribution of (now discontinued) mimic as gmcquillan-mimic.
import multiprocessing from setuptools import setup, find_packages requirements = [] with open('requirements.txt', 'r') as in_: requirements = in_.readlines() setup( name='myfitnesspal', version='1.2.2', url='http://github.com/coddingtonbear/python-myfitnesspal/', description='Access health and fitness data stored in Myfitnesspal', author='Adam Coddington', author_email='me@adamcoddington.net', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], packages=find_packages(), install_requires=requirements, test_suite='nose.collector', tests_require=[ 'gmcquillan-mimic', 'nose', ] )
import multiprocessing from setuptools import setup, find_packages requirements = [] with open('requirements.txt', 'r') as in_: requirements = in_.readlines() setup( name='myfitnesspal', version='1.2.2', url='http://github.com/coddingtonbear/python-myfitnesspal/', description='Access health and fitness data stored in Myfitnesspal', author='Adam Coddington', author_email='me@adamcoddington.net', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], packages=find_packages(), install_requires=requirements, test_suite='nose.collector', tests_require=[ 'mimic', 'nose', ] )
Make the regex work on Python2.x
import sublime import sublime_plugin import re class CopyFromFindInFilesCommand(sublime_plugin.TextCommand): def run(self, edit, force=False): self.view.run_command('copy') if not self.in_find_results_view() and not force: return clipboard_contents = sublime.get_clipboard() if clipboard_contents: settings = sublime.load_settings('CopyFromFindInFiles.sublime-settings') keep_intermediate_dots = settings.get('keep_intermediate_dots', False) new_clipboard = RegexStruct(keep_intermediate_dots).sub(clipboard_contents) sublime.set_clipboard(new_clipboard) def in_find_results_view(self): return self.view.settings().get('syntax') == 'Packages/Default/Find Results.hidden-tmLanguage' class RegexStruct(): default = re.compile('^\s*\d+(\:\s|\s{2})', re.MULTILINE) without_dots = re.compile('^\s*(\d+(\:\s|\s{2})|.+\n)', re.MULTILINE) def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return self.construct().sub('', text) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots
import sublime import sublime_plugin import re class CopyFromFindInFilesCommand(sublime_plugin.TextCommand): def run(self, edit, force=False): self.view.run_command('copy') if not self.in_find_results_view() and not force: return clipboard_contents = sublime.get_clipboard() if clipboard_contents: settings = sublime.load_settings('CopyFromFindInFiles.sublime-settings') keep_intermediate_dots = settings.get('keep_intermediate_dots', False) new_clipboard = RegexStruct(keep_intermediate_dots).sub(clipboard_contents) sublime.set_clipboard(new_clipboard) def in_find_results_view(self): return self.view.settings().get('syntax') == 'Packages/Default/Find Results.hidden-tmLanguage' class RegexStruct(): default = r'^\s*\d+(\:\s|\s{2})' without_dots = r'^\s*(\d+(\:\s|\s{2})|.+\n)' def __init__(self, keep_dots=True): self.keep_dots = keep_dots def sub(self, text): return re.sub(self.construct(), '', text, flags=re.MULTILINE) def construct(self): return RegexStruct.default if self.keep_dots else RegexStruct.without_dots
Update shebang to request python 3
#!/usr/bin/python3 import argparse import dice def main(): roller = dice.Roller(args) for repeat in range(args.repeats): roller.do_roll() for result in roller: if isinstance(result, list): print(' '.join(map(str, result))) else: print(result) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Roll some dice.") parser.add_argument("-r, --repeat", dest="repeats", type=int, metavar="N", default=1, help="Repeat these rolls N times.") parser.add_argument("-e, --explode", dest="explode", metavar="E", type=int, default=None, help="Any die whose roll matches or exceeds E is counted and rolled again. Set to 1 or lower to disable this behavior on special dice.") parser.add_argument("dice", nargs='*', help="Dice to roll, given in pairs of the number of dice to roll, and the sides those dice have.") args = parser.parse_args() # some basic error checking if len(args.dice)%2 != 0: parser.error("Incorrect number of arguments: Rolls and faces must be paired") main()
#!/usr/bin/python import argparse import dice def main(): roller = dice.Roller(args) for repeat in range(args.repeats): roller.do_roll() for result in roller: if isinstance(result, list): print(' '.join(map(str, result))) else: print(result) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Roll some dice.") parser.add_argument("-r, --repeat", dest="repeats", type=int, metavar="N", default=1, help="Repeat these rolls N times.") parser.add_argument("-e, --explode", dest="explode", metavar="E", type=int, default=None, help="Any die whose roll matches or exceeds E is counted and rolled again. Set to 1 or lower to disable this behavior on special dice.") parser.add_argument("dice", nargs='*', help="Dice to roll, given in pairs of the number of dice to roll, and the sides those dice have.") args = parser.parse_args() # some basic error checking if len(args.dice)%2 != 0: parser.error("Incorrect number of arguments: Rolls and faces must be paired") main()
Fix a violation of Helper class
/* * Copyright (C) 2012 VSPLF Software Foundation (VSF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vsplf.i18n; /** * The application entry point. * * @author <a href="http://hoatle.net">hoatle (hoatlevan at gmail dot com)</a> * @since Feb 23, 2012 */ public final class DynamicI18N { private DynamicI18N() { } public static TranslatorFactory buildDefaultTranslatorFactory() { return null; } }
/* * Copyright (C) 2012 VSPLF Software Foundation (VSF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vsplf.i18n; /** * The application entry point for bootstrap. * * @author <a href="http://hoatle.net">hoatle (hoatlevan at gmail dot com)</a> * @since 2/23/12 */ public class DynamicI18N { public static TranslatorFactory buildDefaultTranslatorFactory() { return null; } }
Add super hero search data. Format the search output.
console.log("================================="); console.log("Creating search index..."); console.log("================================="); // Scan through all content/ directories // For each markdown file // CreateIndex(title,content,path) var lunr = require('lunr'); var idx = lunr(function () { this.field('title') this.field('body') this.field('author') this.ref('id') this.add({ "title": "Wolverine", "body": "A animal-human hybrid with a indestructible metal skeleton", "author": "Marvel Comics", "id": "/xmen/wolverine/" }) this.add({ "title": "Batman", "body": "A cloaked hero with ninja like skills and dark personality", "author": "DC Comics", "id": "/justiceleague/batman/" }) this.add({ "title": "Superman", "body": "A humanoid alien that grew up on earth with super-human powers", "author": "DC Comics", "id": "/justiceleague/superman/" }) }) const searchTerm = "metal"; console.log(JSON.stringify(idx.search(searchTerm),null,2)); console.log("================================="); // Build the search index //console.log(JSON.stringify(idx));
console.log("================================="); console.log("Creating search index..."); console.log("================================="); // Scan through all content/ directories // For each markdown file // CreateIndex(title,content,path) var lunr = require('lunr'); var idx = lunr(function () { this.field('title') this.field('body') this.add({ "title": "Twelfth-Night", "body": "If music be the food of love, play on: Give me excess of it…", "author": "William Shakespeare", "id": "/william/shakespeare/" }) this.add({ "title": "Batman", "body": "Batman loves throwing batarangs.", "author": "DC Comics", "id": "/dc/batman/" }) }) console.log(idx.search("love")); console.log("================================="); console.log(JSON.stringify(idx));
Define which examples to use in OpenAPI
# -*- coding: utf-8 -*- import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from openfisca_country_template import entities from openfisca_country_template.situation_examples import couple COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) # Our country tax and benefit class inherits from the general TaxBenefitSystem class. # The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package. class CountryTaxBenefitSystem(TaxBenefitSystem): def __init__(self): # We initialize our tax and benefit system with the general constructor super(CountryTaxBenefitSystem, self).__init__(entities.entities) # We add to our tax and benefit system all the variables self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables')) # We add to our tax and benefit system all the legislation parameters defined in the parameters files param_path = os.path.join(COUNTRY_DIR, 'parameters') self.load_parameters(param_path) # We define which variable, parameter and simulation example will be used in the OpenAPI specification self.open_api_config = { "variable_example": "disposable_income", "parameter_example": "taxes.income_tax_rate", "simulation_example": couple, }
# -*- coding: utf-8 -*- import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) # Our country tax and benefit class inherits from the general TaxBenefitSystem class. # The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package. class CountryTaxBenefitSystem(TaxBenefitSystem): def __init__(self): # We initialize our tax and benefit system with the general constructor super(CountryTaxBenefitSystem, self).__init__(entities.entities) # We add to our tax and benefit system all the variables self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables')) # We add to our tax and benefit system all the legislation parameters defined in the parameters files param_path = os.path.join(COUNTRY_DIR, 'parameters') self.load_parameters(param_path)
Fix indentation (remove blank line + add blank line after namespace declaration
<?php /** * @title Import Class * @desc Generic Importer Class for the pH7CMS. * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Install / Class * @version 0.1 */ namespace PH7; defined('PH7') or exit('Restricted access'); abstract class Import { protected $db; public function __construct() { $this->db = Db::getInstance(); } }
<?php /** * @title Import Class * @desc Generic Importer Class for the pH7CMS. * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Install / Class * @version 0.1 */ namespace PH7; defined('PH7') or exit('Restricted access'); abstract class Import { protected $db; public function __construct() { $this->db = Db::getInstance(); } }
Test runner: fix line endings, print to stderr
import os, sys PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ )) SRC_DIR = os.path.join(PROJECT_DIR, "src") TEST_DIR = os.path.join(PROJECT_DIR, "test") def runtestdir(subdir): entries = os.listdir(subdir) total = 0 errs = 0 for f in entries: if not f.endswith(".py"): continue if not f.startswith("test_"): continue test_file = os.path.join(subdir, f) print >> sys.stderr, "FILE:", test_file exit_code = os.system(sys.executable + " " + test_file) total += 1 if exit_code != 0: errs += 1 print >> sys.stderr, "SUMMARY: %s -> %s total / %s error (%s)" \ % (subdir, total, errs, sys.executable) if __name__ == "__main__": os.chdir(TEST_DIR) os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR]) runtestdir("bindertest")
import os, sys PROJECT_DIR = os.path.abspath(os.path.dirname( __file__ )) SRC_DIR = os.path.join(PROJECT_DIR, "src") TEST_DIR = os.path.join(PROJECT_DIR, "test") def runtestdir(subdir): entries = os.listdir(subdir) total = 0 errs = 0 for f in entries: if not f.endswith(".py"): continue if not f.startswith("test_"): continue test_file = os.path.join(subdir, f) print "FILE:", test_file exit_code = os.system(sys.executable + " " + test_file) total += 1 if exit_code != 0: errs += 1 print "SUMMARY: %s -> %s total / %s error (%s)" \ % (subdir, total, errs, sys.executable) if __name__ == "__main__": os.chdir(TEST_DIR) os.environ["PYTHONPATH"] = ":".join([SRC_DIR, TEST_DIR]) runtestdir("bindertest")
Set default for get_config to None.
from django.shortcuts import _get_queryset from django.conf import settings def get_object_or_None(klass, *args, **kwargs): """ Uses get() to return an object or None if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Note: Like with get(), a MultipleObjectsReturned will be raised if more than one object is found. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: return None def get_config(key, default=None): """ Get settings from django.conf if exists, return default value otherwise example: ADMIN_EMAIL = get_config('ADMIN_EMAIL', 'default@email.com') """ return getattr(settings, key, default)
from django.shortcuts import _get_queryset from django.conf import settings def get_object_or_None(klass, *args, **kwargs): """ Uses get() to return an object or None if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Note: Like with get(), a MultipleObjectsReturned will be raised if more than one object is found. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: return None def get_config(key, default): """ Get settings from django.conf if exists, return default value otherwise example: ADMIN_EMAIL = get_config('ADMIN_EMAIL', 'default@email.com') """ return getattr(settings, key, default)
Add compressed style to sass build
var gulp = require('gulp'); var gulpUtil = require('gulp-util'); var gulpIf = require('gulp-if'); var browserSync = require('browser-sync').create(); var uglify = require('gulp-uglify'); var sass = require('gulp-ruby-sass'); var jshint = require('gulp-jshint'); var jshintStylish = require('jshint-stylish'); var useref = require('gulp-useref'); var imagemin = require('gulp-imagemin'); var del = require('del'); // Tasks gulp.task('build:sass', function () { return sass('scss/main.scss', { sourcemap: true }) .on('error', sass.logError) .pipe(gulp.dest('_site/css')); .pipe(sourcemaps.write('maps', { includeContent: false, sourceRoot: 'source' })) });
var gulp = require('gulp'); var gulpUtil = require('gulp-util'); var gulpIf = require('gulp-if'); var browserSync = require('browser-sync').create(); var uglify = require('gulp-uglify'); var sass = require('gulp-ruby-sass'); var jshint = require('gulp-jshint'); var jshintStylish = require('jshint-stylish'); var useref = require('gulp-useref'); var imagemin = require('gulp-imagemin'); var del = require('del'); // Tasks gulp.task('build:sass', function () { return sass('scss/main.scss') .on('error', sass.logError) .pipe(gulp.dest('_site/css')); });
Update import to use flask.ext
# -*- coding: utf-8 -*- """ Flask-Login example =================== This is a small application that provides a trivial demonstration of Flask-Login, including remember me functionality. :copyright: (C) 2011 by Matthew Frazier. :license: MIT/X11, see LICENSE for more details. """ from flask import Flask from flask.exti.olinauth import OlinAuth, auth_required, current_user app = Flask(__name__) SECRET_KEY = "yeah, not actually a secret" DEBUG = True app.config.from_object(__name__) oa = OlinAuth(app) #initial OlinAuth, with callback host of localhost:5000 oa.init_app(app, 'localhost:5000') @app.route("/") def index(): if current_user: responseString = "Awesome index, guess what? %s is logged in. Sweet, right?" % current_user['id'] else: responseString = "It is kind of lonely here... No users are logged in" return responseString @app.route("/secret") @auth_required def secret(): return "I wouldn't normally show you this, but since %s is logged in, here is the secret: 42" % current_user['id'] if __name__ == "__main__": app.run(debug=True)
# -*- coding: utf-8 -*- """ Flask-Login example =================== This is a small application that provides a trivial demonstration of Flask-Login, including remember me functionality. :copyright: (C) 2011 by Matthew Frazier. :license: MIT/X11, see LICENSE for more details. """ from flask import Flask from flask_olinauth import OlinAuth, auth_required, current_user app = Flask(__name__) SECRET_KEY = "yeah, not actually a secret" DEBUG = True app.config.from_object(__name__) oa = OlinAuth(app) #initial OlinAuth, with callback host of localhost:5000 oa.init_app(app, 'localhost:5000') @app.route("/") def index(): if current_user: responseString = "Awesome index, guess what? %s is logged in. Sweet, right?" % current_user['id'] else: responseString = "It is kind of lonely here... No users are logged in" return responseString @app.route("/secret") @auth_required def secret(): return "I wouldn't normally show you this, but since %s is logged in, here is the secret: 42" % current_user['id'] if __name__ == "__main__": app.run(debug=True)
Use full path in file reading error
var fs = require('fs'); var parallelStream = require('pelias-parallel-stream'); var maxInFlight = 10; module.exports.create = function create_json_parse_stream(dataDirectory) { return parallelStream(maxInFlight, function(record, enc, next) { var full_file_path = dataDirectory + record.path; fs.readFile(full_file_path, function(err, data) { if (err) { console.error('exception reading file ' + full_file_path); next(err); } else { try { var object = JSON.parse(data); next(null, object); } catch (parse_err) { console.error('exception parsing JSON in file %s:', record.path, parse_err); console.error('Inability to parse JSON usually means that WOF has been cloned ' + 'without using git-lfs, please see instructions here: ' + 'https://github.com/whosonfirst/whosonfirst-data#git-and-large-files'); next(parse_err); } } }); }); };
var fs = require('fs'); var parallelStream = require('pelias-parallel-stream'); var maxInFlight = 10; module.exports.create = function create_json_parse_stream(dataDirectory) { return parallelStream(maxInFlight, function(record, enc, next) { fs.readFile(dataDirectory + record.path, function(err, data) { if (err) { console.error('exception reading file ' + record.path); next(err); } else { try { var object = JSON.parse(data); next(null, object); } catch (parse_err) { console.error('exception parsing JSON in file %s:', record.path, parse_err); console.error('Inability to parse JSON usually means that WOF has been cloned ' + 'without using git-lfs, please see instructions here: ' + 'https://github.com/whosonfirst/whosonfirst-data#git-and-large-files'); next(parse_err); } } }); }); };
Replace placeholders in comment url
<?php namespace Jacobemerick\CommentService\Serializer; use DateTime; use Jacobemerick\CommentService\Serializer\Commenter as CommenterSerializer; class Comment { public function __construct() {} /** * @param array $comment * @returns array */ public function __invoke(array $comment) { $commenterSerializer = new CommenterSerializer(); return [ 'id' => $comment['id'], 'commenter' => $commenterSerializer([ 'id' => $comment['commenter_id'], 'name' => $comment['commenter_name'], 'website' => $comment['commenter_website'], ]), 'body' => $comment['body'], 'date' => (new DateTime($comment['date']))->format('c'), 'url' => $this->prepareUrl($comment['url'], $comment), 'reply_to' => $comment['reply_to'], 'thread' => $comment['thread'], ]; } protected function prepareUrl($url, array $comment) { return str_replace('{{id}}}', $comment['id'], $url); } }
<?php namespace Jacobemerick\CommentService\Serializer; use DateTime; use Jacobemerick\CommentService\Serializer\Commenter as CommenterSerializer; class Comment { public function __construct() {} /** * @param array $comment * @returns array */ public function __invoke(array $comment) { $commenterSerializer = new CommenterSerializer(); return [ 'id' => $comment['id'], 'commenter' => $commenterSerializer([ 'id' => $comment['commenter_id'], 'name' => $comment['commenter_name'], 'website' => $comment['commenter_website'], ]), 'body' => $comment['body'], 'date' => (new DateTime($comment['date']))->format('c'), 'url' => $comment['url'], // todo magic replacement 'reply_to' => $comment['reply_to'], 'thread' => $comment['thread'], ]; } }
Print that table is dropped.
package emp; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import oracle.ucp.jdbc.PoolDataSource; import oracle.ucp.jdbc.PoolDataSourceFactory; /** * Drops the employee table used by the other examples. */ public class DropTable { public static void main(String[] args) throws SQLException { PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource(); pool.setURL(args[0]); pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource"); try (Connection con = pool.getConnection()) { Statement stmt = con.createStatement(); stmt.execute("drop table emp"); System.out.println("Table dropped."); } } }
package emp; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import oracle.ucp.jdbc.PoolDataSource; import oracle.ucp.jdbc.PoolDataSourceFactory; /** * Drops the employee table used by the other examples. */ public class DropTable { public static void main(String[] args) throws SQLException { PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource(); pool.setURL(args[0]); pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource"); try (Connection con = pool.getConnection()) { Statement stmt = con.createStatement(); stmt.execute("drop table emp"); } } }
Add more tests for sneeze.
import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit", "from nipype.interfaces import afni", "import nipype.interfaces.afni", "from nipype.interfaces import afni as af"] def test_imports(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') for impt in import_strings: fp = open(fname, 'w') fp.write(impt) fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path yield assert_equal, cmd, \ 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni' if os.path.exists(dname): rmtree(dname)
import os from tempfile import mkdtemp from shutil import rmtree from nipy.testing import * from sneeze import find_pkg, run_nose import_strings = ["from nipype.interfaces.afni import To3d", "from nipype.interfaces import afni", "import nipype.interfaces.afni"] def test_from_namespace(): dname = mkdtemp() fname = os.path.join(dname, 'test_afni.py') fp = open(fname, 'w') fp.write('from nipype.interfaces.afni import To3d') fp.close() cover_pkg, module = find_pkg(fname) cmd = run_nose(cover_pkg, fname, dry_run=True) cmdlst = cmd.split() cmd = ' '.join(cmdlst[:4]) # strip off temporary directory path #print cmd assert_equal(cmd, 'nosetests -sv --with-coverage --cover-package=nipype.interfaces.afni') if os.path.exists(dname): rmtree(dname)
fix: Reduce sample size for faster processing
# importing modules/ libraries import pandas as pd import random import numpy as np # create a sample of prior orders orders_df = pd.read_csv("Data/orders.csv") s = round(3214874 * 0.01) i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s)) orders_df.loc[i,:].to_csv("Data/orders_prior_sample.csv", index = False) # create a sample of train orders s = round(131209 * 0.01) j = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="train"].index), s)) orders_df.loc[j,:].to_csv("Data/orders_train_sample.csv", index = False) # create a sample of prior order products order_products_prior_df = pd.read_csv('Data/order_products__prior.csv', index_col = 'order_id') order_products_prior_df.loc[orders_df.loc[i,:]['order_id'],:].to_csv("Data/order_products_prior_sample.csv") # create a sample of train order products order_products_train_df = pd.read_csv('Data/order_products__train.csv', index_col = 'order_id') order_products_train_df.loc[orders_df.loc[j,:]['order_id'],:].to_csv("Data/order_products_train_sample.csv")
# importing modules/ libraries import pandas as pd import random import numpy as np # create a sample of prior orders orders_df = pd.read_csv("Data/orders.csv") s = round(3214874 * 0.1) i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s)) orders_df.loc[i,:].to_csv("Data/orders_prior_sample.csv", index = False) # create a sample of train orders s = round(131209 * 0.1) j = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="train"].index), s)) orders_df.loc[j,:].to_csv("Data/orders_train_sample.csv", index = False) # create a sample of prior order products order_products_prior_df = pd.read_csv('Data/order_products__prior.csv', index_col = 'order_id') order_products_prior_df.loc[orders_df.loc[i,:]['order_id'],:].to_csv("Data/order_products_prior_sample.csv") # create a sample of train order products order_products_train_df = pd.read_csv('Data/order_products__train.csv', index_col = 'order_id') order_products_train_df.loc[orders_df.loc[j,:]['order_id'],:].to_csv("Data/order_products_train_sample.csv")
Add inputs plugin to computation.
'use strict'; const FreeSurfer = require('freesurfer-parser'); const pkg = require('../package.json'); const localRunner = require('./local'); const remoteRunner = require('./remote'); module.exports = { name: pkg.name, version: pkg.version, plugins: ['group-step', 'inputs'], local: [ { type: 'function', fn(opts) { // simulate pre-processing step. we actually are passing in // pre-processed data. required s.t. remote compute node can assert // that all users have correct data shape (e.g. num features) const rslt = localRunner.preprocess(opts); console.log('pre-processing complete.'); return rslt; }, verbose: true, inputs: [{ help: 'Select Freesurfer region(s) of interest', label: 'Freesurfer ROI', values: FreeSurfer.validFields, }] }, { type: 'function', fn(opts) { return localRunner.run(opts); }, verbose: true, }, ], remote: { type: 'function', fn(opts) { return remoteRunner.run(opts); }, verbose: true, }, };
'use strict'; const pkg = require('../package.json'); const localRunner = require('./local'); const remoteRunner = require('./remote'); module.exports = { name: pkg.name, version: pkg.version, plugins: ['group-step'], local: [ { type: 'function', fn(opts) { // simulate pre-processing step. we actually are passing in // pre-processed data. required s.t. remote compute node can assert // that all users have correct data shape (e.g. num features) const rslt = localRunner.preprocess(opts); console.log('pre-processing complete.'); return rslt; }, verbose: true, }, { type: 'function', fn(opts) { return localRunner.run(opts); }, verbose: true, }, ], remote: { type: 'function', fn(opts) { return remoteRunner.run(opts); }, verbose: true, }, };
Write test that attempts to unpack invalid archive
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os import sys import pytest @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('filling up the boring replacements', r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text @needinternet def test_check_get_invalid_archive(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('what file? hahahaha', r'http://rlee287.github.io/pyautoupdate/testing2/', newfiles="project.tar.gz") launch._get_new() assert os.path.isfile("project.tar.gz.dump") os.remove("project.tar.gz.dump")
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os import sys import pytest @pytest.mark.trylast @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" package=fixture_update_dir("0.0.1") launch = Launcher('filling up the boring replacements', r'http://rlee287.github.io/pyautoupdate/testing/') launch._get_new() with open(os.path.abspath("downloads/extradir/blah.py"), "r") as file_code: file_text=file_code.read() assert "new version" in file_text
Make it possible to do a password input field
(function registerInputFieldLayout(){ widget.layout.register( 'inputField', createInputField, { description: "TODO!" }, { styleClass: 'inputFieldHolder' } ); function createInputField( def ) { var view = def.parent; var data = def.layout; var options = def.options; var fieldKey = (data.dataSource.path).replace( /\./g, "_" ); var panel = $('<div/>' ); var field = $('<input>').attr( { id: fieldKey, name: fieldKey, type: data.fieldType || 'text', placeholder: data.placeholder }).addClass( 'inputField' ); if( options.readonly ) field.addClass('readonly').prop( 'readonly', options.readonly ); var sourceData = widget.util.get( data.dataSource.type, data.dataSource.path ); if( sourceData ) field.val( sourceData ); field.on( 'propertychange keyup input paste', function(){ widget.util.set( data.dataSource.type, data.dataSource.path, field.val() ); }); if( data.label ) { panel.append( $('<label/>', { html: data.label } ) ); } panel.append( field ); return panel.appendTo( view ); } })();
(function registerInputFieldLayout(){ widget.layout.register( 'inputField', createInputField, { description: "TODO!" }, { styleClass: 'inputFieldHolder' } ); function createInputField( def ) { var view = def.parent; var data = def.layout; var options = def.options; var fieldKey = (data.dataSource.path).replace( /\./g, "_" ); var panel = $('<div/>' ); var field = $('<input>').attr( { id: fieldKey, name: fieldKey, placeholder: data.placeholder }).addClass( 'inputField' ); if( options.readonly ) field.addClass('readonly').prop( 'readonly', options.readonly ); var sourceData = widget.util.get( data.dataSource.type, data.dataSource.path ); if( sourceData ) field.val( sourceData ); field.on( 'propertychange keyup input paste', function(){ widget.util.set( data.dataSource.type, data.dataSource.path, field.val() ); }); if( data.label ) { panel.append( $('<label/>', { html: data.label } ) ); } panel.append( field ); return panel.appendTo( view ); } })();
Remove '/blog/' from the post url. Was pretty unnecessary.
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('posts.views', # Examples: url(r'^$', 'home', name='blog_home'), url(r'^(?P<post_year>\d{4})/(?P<post_month>\d{2})/(?P<post_title>\w+)/$', 'post', name='blog_post'), url(r'^archive/$', 'archive', name='blog_archive'), url(r'^about/$', 'about', name='blog_about_me'), # url(r'^blog/', include('blog.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('posts.views', # Examples: url(r'^$', 'home', name='blog_home'), url(r'^blog/(?P<post_year>\d{4})/(?P<post_month>\d{2})/(?P<post_title>\w+)/$', 'post', name='blog_post'), url(r'^archive/$', 'archive', name='blog_archive'), url(r'^about/$', 'about', name='blog_about_me'), # url(r'^blog/', include('blog.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
Bump pyyaml from 3.12 to 5.1 Bumps [pyyaml](https://github.com/yaml/pyyaml) from 3.12 to 5.1. - [Release notes](https://github.com/yaml/pyyaml/releases) - [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES) - [Commits](https://github.com/yaml/pyyaml/compare/3.12...5.1) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com>
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='b2fuse', version=1.3, description="FUSE integration for Backblaze B2 Cloud storage", long_description=read('README.md'), classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5 ', 'Programming Language :: Python :: 3.6', ], keywords='', author='Sondre Engebraaten', packages=find_packages(), install_requires=['b2==1.1.0', 'fusepy==2.0.4', 'PyYAML==5.1'], include_package_data=True, zip_safe=True, entry_points={ 'console_scripts': ['b2fuse = b2fuse.b2fuse:main',], } )
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='b2fuse', version=1.3, description="FUSE integration for Backblaze B2 Cloud storage", long_description=read('README.md'), classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5 ', 'Programming Language :: Python :: 3.6', ], keywords='', author='Sondre Engebraaten', packages=find_packages(), install_requires=['b2==1.1.0', 'fusepy==2.0.4', 'PyYAML==3.12'], include_package_data=True, zip_safe=True, entry_points={ 'console_scripts': ['b2fuse = b2fuse.b2fuse:main',], } )
fix: Refresh on all 401 responses
const mediaType = 'application/vnd.cignium.resource+json' export async function request(method, href, data, config) { const request = { body: data && JSON.stringify(data), credentials: 'include', headers: new Headers({ Accept: 'application/json' }), method, } const response = await fetch(href, request) const contentType = response.headers.get('Content-Type') if (response.status == 401) { location.href = method.toLowerCase() == 'get' ? response.url : location.href return } if (response.status >= 400 && response.status < 600) { throw Error(`${response.status}: ${response.statusText}`) } if (contentType.startsWith(mediaType)) { return await response.json() } if (config && config.onRedirect) { let content = await response.text() content = config.onRedirect(response.url, content) if (content) { content.type = 'html' content.links = [{ rel: 'self', href: response.url }] } return content } location.href = response.url return null }
const mediaType = 'application/vnd.cignium.resource+json' export async function request(method, href, data, config) { const request = { body: data && JSON.stringify(data), credentials: 'include', headers: new Headers({ Accept: 'application/json' }), method, } const response = await fetch(href, request) const contentType = response.headers.get('Content-Type') if (response.status == 401 && contentType && contentType.startsWith('text/html')) { location.href = method.toLowerCase() == 'get' ? response.url : location.href return } if (response.status >= 400 && response.status < 600) { throw Error(`${response.status}: ${response.statusText}`) } if (contentType.startsWith(mediaType)) { return await response.json() } if (config && config.onRedirect) { let content = await response.text() content = config.onRedirect(response.url, content) if (content) { content.type = 'html' content.links = [{ rel: 'self', href: response.url }] } return content } location.href = response.url return null }
Add wait() to login test with wrong credentials to fix WebDriver test
<?php use tests\_pages\LoginPage; $I = new WebGuy($scenario); $I->wantTo('ensure that login works'); $loginPage = LoginPage::openBy($I); $I->see('Login', 'h1'); $I->amGoingTo('try to login with empty credentials'); $loginPage->login('', ''); $I->expectTo('see validations errors'); $I->see('Username cannot be blank.'); $I->see('Password cannot be blank.'); $I->amGoingTo('try to login with wrong credentials'); $loginPage->login('admin', 'wrong'); if (method_exists($I, 'wait')) { $I->wait(3); // only for selenium } $I->expectTo('see validations errors'); $I->see('Incorrect username or password.'); $I->amGoingTo('try to login with correct credentials'); $loginPage->login('admin', 'admin'); if (method_exists($I, 'wait')) { $I->wait(3); // only for selenium } $I->expectTo('see user info'); $I->see('Logout (admin)');
<?php use tests\_pages\LoginPage; $I = new WebGuy($scenario); $I->wantTo('ensure that login works'); $loginPage = LoginPage::openBy($I); $I->see('Login', 'h1'); $I->amGoingTo('try to login with empty credentials'); $loginPage->login('', ''); $I->expectTo('see validations errors'); $I->see('Username cannot be blank.'); $I->see('Password cannot be blank.'); $I->amGoingTo('try to login with wrong credentials'); $loginPage->login('admin', 'wrong'); $I->expectTo('see validations errors'); $I->see('Incorrect username or password.'); $I->amGoingTo('try to login with correct credentials'); $loginPage->login('admin', 'admin'); if (method_exists($I, 'wait')) { $I->wait(3); // only for selenium } $I->expectTo('see user info'); $I->see('Logout (admin)');
Add Identify function to parser
package parser import "fmt" // Identify tries to figure out the format of the structured data passed in // If the data format could not be identified, an error will be returned func Identify(input []byte) (string, error) { for _, name := range parseOrder() { if parsed, err := parsers[name].parse(input); err == nil { fmt.Println(name, parsed) return name, nil } } return "", fmt.Errorf("input format could not be identified") } func auto(input []byte) (interface{}, error) { for _, name := range parseOrder() { if parsed, err := parsers[name].parse(input); err == nil { return parsed, err } } return nil, fmt.Errorf("input format could not be identified") } func parseOrder() []string { order := make([]string, 0, len(parsers)) tried := make(map[string]bool) var tryParser func(string) tryParser = func(name string) { if tried[name] { return } for _, pref := range parsers[name].prefers { tryParser(pref) } order = append(order, name) tried[name] = true } for name := range parsers { if name != "auto" { tryParser(name) } } return order } func init() { parsers["auto"] = parser{ parse: auto, } }
package parser import "fmt" func auto(input []byte) (interface{}, error) { for _, name := range parseOrder() { if parsed, err := parsers[name].parse(input); err == nil { return parsed, err } } return nil, fmt.Errorf("input format could not be identified") } func parseOrder() []string { order := make([]string, 0, len(parsers)) tried := make(map[string]bool) var tryParser func(string) tryParser = func(name string) { if tried[name] { return } for _, pref := range parsers[name].prefers { tryParser(pref) } order = append(order, name) tried[name] = true } for name := range parsers { if name != "auto" { tryParser(name) } } return order } func init() { parsers["auto"] = parser{ parse: auto, } }
Fix calendar modal default value
import React, { PropTypes } from 'react'; import { TransitionView, Calendar } from 'react-date-picker'; import Modal from '../Modal'; const propTypes = { open: PropTypes.bool.isRequired, defaultDate: PropTypes.string, onClose: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired }; const TimePickerModal = props => props.open && <Modal onClose={props.onClose} className="time-picker"> <div className="flex-col"> <TransitionView> <Calendar dateFormat="YYYY-MM-DD HH:mm:ss" defaultDate={props.defaultDate || ''} onChange={(dateString) => props.onChange(dateString)} /> </TransitionView> <button className="btn btn-primary btn--absolute" onClick={props.onClose} > Apply </button> </div> </Modal>; TimePickerModal.propTypes = propTypes; export default TimePickerModal;
import React, { PropTypes } from 'react'; import { TransitionView, Calendar } from 'react-date-picker'; import Modal from '../Modal'; const propTypes = { open: PropTypes.bool.isRequired, defaultDate: PropTypes.string, onClose: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired }; const now = new Date(); const defaultProps = { defaultDate: now.toISOString().replace('T', ' ') .slice(0, -5) }; const TimePickerModal = props => props.open && <Modal onClose={props.onClose} className="time-picker"> <div className="flex-col"> <TransitionView> <Calendar dateFormat="YYYY-MM-DD HH:mm:ss" defaultDate={props.defaultDate} onChange={(dateString) => props.onChange(dateString)} /> </TransitionView> <button className="btn btn-primary btn--absolute" onClick={props.onClose} > Apply </button> </div> </Modal>; TimePickerModal.propTypes = propTypes; TimePickerModal.defaultProps = defaultProps; export default TimePickerModal;
Add genres and set max width instead of height.
$('form').submit(function(event) { event.preventDefault(); var movie = $('#movie'), id = $('#search-id').val(); movie.html('<img src="/static/img/loading.gif">'); var request = $.getJSON('/movie/' + id + '/110', function(data) { var html = ''; html += '<img src="' + data.poster + '" class="img-polaroid">'; html += '<section class="movie-info">'; html += '<h2>' + data.title + '</h2>'; html += '<p>Genres: '; $.each(data.genres, function(index, value) { html += value; if (data.genres[index + 1]) { html += ' / '; } }); html += '</p>'; html += '<p>Rating: ' + data.vote_average + ' (' + data.vote_count + ' votes)</p>'; html += '<p>Release date: ' + data.release_date + '</p>'; html += '<p>' + data.overview + '</p>'; html += '</section>'; movie.html(html); }); request.fail(function(jqXHR, textStatus) { movie.html('<div class="alert alert-error">Bad request!</div>'); }); });
$('form').submit(function(event) { event.preventDefault(); var movie = $('#movie'), id = $('#search-id').val(); movie.html('<img src="/static/img/loading.gif">'); var request = $.getJSON('/movie/' + id + '/0/150', function(data) { var html = ''; html += '<img src="' + data.poster + '" class="img-polaroid">'; html += '<section class="movie-info">'; html += '<h2>' + data.title + '</h2>'; html += '<p>Rating: ' + data.vote_average + ' (' + data.vote_count + ' votes)</p>'; html += '<p>Release date: ' + data.release_date + '</p>'; html += '<p>' + data.overview + '</p>'; html += '</section>'; movie.html(html); }); request.fail(function(jqXHR, textStatus) { movie.html('<div class="alert alert-error">Bad request!</div>'); }); });
Change field "id" to "pk" in order to not conflict with Python "id" keyword
from app import db class Base(db.Model): __abstract__ = True pk = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'routes' origin_point = db.Column(db.String(128), nullable=False) destination_point = db.Column(db.String(128), nullable=False) distance = db.Column(db.Integer, nullable=False) def __repr__(self): return '<Route <{0}-{1}-{2}>'.format(self.origin_point, self.destination_point, self.distance)
from app import db class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'routes' origin_point = db.Column(db.String(128), nullable=False) destination_point = db.Column(db.String(128), nullable=False) distance = db.Column(db.Integer, nullable=False) def __repr__(self): return '<Route <{0}-{1}-{2}>'.format(self.origin_point, self.destination_point, self.distance)
Add the parent element to the list of potential targets
var arrayUnion = require('array-union'); module.exports = function(el, targets, states) { var targetNames = []; var state; var nodes; var elTargetName; // first we want to find all targets and their names for(var stateName in states) { state = states[ stateName ]; if(state) { targetNames = arrayUnion(targetNames, state.constructor === Object ? Object.keys(state) : [] ); } } // then we'll get all elements with the `data-f1` attribute nodes = el.querySelectorAll('[data-f1]'); // then we'll cross reference and grab only the nodes we want to act on for(var i = 0; i < nodes.length; i++) { elTargetName = nodes[ i ].getAttribute('data-f1'); if(targetNames.indexOf(elTargetName) !== -1) { targets[ elTargetName ] = nodes[ i ]; } } // Add the container to potential target list as well if (elTargetName = el.getAttribute('data-f1')) targets[ elTargetName ] = el; };
var arrayUnion = require('array-union'); module.exports = function(el, targets, states) { var targetNames = []; var state; var nodes; var elTargetName; // first we want to find all targets and their names for(var stateName in states) { state = states[ stateName ]; if(state) { targetNames = arrayUnion(targetNames, state.constructor === Object ? Object.keys(state) : [] ); } } // then we'll get all elements with the `data-f1` attribute nodes = el.querySelectorAll('[data-f1]'); // then we'll cross reference and grab only the nodes we want to act on for(var i = 0; i < nodes.length; i++) { elTargetName = nodes[ i ].getAttribute('data-f1'); if(targetNames.indexOf(elTargetName) !== -1) { targets[ elTargetName ] = nodes[ i ]; } } };
Add a check in ResponsesShowWindow if view is defined or not
function ResponseShowWindow(responseID) { var ResponseShowView = require('ui/common/responses/ResponseShowView'); var ResponseEditWindow = require('ui/handheld/android/ResponseEditWindow'); var self = Ti.UI.createWindow({ navBarHidden : true, backgroundColor : "#fff" }); var view = new ResponseShowView(responseID); self.add(view); var activityIndicator = Ti.UI.Android.createProgressIndicator({ message : L('activity_indicator'), location : Ti.UI.Android.PROGRESS_INDICATOR_DIALOG, type : Ti.UI.Android.PROGRESS_INDICATOR_INDETERMINANT }); self.add(activityIndicator); view.addEventListener('ResponseShowView:responseEdit', function(e) { activityIndicator.show(); new ResponseEditWindow(e.responseID).open(); activityIndicator.hide(); }); view.addEventListener('ResponseShowView:responseDeleted', function(e) { self.close(); Ti.App.fireEvent('ResponseShowWindow:closed'); }); self.addEventListener('android:back', function() { if (view) view.cleanup(); view = null; self.close(); Ti.App.fireEvent('ResponseShowWindow:back'); }); return self; } module.exports = ResponseShowWindow;
function ResponseShowWindow(responseID) { var ResponseShowView = require('ui/common/responses/ResponseShowView'); var ResponseEditWindow = require('ui/handheld/android/ResponseEditWindow'); var self = Ti.UI.createWindow({ navBarHidden : true, backgroundColor : "#fff" }); var view = new ResponseShowView(responseID); self.add(view); var activityIndicator = Ti.UI.Android.createProgressIndicator({ message : L('activity_indicator'), location : Ti.UI.Android.PROGRESS_INDICATOR_DIALOG, type : Ti.UI.Android.PROGRESS_INDICATOR_INDETERMINANT }); self.add(activityIndicator); view.addEventListener('ResponseShowView:responseEdit', function(e) { activityIndicator.show(); new ResponseEditWindow(e.responseID).open(); activityIndicator.hide(); }); view.addEventListener('ResponseShowView:responseDeleted', function(e) { self.close(); Ti.App.fireEvent('ResponseShowWindow:closed'); }); self.addEventListener('android:back', function() { view.cleanup(); view = null; self.close(); Ti.App.fireEvent('ResponseShowWindow:back'); }); return self; } module.exports = ResponseShowWindow;
Replace newlines with <br /> tags
var Mehdown; if (typeof exports === 'object' && typeof require === 'function') { Mehdown = exports; } else { Mehdown = {}; } Mehdown.usernameRegExp = /(^|[^@\w])@(\w{1,15})\b/g; Mehdown.parse = function(text) { // Replace newlines with <br /> tags text = text.replace(/\n/g, '<br />\n'); // Hashtags text = text.replace(/(^|[^#\w])#([a-z0-9_-]+)\b/gi, '$1' + Mehdown.hashtag('$2')); // Usernames text = text.replace(Mehdown.usernameRegExp, '$1' + Mehdown.username('$2')); return text; }; Mehdown.hashtag = function(hashtag) { return '<a href="https://mediocre.com/tags/' + hashtag + '">#' + hashtag + '</a>'; } Mehdown.username = function(username) { //return '<span class="vcard"><a href="https://mediocre.com/forums/users/' + username + '">@<span class="fn nickname">' + username + '</span></a>'; return '<a href="/brenner/users/' + username + '">@' + username + '</a>'; }
var Mehdown; if (typeof exports === 'object' && typeof require === 'function') { Mehdown = exports; } else { Mehdown = {}; } Mehdown.usernameRegExp = /(^|[^@\w])@(\w{1,15})\b/g; Mehdown.parse = function(text) { // Hashtags text = text.replace(/(^|[^#\w])#([a-z0-9_-]+)\b/gi, '$1' + Mehdown.hashtag('$2')); // Usernames text = text.replace(Mehdown.usernameRegExp, '$1' + Mehdown.username('$2')); return text; }; Mehdown.hashtag = function(hashtag) { return '<a href="https://mediocre.com/tags/' + hashtag + '">#' + hashtag + '</a>'; } Mehdown.username = function(username) { //return '<span class="vcard"><a href="https://mediocre.com/forums/users/' + username + '">@<span class="fn nickname">' + username + '</span></a>'; return '<a href="/brenner/users/' + username + '">@' + username + '</a>'; }
Fix git mvn problem with white space
package org.graphwalker.io.factory; /* * #%L * GraphWalker Input/Output * %% * Copyright (C) 2011 - 2014 GraphWalker * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ /** * Created by krikar on 8/20/14. */ public class YEdParsingException extends RuntimeException { public YEdParsingException(Throwable throwable) { super(throwable); } public YEdParsingException(String message) { super(message); } }
package org.graphwalker.io.factory; /* * #%L * GraphWalker Input/Output * %% * Copyright (C) 2011 - 2014 GraphWalker * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ /** * Created by krikar on 8/20/14. */ public class YEdParsingException extends RuntimeException { public YEdParsingException(Throwable throwable) { super(throwable); } public YEdParsingException(String message) { super(message); } }
Check for undefined localized values Fixes #2.
'use strict'; /** * Retrieve a localized configuration value or the default if the localization * is unavailable. * * @param {String} configuration value * @param {String} language * @param {Object} Hexo configuration object * @param {String} Hexo locals object * @returns {*} localized or default configuration value */ exports._c = function _c(value, lang, config, locals) { if (locals.data['config_' + lang] != null) { var localized = retrieveItem(locals.data['config_' + lang], value) return localized != undefined ? localized : retrieveItem(config, value); } return retrieveItem(config, value); }; /** * Retrieve nested item from object/array (http://stackoverflow.com/a/16190716) * @param {Object|Array} obj * @param {String} path dot separated * @param {*} def default value ( if result undefined ) * @returns {*} */ function retrieveItem(obj, path, def) { var i, len; for (i = 0, path = path.split('.'), len = path.length; i < len; i++) { if (!obj || typeof obj !== 'object') return def; obj = obj[path[i]]; } if (obj === undefined) return def; return obj; }
'use strict'; /** * Retrieve a localized configuration value or the default if the localization * is unavailable. * * @param {String} configuration value * @param {String} language * @param {Object} Hexo configuration object * @param {String} Hexo locals object * @returns {*} localized or default configuration value */ exports._c = function _c(value, lang, config, locals) { if (locals.data['config_' + lang] != null) { return retrieveItem(locals.data['config_' + lang], value) || retrieveItem(config, value); } return retrieveItem(config, value); }; /** * Retrieve nested item from object/array (http://stackoverflow.com/a/16190716) * @param {Object|Array} obj * @param {String} path dot separated * @param {*} def default value ( if result undefined ) * @returns {*} */ function retrieveItem(obj, path, def) { var i, len; for (i = 0, path = path.split('.'), len = path.length; i < len; i++) { if (!obj || typeof obj !== 'object') return def; obj = obj[path[i]]; } if (obj === undefined) return def; return obj; }
Add outputPath to test scenario 2.
/*jshint node:true*/ /* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var options; switch (process.env.TEST_SCENARIO) { case undefined: case '1': break; case '2': options = { loadExternal: true, outputPath: 'new-relic.js' }; break; } var app = new EmberAddon(defaults, { // Add options here 'ember-new-relic': options }); /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
/*jshint node:true*/ /* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var options; switch (process.env.TEST_SCENARIO) { case undefined: case '1': break; case '2': options = { loadExternal: true, outputPath: '' }; break; } var app = new EmberAddon(defaults, { // Add options here 'ember-new-relic': options }); /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
[fix] Fix problem with callbacks called out of order
var assert = require('assert'); var assertCalled = module.exports = function (cb) { var index = assertCalled.wanted.push({ callback: cb, error: new Error() }); return function () { wanted[index - 1] = null; cb.apply(this, arguments); }; }; var wanted = assertCalled.wanted = []; process.on('exit', function () { var msg; wanted = wanted.filter(Boolean); if (wanted.length) { msg = wanted.length + ' callback' + (wanted.length > 1 ? 's' : '') + ' not called:'; wanted.forEach(function (func) { var stack; msg += '\n ' + (func.callback.name ? func.callback.name : '<anonymous>') + '\n'; stack = func.error.stack.split('\n'); stack.splice(0, 2); msg += stack.join('\n') + '\n'; }); throw new assert.AssertionError({ message: msg, actual: wanted.length, expected: 0 }); } });
var assert = require('assert'); var assertCalled = module.exports = function (cb) { var index = assertCalled.wanted.push({ callback: cb, error: new Error() }); return function () { wanted.splice(index - 1, 1); cb.apply(this, arguments); }; }; var wanted = assertCalled.wanted = []; process.on('exit', function () { var msg; if (wanted.length) { msg = wanted.length + ' callback' + (wanted.length > 1 ? 's' : '') + ' not called:'; wanted.forEach(function (func) { var stack; msg += '\n ' + (func.callback.name ? func.callback.name : '<anonymous>') + '\n'; stack = func.error.stack.split('\n'); stack.splice(0, 2); msg += stack.join('\n') + '\n'; }); throw new assert.AssertionError({ message: msg, actual: wanted.length, expected: 0 }); } });
Check for `GNdr` grammeme in `gender-match` label
GENDERS = ("masc", "femn", "neut", "Ms-f", "GNdr") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) *case_token_genders, case_token_msf, case_token_gndr = next(results) *candidate_token_genders, candidate_token_msf, candidate_token_gndr = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True elif case_token_gndr or candidate_token_gndr: return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, }
GENDERS = ("masc", "femn", "neut", "Ms-f") def gram_label(token, value, stack): return value in token.grammemes def gram_not_label(token, value, stack): return not value in token.grammemes def gender_match_label(token, index, stack, genders=GENDERS): results = ((g in t.grammemes for g in genders) for t in (stack[index], token)) *case_token_genders, case_token_msf = next(results) *candidate_token_genders, candidate_token_msf = next(results) if not candidate_token_genders == case_token_genders: if case_token_msf: if any(candidate_token_genders[:2]): return True else: return True return False def dictionary_label(token, values, stack): return any((n in values) for n in token.forms) LABELS_LOOKUP_MAP = { "gram": gram_label, "gram-not": gram_not_label, "dictionary": dictionary_label, "gender-match": gender_match_label, }
Clean logic in Communities preflight
import requests from cumulusci.tasks.salesforce import BaseSalesforceApiTask class IsCommunitiesEnabled(BaseSalesforceApiTask): api_version = "48.0" def _run_task(self): s = requests.Session() s.get(self.org_config.start_url).raise_for_status() r = s.get( "{}/sites/servlet.SitePrerequisiteServlet".format( self.org_config.instance_url ) ) self.return_values = r.status_code == 200 self.logger.info( "Completed Communities preflight check with result {}".format( self.return_values ) )
import requests from cumulusci.tasks.salesforce import BaseSalesforceApiTask class IsCommunitiesEnabled(BaseSalesforceApiTask): api_version = "48.0" def _run_task(self): s = requests.Session() s.get(self.org_config.start_url).raise_for_status() r = s.get( "{}/sites/servlet.SitePrerequisiteServlet".format( self.org_config.instance_url ) ) if r.status_code != 200: self.return_values = False else: self.return_values = True self.logger.info( "Completed Communities preflight check with result {}".format( self.return_values ) )
Fix form PageForm needs updating.
from django.conf import settings from django.contrib import admin from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.utils.module_loading import import_string FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.TinyMCE') FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', {'attrs': {'cols': 100, 'rows': 15}}) class PageForm(FlatpageForm): class Meta: model = FlatPage widgets = { 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), } fields = '__all__' class PageAdmin(FlatPageAdmin): """ Page Admin """ form = PageForm admin.site.unregister(FlatPage) admin.site.register(FlatPage, PageAdmin)
from django.conf import settings from django.contrib import admin from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.utils.module_loading import import_string FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.TinyMCE') FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', {'attrs': {'cols': 100, 'rows': 15}}) class PageForm(FlatpageForm): class Meta: model = FlatPage widgets = { 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), } class PageAdmin(FlatPageAdmin): """ Page Admin """ form = PageForm admin.site.unregister(FlatPage) admin.site.register(FlatPage, PageAdmin)
Allow to set allowClear in alchemyPageSelect Sometimes we do not want to allow to clear the selection.
$.fn.alchemyPageSelect = function (options) { var pageTemplate = HandlebarsTemplates.page return this.select2({ placeholder: options.placeholder, allowClear: options.hasOwnProperty("allowClear") ? options.allowClear : true, minimumInputLength: 3, initSelection: function (_$el, callback) { if (options.initialSelection) { callback(options.initialSelection) } }, ajax: { url: options.url, datatype: "json", quietMillis: 300, data: function (term, page) { return { q: $.extend( { name_cont: term }, options.query_params ), page: page } }, results: function (data) { var meta = data.meta return { results: data.pages, more: meta.page * meta.per_page < meta.total_count } } }, formatSelection: function (page) { return page.text || page.name }, formatResult: function (page) { return pageTemplate({ page: page }) } }) }
$.fn.alchemyPageSelect = function(options) { var pageTemplate = HandlebarsTemplates.page return this.select2({ placeholder: options.placeholder, allowClear: true, minimumInputLength: 3, initSelection: function (_$el, callback) { if (options.initialSelection) { callback(options.initialSelection) } }, ajax: { url: options.url, datatype: 'json', quietMillis: 300, data: function (term, page) { return { q: $.extend({ name_cont: term }, options.query_params), page: page } }, results: function (data) { var meta = data.meta return { results: data.pages, more: meta.page * meta.per_page < meta.total_count } } }, formatSelection: function (page) { return page.text || page.name }, formatResult: function(page) { return pageTemplate({page: page}) } }) }
Use the right URI for send
<?php namespace MessageBird\Resources\Conversation; use MessageBird\Common\HttpClient; use MessageBird\Exceptions; use MessageBird\Objects\Conversation\SendMessage; use MessageBird\Objects\Conversation\SendMessageResult; use MessageBird\Resources\Base; class Send extends Base { const RESOURCE_NAME = 'send'; public function __construct(HttpClient $httpClient) { parent::__construct($httpClient); $this->setObject(new SendMessageResult()); $this->setResourceName(self::RESOURCE_NAME); } /** * Starts a conversation or adding a message to the conversation when a conversation with the contact already exist. * * @param SendMessage $object * @param array|null $query * * @return SendMessageResult * * @throws Exceptions\HttpException * @throws Exceptions\RequestException * @throws Exceptions\ServerException */ public function send($object, $query = null) { $body = json_encode($object); list(, , $resultBody) = $this->HttpClient->performHttpRequest( HttpClient::REQUEST_POST, $this->getResourceName(), $query, $body ); return $this->processRequest($resultBody); } }
<?php namespace MessageBird\Resources\Conversation; use MessageBird\Common\HttpClient; use MessageBird\Exceptions; use MessageBird\Objects\Conversation\SendMessage; use MessageBird\Objects\Conversation\SendMessageResult; use MessageBird\Resources\Base; class Send extends Base { const RESOURCE_NAME = 'conversations/send'; public function __construct(HttpClient $httpClient) { parent::__construct($httpClient); $this->setObject(new SendMessageResult()); $this->setResourceName(self::RESOURCE_NAME); } /** * Starts a conversation or adding a message to the conversation when a conversation with the contact already exist. * * @param SendMessage $object * @param array|null $query * * @return SendMessageResult * * @throws Exceptions\HttpException * @throws Exceptions\RequestException * @throws Exceptions\ServerException */ public function send($object, $query = null) { $body = json_encode($object); list(, , $body) = $this->HttpClient->performHttpRequest( HttpClient::REQUEST_POST, $this->getResourceName(), $query, $body ); return $this->processRequest($body); } }
Add levels to log output
package statemachine import ( "log" "os" ) type Handler func() string type Machine struct { Handlers map[string]Handler Logger *log.Logger } type StateMachineError struct { State string } func (sme StateMachineError) Error() string { return "ERROR: No handler function registered for state: " + sme.State } func NewMachine() Machine { return Machine{ Handlers: map[string]Handler{}, Logger: log.New(os.Stdout, "statemachine: ", 0), } } func (machine Machine) AddState(stateName string, handlerFn Handler) { machine.Handlers[stateName] = handlerFn } func (machine Machine) Run() (success bool, error error) { state := "INIT" machine.Logger.Println("INFO: Starting in state: INIT") for { if handler, present := machine.Handlers[state]; present { oldstate := state state = handler() machine.Logger.Printf("INFO: State transition: %s -> %s\n", oldstate, state) if state == "END" { machine.Logger.Println("INFO: Terminating") return true, nil } } else { err := StateMachineError{state} machine.Logger.Print(err) return false, err } } }
package statemachine import ( "log" "os" ) type Handler func() string type Machine struct { Handlers map[string]Handler Logger *log.Logger } type StateMachineError struct { State string } func (sme StateMachineError) Error() string { return "statemachine: No handler function registered for state: " + sme.State } func NewMachine() Machine { return Machine{ Handlers: map[string]Handler{}, Logger: log.New(os.Stdout, "statemachine: ", 0), } } func (machine Machine) AddState(stateName string, handlerFn Handler) { machine.Handlers[stateName] = handlerFn } func (machine Machine) Run() (success bool, error error) { state := "INIT" machine.Logger.Println("Starting in state: INIT") for { if handler, present := machine.Handlers[state]; present { oldstate := state state = handler() machine.Logger.Printf("State transition: %s -> %s\n", oldstate, state) if state == "END" { machine.Logger.Println("Terminating") return true, nil } } else { return false, StateMachineError{state} } } }
Update tests for vectors for the new protocol Now the tests for vectors are updated for the new non backward compatible change for the concepts of label and base.
"""Tests for vectors.""" from sympy import sympify from drudge import Vec def test_vecs_has_basic_properties(): """Tests the basic properties of vector instances.""" base = Vec('v') v_ab = Vec('v', indices=['a', 'b']) v_ab_1 = base['a', 'b'] v_ab_2 = (base['a'])['b'] indices_ref = (sympify('a'), sympify('b')) hash_ref = hash(v_ab) str_ref = 'v[a, b]' repr_ref = "Vec('v', (a, b))" for i in [v_ab, v_ab_1, v_ab_2]: assert i.label == base.label assert i.base == base assert i.indices == indices_ref assert hash(i) == hash_ref assert i == v_ab assert str(i) == str_ref assert repr(i) == repr_ref
"""Tests for vectors.""" from sympy import sympify from drudge import Vec def test_vecs_has_basic_properties(): """Tests the basic properties of vector instances.""" base = Vec('v') v_ab = Vec('v', indices=['a', 'b']) v_ab_1 = base['a', 'b'] v_ab_2 = (base['a'])['b'] indices_ref = (sympify('a'), sympify('b')) hash_ref = hash(v_ab) str_ref = 'v[a, b]' repr_ref = "Vec('v', (a, b))" for i in [v_ab, v_ab_1, v_ab_2]: assert i.base == base.base assert i.indices == indices_ref assert hash(i) == hash_ref assert i == v_ab assert str(i) == str_ref assert repr(i) == repr_ref
Disable logging in test runs SPEED!
"""Django configuration for testing and CI environments.""" from .common import * # Use in-memory file storage DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' # Speed! PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'TEST': {} } } # Disable logging import logging logging.disable(logging.CRITICAL) env = get_secret("ENVIRONMENT") import sys if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv: # and this allows you to use --reuse-db to skip re-creating the db, # even faster! # # To create the RAMDisk, use bash: # $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB)) # /dev/disk2 # $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2 DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
"""Django configuration for testing and CI environments.""" from .common import * # Use in-memory file storage DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' # Speed! PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'TEST': {} } } env = get_secret("ENVIRONMENT") import sys if os.path.isdir('/Volumes/RAMDisk') and not env == 'ci' and not 'create-db' in sys.argv: # and this allows you to use --reuse-db to skip re-creating the db, # even faster! # # To create the RAMDisk, use bash: # $ hdiutil attach -nomount ram://$((2 * 1024 * SIZE_IN_MB)) # /dev/disk2 # $ diskutil eraseVolume HFS+ RAMDisk /dev/disk2 DATABASES['default']['TEST']['NAME'] = '/Volumes/RAMDisk/unkenmathe.test.db.sqlite3'
Fix random wrong month or year in prayer times
package com.i906.mpt.date; import java.util.Calendar; import java.util.TimeZone; import javax.inject.Inject; import javax.inject.Singleton; /** * @author Noorzaini Ilhami */ @Singleton class DateProvider { private Calendar mCalendar; @Inject DateProvider() { } private void refresh() { mCalendar = getCalendarInstance(); } public long getCurrentTime() { return System.currentTimeMillis(); } public Calendar getNow() { refresh(); return mCalendar; } public Calendar getCalendarInstance() { return Calendar.getInstance(TimeZone.getTimeZone("GMT+8")); } }
package com.i906.mpt.date; import java.util.Calendar; import java.util.TimeZone; import javax.inject.Inject; import javax.inject.Singleton; /** * @author Noorzaini Ilhami */ @Singleton class DateProvider { private final Calendar mCalendar; @Inject DateProvider() { mCalendar = getCalendarInstance(); } private void refresh() { mCalendar.setTimeInMillis(getCurrentTime()); } public long getCurrentTime() { return System.currentTimeMillis(); } public Calendar getNow() { refresh(); return mCalendar; } public Calendar getCalendarInstance() { return Calendar.getInstance(TimeZone.getTimeZone("GMT+8")); } }
Connect to mongohq in prod
var mongojs = require('mongojs'); process.on('uncaughtException', function (err) { console.error("uncaught exception", err, err.stack); }); var express = require('express'); var app = express(); var mongoConnection = process.env.NODEJOBS_MONGO || 'nodejobs'; app.configure(function () { app.use(express.logger()); app.use(express.bodyParser()); app.use(function(req, res, next){ req.db = mongojs(mongoConnection, ['jobs']); return next(); }); app.use(app.router); app.use(express.compress()); //app.set('views', __dirname + '/../views'); //app.set('view engine', 'jade'); app.use(express.methodOverride()); app.use(express.static(__dirname + '/../public', {clientMaxAge:-1000 * 60 * 60 * 24})); app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); }); require("./webservices/jobs.js")(app); require("./websiteRoutes.js")(app); var port = process.env.PORT || 3000; app.listen(port); console.log('listening on http://localhost:' + port);
var mongojs = require('mongojs'); process.on('uncaughtException', function (err) { console.error("uncaught exception", err, err.stack); }); var express = require('express'); var app = express(); app.configure(function () { app.use(express.logger()); app.use(express.bodyParser()); app.use(function(req, res, next){ req.db = mongojs('nodejobs', ['jobs']); return next(); }); app.use(app.router); app.use(express.compress()); //app.set('views', __dirname + '/../views'); //app.set('view engine', 'jade'); app.use(express.methodOverride()); app.use(express.static(__dirname + '/../public', {clientMaxAge:-1000 * 60 * 60 * 24})); app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!'); }); }); require("./webservices/jobs.js")(app); require("./websiteRoutes.js")(app); var port = process.env.PORT || 3000; app.listen(port); console.log('listening on http://localhost:' + port);
Allow disabling of native PG driver
var pg = null , native = null try { pg = require('pg') native = pg.native } catch (__e) { if (!pg) { exports.create = exports.createQuery = function () { throw new Exception("pg driver failed to load, please `npm install pg`") } return } } var Transaction = require('../transaction') var helpers = require('../helpers') exports.forceJS = false exports.createConnection = function (url, callback) { var opts = helpers.prepareUrl(url) , scheme = url.protocol , backend = (exports.forceJS || !native) ? pg : native , conn = backend.Client(opts) if (callback) { conn.connect(function (err) { if (err) callback(err) else callback(null, conn) }) } else { conn.connect() } conn.begin = Transaction.createBeginMethod(exports.createQuery) //conn.query = wrapQueryMethod(conn.query) return conn } // Create a Query object that conforms to the Any-DB interface exports.createQuery = function (stmt, params, callback) { var backend = (exports.forceJS || !native) ? pg : native return new backend.Query(stmt, params, callback) }
var pg = null try { pg = require('pg') pg = pg.native } catch (__e) { if (!pg) { exports.create = exports.createQuery = function () { throw new Exception("pg driver failed to load, please `npm install pg`") } return } } var Transaction = require('../transaction') var helpers = require('../helpers') exports.createConnection = function (url, callback) { var opts = helpers.prepareUrl(url) , conn = new pg.Client(opts) if (callback) { conn.connect(function (err) { if (err) callback(err) else callback(null, conn) }) } else { conn.connect() } conn.begin = Transaction.createBeginMethod(exports.createQuery) //conn.query = wrapQueryMethod(conn.query) return conn } // Create a Query object that conforms to the Any-DB interface exports.createQuery = function (stmt, params, callback) { return new pg.Query(stmt, params, callback) }
Make UI view listener priority higher
<?php namespace HotfixBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class ViewListenerPriorityPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('oro_ui.view.listener')) { return; } $definition = $container->getDefinition('oro_ui.view.listener'); $tags = $definition->getTags(); if (array_key_exists('kernel.event_listener', $tags)) { foreach ($tags['kernel.event_listener'] as &$tag) { if (array_key_exists('event', $tag) && 'kernel.view' === $tag['event']) { $tag['priority'] = 255; // 50 does not always seem to be enough } } $definition->setTags($tags); } } }
<?php namespace HotfixBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class ViewListenerPriorityPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('oro_ui.view.listener')) { return; } $definition = $container->getDefinition('oro_ui.view.listener'); $tags = $definition->getTags(); if (array_key_exists('kernel.event_listener', $tags)) { foreach ($tags['kernel.event_listener'] as &$tag) { if (array_key_exists('event', $tag) && 'kernel.view' === $tag['event']) { $tag['priority'] = 50; } } $definition->setTags($tags); } } }
Add command to flush out the database
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { var phoneNumber = req.params.From; var message = req.params.Body.toLowerCase(); if (message === 'flush') { session.flushall(function () { messenger('The database has been flushed.'); }); } session.get(phoneNumber, function(err, user) { if (err) { messenger.send(phoneNumber, 'There was some kind of error.'); res.send(500, {error: 'Something went wrong.'}); } if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); }); } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
var restify = require('restify'); var messenger = require('./lib/messenger'); var session = require('./lib/session'); var server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.authorizationParser()); server.get('/', function (req, res, next) { res.send(200, {status: 'ok'}); }); server.post('/messages', function (req, res, next) { console.log(req); var phoneNumber = req.params.From; session.get(phoneNumber, function(err, user) { if (err) { messenger.send(phoneNumber, 'There was some kind of error.'); res.send(500, {error: 'Something went wrong.'}); } if (user) { messenger.send(phoneNumber, 'Hello, old friend.'); } else { session.set(phoneNumber, 'initial', function () { messenger.send(phoneNumber, 'Nice to meet you.'); }); } }); res.send(200, {status: 'ok'}); }); server.listen(process.env.PORT || '3000', function() { console.log('%s listening at %s', server.name, server.url); });
Remove 'Forgot password' from sign in form'
<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="E-postadress eller nick" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <label><input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> </form>
<form name="loginform" action="<?php bloginfo("wpurl");?>/wp-login.php" method="post"> <input type="hidden" name="redirect_to" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" /> <input type="hidden" name="user-cookie" value="1" /> <p> <input type="text" name="log" placeholder="E-postadress eller nick" <?php if(isset($_POST['user_email'])) echo 'value="'. $_POST['user_email'] .'" autofocus' ?> /> <input type="password" name="pwd" placeholder="Lösenord" /> </p> <p> <input type="checkbox" id="rememberme" name="rememberme" value="forever" checked="checked" /> <label for="rememberme">Håll mig inloggad</label> <input type="submit" name="submit" class="small" value="Logga in" /> </p> <p class="extra-info"> <a href="<?php echo wp_lostpassword_url();?>">Glömt lösenord</a> </p> </form>
Use 'with ... as ...' for file opening. Standardize variable names.
""" Sending a message: Encrypt your plaintext with encrypt_message Your id will serve as your public key Reading a message Use decrypt_message and validate contents """ from Crypto.PublicKey import RSA # Generates and writes byte string with object of RSA key object def create_key(): key = RSA.generate(2048) with open('key.pem', 'w') as f: f.write(key.exportKey('PEM')) # Reads an exported key-bytestring from file and returns an RSA key object def retrieve_key(): with open('key.pem', 'r') as f: key = RSA.importKey(f.read()) return key def get_public_bytestring(): key = retrieve_key() return key.publickey().exportKey() # Use own private key to decrypt broadcasted message def decrypt_message(message): key = retrieve_key() return key.decrypt(message) # Use given id to encrypt message def encrypt_message(key_string, message): key = RSA.importKey(key_string) return key.encrypt(message, 123)
""" Sending a message: Encrypt your plaintext with encrypt_message Your id will serve as your public key Reading a message Use decrypt_message and validate contents """ from Crypto.PublicKey import RSA # Generates and writes byte string with object of RSA key object def create_key(): key = RSA.generate(2048) f = open('key.pem', 'w') f.write(key.exportKey('PEM')) f.close() # Reads an exported key-bytestring from file and returns an RSA key object def retrieve_key(): f = open('key.pem', 'r') key = RSA.importKey(f.read()) return key def get_public_bytestring(): key = retrieve_key() return key.publickey().exportKey() # Use own private key to decrypt broadcasted message def decrypt_message(message): key_obj = retrieve_key() return key_obj.decrypt(message) # Use given id to encrypt message def encrypt_message(key_string, message): key = RSA.importKey(key_string) return key.encrypt(message, 123)
Add additional test to determine monster
const { describe, it } = global; import {expect} from 'chai'; import {default as GameUtil} from '../game'; describe('game utilities', () => { it('determines the correct monster', () => { const winMap = [ { ingredients: [ 'BloodOfVirgin', 'EyeOfEnemy' ], expectedMonster: 'Ooze' }, { ingredients: [ 'BloodOfVirgin', 'BasilPetal' ], expectedMonster: 'Soup' }, { ingredients: [ 'BasilPetal', 'BasilPetal' ], expectedMonster: 'Basil' }, { ingredients: [ 'EyeOfEnemy', 'BasilPetal' ], expectedMonster: 'Fairy' } ]; winMap.forEach((test) => { let monster = GameUtil.determineMonster( test.ingredients ); expect(monster.name).to.be.equal( test.expectedMonster ); // // Test the inverse // monster = gameUtil.determineMonster( // test.ingredients // ); // expect(monster.label).to.be.equal( // test.expectedMonster // ); }); }); });
const { describe, it } = global; import {expect} from 'chai'; import {default as GameUtil} from '../game'; describe('game utilities', () => { it('determines the correct monster', () => { const winMap = [ { ingredients: [ 'BloodOfVirgin', 'EyeOfEnemy' ], expectedMonster: 'Ooze' }, { ingredients: [ 'BloodOfVirgin', 'BasilPetal' ], expectedMonster: 'Soup' }, { ingredients: [ 'BasilPetal', 'BasilPetal' ], expectedMonster: 'Basil' } ]; winMap.forEach((test) => { let monster = GameUtil.determineMonster( test.ingredients ); expect(monster.name).to.be.equal( test.expectedMonster ); // // Test the inverse // monster = gameUtil.determineMonster( // test.ingredients // ); // expect(monster.label).to.be.equal( // test.expectedMonster // ); }); }); });
Add additional shortcuts for top level package
"""Dependency injector.""" from .catalog import AbstractCatalog from .catalog import override from .providers import Provider from .providers import Delegate from .providers import Factory from .providers import Singleton from .providers import ExternalDependency from .providers import Class from .providers import Object from .providers import Function from .providers import Value from .providers import Callable from .providers import Config from .injections import Injection from .injections import KwArg from .injections import Attribute from .injections import Method from .injections import inject from .utils import is_provider from .utils import ensure_is_provider from .utils import is_injection from .utils import ensure_is_injection from .utils import is_kwarg_injection from .utils import is_attribute_injection from .utils import is_method_injection from .errors import Error __all__ = ( # Catalogs 'AbstractCatalog', 'override', # Providers 'Provider', 'Delegate', 'Factory', 'Singleton', 'ExternalDependency', 'Class', 'Object', 'Function', 'Value', 'Callable', 'Config', # Injections 'KwArg', 'Attribute', 'Method', 'inject', # Utils 'is_provider', 'ensure_is_provider', 'is_injection', 'ensure_is_injection', 'is_kwarg_injection', 'is_attribute_injection', 'is_method_injection', # Errors 'Error', )
"""Dependency injector.""" from .catalog import AbstractCatalog from .catalog import override from .providers import Provider from .providers import Delegate from .providers import Factory from .providers import Singleton from .providers import ExternalDependency from .providers import Class from .providers import Object from .providers import Function from .providers import Value from .providers import Callable from .providers import Config from .injections import KwArg from .injections import Attribute from .injections import Method from .injections import inject from .errors import Error __all__ = ('AbstractCatalog', # Providers 'Provider', 'Delegate', 'Factory', 'Singleton', 'ExternalDependency', 'Class', 'Object', 'Function', 'Value', 'Callable', 'Config', # Injections 'KwArg', 'Attribute', 'Method', # Decorators 'override', 'inject', # Errors 'Error')
Return empty list if nothing found
''' Created on 17-sep.-2012 @author: ldevocht ''' import urllib.request import urllib.parse import lxml.objectify import logging logger = logging.getLogger('pathFinder') def dbPediaPrefix(prefix): gateway = 'http://lookup.dbpedia.org/api/search.asmx/PrefixSearch?QueryString={0}'.format(prefix) request = urllib.parse.quote(gateway, ':/=?<>"*&') logger.debug('Request %s' % request) raw_output = urllib.request.urlopen(request).read() root = lxml.objectify.fromstring(raw_output) results = list() for result in root.Result: if hasattr(result.Classes, 'Class'): klasses = result.Classes.Class if hasattr(klasses, 'Label'): klasse = klasses else: klasse = klasses[0] item = dict() item['label'] = result.Label[0].text item['category']=klasse.Label.text item['value']=result.URI[0].text results.append(item) return results print (dbPediaPrefix('Lon'))
''' Created on 17-sep.-2012 @author: ldevocht ''' import urllib.request import urllib.parse import lxml.objectify import logging logger = logging.getLogger('pathFinder') def dbPediaPrefix(prefix): gateway = 'http://lookup.dbpedia.org/api/search.asmx/PrefixSearch?QueryString={0}'.format(prefix) request = urllib.parse.quote(gateway, ':/=?<>"*&') logger.debug('Request %s' % request) raw_output = urllib.request.urlopen(request).read() root = lxml.objectify.fromstring(raw_output) results = list() for result in root.Result: if hasattr(result.Classes, 'Class'): klasses = result.Classes.Class if hasattr(klasses, 'Label'): klasse = klasses else: klasse = klasses[0] item = dict() item['label'] = result.Label[0].text item['type']=klasse.Label.text item['value']=result.URI[0].text results.append(item) return results print (dbPediaPrefix('Lon'))
Throw IllegalAccessException like in RuleAnnotatedMethod
/* * Copyright 2015-2016 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package org.junit.jupiter.migrationsupport.rules.member; import static org.junit.platform.commons.meta.API.Usage.Internal; import java.lang.reflect.Field; import java.util.logging.Logger; import org.junit.platform.commons.meta.API; import org.junit.platform.commons.util.ExceptionUtils; import org.junit.rules.TestRule; @API(Internal) public class RuleAnnotatedField extends AbstractRuleAnnotatedMember { private static final Logger LOG = Logger.getLogger(RuleAnnotatedField.class.getName()); public RuleAnnotatedField(Object testInstance, Field testRuleField) { try { testRuleField.setAccessible(true); this.testRuleInstance = (TestRule) testRuleField.get(testInstance); } catch (IllegalAccessException exception) { throw ExceptionUtils.throwAsUncheckedException(exception); } } }
/* * Copyright 2015-2016 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package org.junit.jupiter.migrationsupport.rules.member; import static org.junit.platform.commons.meta.API.Usage.Internal; import java.lang.reflect.Field; import java.util.logging.Logger; import org.junit.platform.commons.meta.API; import org.junit.rules.TestRule; @API(Internal) public class RuleAnnotatedField extends AbstractRuleAnnotatedMember { private static final Logger LOG = Logger.getLogger(RuleAnnotatedField.class.getName()); public RuleAnnotatedField(Object testInstance, Field testRuleField) { try { testRuleField.setAccessible(true); this.testRuleInstance = (TestRule) testRuleField.get(testInstance); } catch (IllegalAccessException exception) { LOG.warning(exception.getMessage()); } } }
Revert "added constructor (testcommit for new git interface)" This reverts commit d5c0252b75e97103d61c3203e2a8d04a061c8a2f.
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # Copyright 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Scoville. # # Scoville 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. # # Scoville 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 Scoville. # If not, see http://www.gnu.org/licenses/. ########################################################### import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): pass
#!/usr/bin/python #-*- coding: utf-8 -*- ########################################################### # Copyright 2011 Daniel 'grindhold' Brendle and Team # # This file is part of Scoville. # # Scoville 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. # # Scoville 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 Scoville. # If not, see http://www.gnu.org/licenses/. ########################################################### import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): def __init__(self): pass
Move favorite button inside h1 tag
import React from 'react'; import numeral from 'numeral'; import { Link } from 'react-router'; import FavoriteCategoryButton from '../favorites/FavoriteCategoryButton'; import Icon from '../widgets/Icon'; const Tag = ({ tag, removeCategoryFavorite, addCategoryFavorite, isFavorited }) => <div className="page"> <div className="my-3 text-xs-center"> <h1> <FavoriteCategoryButton name={tag.name} isFavorited={isFavorited} onClick={isFavorited ? () => removeCategoryFavorite(tag.name) : () => addCategoryFavorite(tag.name) } /> { ' ' } <Link to={`/hot/${tag.name}`}>#{tag.name}</Link>{' '} </h1> <h2> <Icon name="library_books" lg /> {numeral(tag.comments).format('0,0')}{' '} <Icon name="attach_money" lg /> {numeral(tag.total_payouts).format('$0,0')} </h2> </div> </div>; export default Tag;
import React from 'react'; import numeral from 'numeral'; import { Link } from 'react-router'; import FavoriteCategoryButton from '../favorites/FavoriteCategoryButton'; import Icon from '../widgets/Icon'; const Tag = ({ tag, removeCategoryFavorite, addCategoryFavorite, isFavorited }) => <div className="page"> <div className="my-3 text-xs-center"> <span> <FavoriteCategoryButton name={tag.name} isFavorited={isFavorited} onClick={isFavorited ? () => removeCategoryFavorite(tag.name) : () => addCategoryFavorite(tag.name) } /> </span> <h1 style={{ display: 'inline-block' }}> { ' ' } <Link to={`/hot/${tag.name}`}>#{tag.name}</Link>{' '} </h1> <h2> <Icon name="library_books" lg /> {numeral(tag.comments).format('0,0')}{' '} <Icon name="attach_money" lg /> {numeral(tag.total_payouts).format('$0,0')} </h2> </div> </div>; export default Tag;
Create lambda instead of IF in GroupCreationTest
package ru.sfwt.mt.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ru.sfwt.mt.addressbook.model.GroupData; import java.util.Comparator; import java.util.HashSet; import java.util.List; public class GroupCreationTests extends TestBase{ @Test public void testGroupCreation() { app.getNavigationHelper().gotoGroupPage(); List<GroupData> before = app.getGroupHelper().getGroupList(); GroupData group = new GroupData("test5", null, null); app.getGroupHelper().createGroup(group); List<GroupData> after = app.getGroupHelper().getGroupList(); Assert.assertEquals(after.size(), before.size() +1); // int max = 0; // for (GroupData g : after) { // if (g.getId() > max) { // max = g.getId(); // } // } group.setId(after.stream().max((Comparator<GroupData>) (o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId()); before.add(group); Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after)); } }
package ru.sfwt.mt.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ru.sfwt.mt.addressbook.model.GroupData; import java.util.HashSet; import java.util.List; public class GroupCreationTests extends TestBase{ @Test public void testGroupCreation() { app.getNavigationHelper().gotoGroupPage(); List<GroupData> before = app.getGroupHelper().getGroupList(); GroupData group = new GroupData("test1", null, null); app.getGroupHelper().createGroup(group); List<GroupData> after = app.getGroupHelper().getGroupList(); Assert.assertEquals(after.size(), before.size() +1); int max = 0; for (GroupData g : after) { if (g.getId() > max) { max = g.getId(); } } group.setId(max); before.add(group); Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after)); } }
Update log for local server
const cacheManager = require('cache-manager'); const createWebhook = require('github-webhook-handler'); const createIntegration = require('github-integration'); const Raven = require('raven'); const createRobot = require('./lib/robot'); const createServer = require('./lib/server'); module.exports = options => { const cache = cacheManager.caching({ store: 'memory', ttl: 60 * 60 // 1 hour }); const webhook = createWebhook({path: '/', secret: options.secret}); const integration = createIntegration({ id: options.id, cert: options.cert, debug: process.env.LOG_LEVEL === 'trace' }); const server = createServer(webhook); const robot = createRobot(integration, webhook, cache); if (process.env.SENTRY_URL) { Raven.config(process.env.SENTRY_URL, { captureUnhandledRejections: true }).install({}); } // Handle case when webhook creation fails webhook.on('error', err => { Raven.captureException(err); robot.log.error(err); }); return { server, robot, start() { server.listen(options.port); robot.log.trace('Listening on http://localhost:' + options.port); }, load(plugin) { plugin(robot); } }; };
const cacheManager = require('cache-manager'); const createWebhook = require('github-webhook-handler'); const createIntegration = require('github-integration'); const Raven = require('raven'); const createRobot = require('./lib/robot'); const createServer = require('./lib/server'); module.exports = options => { const cache = cacheManager.caching({ store: 'memory', ttl: 60 * 60 // 1 hour }); const webhook = createWebhook({path: '/', secret: options.secret}); const integration = createIntegration({ id: options.id, cert: options.cert, debug: process.env.LOG_LEVEL === 'trace' }); const server = createServer(webhook); const robot = createRobot(integration, webhook, cache); if (process.env.SENTRY_URL) { Raven.config(process.env.SENTRY_URL, { captureUnhandledRejections: true }).install({}); } // Handle case when webhook creation fails webhook.on('error', err => { Raven.captureException(err); robot.log.error(err); }); return { server, robot, start() { server.listen(options.port); console.log('Listening on http://localhost:' + options.port); }, load(plugin) { plugin(robot); } }; };
Fix exception to be valid error default code 1 instead of 244.
<?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration * @since 3.2.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Console\Exception; use Cake\Console\Command; use Cake\Core\Exception\Exception; /** * Exception class for halting errors in console tasks * * @see \Cake\Console\Shell::_stop() * @see \Cake\Console\Shell::error() * @see \Cake\Console\Command::abort() */ class StopException extends Exception { /** * Default exception code * * @var int */ protected $_defaultCode = Command::CODE_ERROR; }
<?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration * @since 3.2.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Console\Exception; use Cake\Core\Exception\Exception; /** * Exception class for halting errors in console tasks * * @see \Cake\Console\Shell::_stop() * @see \Cake\Console\Shell::error() */ class StopException extends Exception { }
Add group validation middleware to routes
import dotenv from 'dotenv'; import authControllers from '../controllers'; import authenticate from '../middleware/authenticate'; import validateGroup from '../middleware/validateGroup'; const usersController = authControllers.users; const loginController = authControllers.login; const groupsController = authControllers.group; const messagesController = authControllers.messages; dotenv.config(); module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the Postit API!', })); app.post('/api/user/signin', loginController.login); app.post('/api/user/signup', usersController.create); // An API route that allow users create broadcast groups: // POST: /api/group app.post('/api/group', authenticate, validateGroup.name, groupsController.create); // An API route that allow users add other users to groups: app.post('/api/group/:groupid/user', authenticate, groupsController.addNewUser); // An API route that allows a logged in user post messages to created groups: app.post('/api/group/:groupid/message', authenticate, messagesController.create); // An API route that allows a logged in user retrieve messages that have been // posted to groups he/she belongs to: app.get('/api/group/:groupid/messages', authenticate, groupsController.list); // Root route app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist')); };
import dotenv from 'dotenv'; import authControllers from '../controllers'; import authenticate from '../middleware/authenticate'; const usersController = authControllers.users; const loginController = authControllers.login; const groupsController = authControllers.group; const messagesController = authControllers.messages; dotenv.config(); module.exports = (app) => { app.get('/api', (req, res) => res.status(200).send({ message: 'Welcome to the Postit API!', })); app.post('/api/user/signin', loginController.login); app.post('/api/user/signup', usersController.create); // An API route that allow users create broadcast groups: // POST: /api/group app.post('/api/group', authenticate, groupsController.create); // An API route that allow users add other users to groups: app.post('/api/group/:groupid/user', authenticate, groupsController.addNewUser); // An API route that allows a logged in user post messages to created groups: app.post('/api/group/:groupid/message', authenticate, messagesController.create); // An API route that allows a logged in user retrieve messages that have been // posted to groups he/she belongs to: app.get('/api/group/:groupid/messages', authenticate, groupsController.list); // Root route app.get('*', (req, res) => res.send('Sorry, the page u requested does not exist')); };
Add missing error URL regex
from django.conf.urls.defaults import * import views urlpatterns = patterns('', url(r'^$', views.home, name='pontoon.home'), url(r'^error/$', views.home, name='pontoon.home'), url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'), url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'), url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'), url(r'^a/$', views.admin, name='pontoon.admin'), url(r'^get/', views.get_translation, name='pontoon.get'), url(r'^save/', views.save_translation, name='pontoon.save'), url(r'^load/', views.load_entities, name='pontoon.load'), url(r'^download/', views.download, name='pontoon.download'), url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'), url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'), url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'), url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'), )
from django.conf.urls.defaults import * import views urlpatterns = patterns('', url(r'^$', views.home, name='pontoon.home'), url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'), url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'), url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'), url(r'^a/$', views.admin, name='pontoon.admin'), url(r'^get/', views.get_translation, name='pontoon.get'), url(r'^save/', views.save_translation, name='pontoon.save'), url(r'^load/', views.load_entities, name='pontoon.load'), url(r'^download/', views.download, name='pontoon.download'), url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'), url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'), url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'), url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'), )
Remove debug output from playerCache closes #227
package youtube import ( "time" ) const defaultCacheExpiration = time.Minute * time.Duration(5) type playerCache struct { key string expiredAt time.Time config playerConfig } // Get : get cache when it has same video id and not expired func (s playerCache) Get(key string) playerConfig { return s.GetCacheBefore(key, time.Now()) } // GetCacheBefore : can pass time for testing func (s playerCache) GetCacheBefore(key string, time time.Time) playerConfig { if key == s.key && s.expiredAt.After(time) { return s.config } return nil } // Set : set cache with default expiration func (s *playerCache) Set(key string, operations playerConfig) { s.setWithExpiredTime(key, operations, time.Now().Add(defaultCacheExpiration)) } func (s *playerCache) setWithExpiredTime(key string, config playerConfig, time time.Time) { s.key = key s.config = config s.expiredAt = time }
package youtube import ( "log" "time" ) const defaultCacheExpiration = time.Minute * time.Duration(5) type playerCache struct { key string expiredAt time.Time config playerConfig } // Get : get cache when it has same video id and not expired func (s playerCache) Get(key string) playerConfig { result := s.GetCacheBefore(key, time.Now()) if result == nil { log.Println("Cache miss for", key) } else { log.Println("Cache hit for", key) } return result } // GetCacheBefore : can pass time for testing func (s playerCache) GetCacheBefore(key string, time time.Time) playerConfig { if key == s.key && s.expiredAt.After(time) { return s.config } return nil } // Set : set cache with default expiration func (s *playerCache) Set(key string, operations playerConfig) { s.setWithExpiredTime(key, operations, time.Now().Add(defaultCacheExpiration)) } func (s *playerCache) setWithExpiredTime(key string, config playerConfig, time time.Time) { s.key = key s.config = config s.expiredAt = time }
Fix E226 missing whitespace around arithmetic operator
# -*- coding: utf-8 -*- __all__ = ["FibonacciGenerator"] class FibonacciGenerator(object): """ """ # We use List to cache already founded fibonacci numbers, # and 1 is the first fibonacci number. _fibonacci_list = [0, 1] # 0 is placeholder skip_the_placeholder_idx = 1 def generate(self, n): with_placehoder_len = n + 2 while len(self._fibonacci_list) < with_placehoder_len: self._fibonacci_list.append(self.find_next_fibonacci()) return self._fibonacci_list[self.skip_the_placeholder_idx: n + 1] def find_next_fibonacci(self): """ find the next fibonacci after the last number of `self._fibonacci_list` """ assert len(self._fibonacci_list[-2:]) == 2, self._fibonacci_list[-2:] last2_num, last1_num = self._fibonacci_list[-2:] return last2_num + last1_num
# -*- coding: utf-8 -*- __all__ = ["FibonacciGenerator"] class FibonacciGenerator(object): """ """ # We use List to cache already founded fibonacci numbers, # and 1 is the first fibonacci number. _fibonacci_list = [0, 1] # 0 is placeholder skip_the_placeholder_idx = 1 def generate(self, n): with_placehoder_len = n + 2 while len(self._fibonacci_list) < with_placehoder_len: self._fibonacci_list.append(self.find_next_fibonacci()) return self._fibonacci_list[self.skip_the_placeholder_idx:n+1] def find_next_fibonacci(self): """ find the next fibonacci after the last number of `self._fibonacci_list` """ assert len(self._fibonacci_list[-2:]) == 2, self._fibonacci_list[-2:] last2_num, last1_num = self._fibonacci_list[-2:] return last2_num + last1_num
Add a comment on the cursor position trick.
var undertale = Elm.fullscreen( Elm.UndertaleDialog, { staticRoot: $STATIC_ROOT, scriptRoot: $SCRIPT_ROOT } ); // passing in above doesn't seem to work? undertale.ports.staticRoot.send($STATIC_ROOT); undertale.ports.scriptRoot.send($SCRIPT_ROOT); undertale.ports.focus.subscribe(function(elementId) { setTimeout(function() { var elem = document.getElementById(elementId); if (elem) { // A dumb trick to put the cursor at the end of the text field. elem.focus(); var val = elem.value; elem.value = ''; elem.value = val; } }, 50); });
var undertale = Elm.fullscreen( Elm.UndertaleDialog, { staticRoot: $STATIC_ROOT, scriptRoot: $SCRIPT_ROOT } ); // passing in above doesn't seem to work? undertale.ports.staticRoot.send($STATIC_ROOT); undertale.ports.scriptRoot.send($SCRIPT_ROOT); undertale.ports.focus.subscribe(function(elementId) { setTimeout(function() { var elem = document.getElementById(elementId); if (elem) { elem.focus(); var val = elem.value; elem.value = ''; elem.value = val; } }, 50); });
Write to temp file then rename
<?php ############################################################################### # There are race conditions when using metrics cache with Nagios where # you can have multiple check script querying gmetad and writing to the # same file. To avoid this condition you can run this script periodically # ie. every 10-15 seconds to populate the cache. You will find a shell # script in this directory which runs this command on a specific schedule ############################################################################### $conf['gweb_root'] = dirname(dirname(__FILE__)); include_once $conf['gweb_root'] . "/eval_conf.php"; $context = "cluster"; include_once $conf['gweb_root'] . "/functions.php"; include_once $conf['gweb_root'] . "/ganglia.php"; include_once $conf['gweb_root'] . "/get_ganglia.php"; # Put the serialized metrics into a file file_put_contents($conf['nagios_cache_file'], serialize($metrics)); foreach ( $metrics as $mhost => $host_metrics ) { foreach ( $host_metrics as $name => $attributes ) { $new_metrics[$mhost][$name]['VAL'] = $metrics[$mhost][$name]['VAL']; if ( isset($metrics[$mhost][$name]['UNITS']) ) $new_metrics[$mhost][$name]['UNITS'] = $metrics[$mhost][$name]['UNITS']; } } $temp_file = $conf['nagios_cache_file'] . ".temp"; file_put_contents($temp_file, serialize($new_metrics)); rename($temp_file, $conf['nagios_cache_file']); ?>
<?php ############################################################################### # There are race conditions when using metrics cache with Nagios where # you can have multiple check script querying gmetad and writing to the # same file. To avoid this condition you can run this script periodically # ie. every 10-15 seconds to populate the cache. You will find a shell # script in this directory which runs this command on a specific schedule ############################################################################### $conf['gweb_root'] = dirname(dirname(__FILE__)); include_once $conf['gweb_root'] . "/eval_conf.php"; $context = "cluster"; include_once $conf['gweb_root'] . "/functions.php"; include_once $conf['gweb_root'] . "/ganglia.php"; include_once $conf['gweb_root'] . "/get_ganglia.php"; # Put the serialized metrics into a file file_put_contents($conf['nagios_cache_file'], serialize($metrics)); foreach ( $metrics as $mhost => $host_metrics ) { foreach ( $host_metrics as $name => $attributes ) { $new_metrics[$mhost][$name]['VAL'] = $metrics[$mhost][$name]['VAL']; if ( isset($metrics[$mhost][$name]['UNITS']) ) $new_metrics[$mhost][$name]['UNITS'] = $metrics[$mhost][$name]['UNITS']; } } file_put_contents($conf['nagios_cache_file'], serialize($new_metrics)); ?>
Update entry point for cloud function data fetch
import base64, json from google.cloud import datastore from fetch_trends import get_updated_daily_data from database_updates import update_investment_database def update(event, context): eventdata = event["data"] decoded = base64.b64decode(eventdata) data = json.loads(decoded) start_date = int(data['date']) google_search = data['search'] entity = { "initial_date" : start_date, "search_term" : google_search } get_context(entity) def get_context(entity): print("Started running function") # Instantiates a client datastore_client = datastore.Client() # Retrieve up to date trends data for each search term daily_data = get_updated_daily_data(entity) # Add up to date data do datastore update_investment_database(daily_data, datastore_client)
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/env python3 """ This is the entry point for the Cloud function for getting context data on new investments. """ import base64, json from google.cloud import datastore from fetch_trends import get_updated_daily_data from database_updates import update_investment_database def update(event, context): eventdata = event["data"] decoded = base64.b64decode(eventdata) data = json.loads(decoded) start_date = int(data['date']) google_search = data['search'] get_context(start_date, google_search) def get_context(start_date, google_search): # Instantiates a client datastore_client = datastore.Client() # Retrieve up to date trends data for each search term daily_data = get_updated_daily_data(google_search, start_date) # Add up to date data do datastore update_investment_database(daily_data, datastore_client)
Set status button in serial no
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); if(frm.doc.status == "Sales Returned" && frm.doc.warehouse) cur_frm.add_custom_button(__('Set Status as Available'), function() { cur_frm.set_value("status", "Available"); cur_frm.save(); }); });
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); if(frm.doc.status == "Sales Returned" && frm.doc.warehouse) cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available); }); cur_frm.cscript.set_status_as_available = function() { cur_frm.set_value("status", "Available"); cur_frm.save() }
Fix ending slash in dir
<?php /** * Based on Sensio\Bundle\DistributionBundle\Composer\ScriptHandler * @see https://github.com/sensio/SensioDistributionBundle/blob/master/Composer/ScriptHandler.php */ namespace BoltSkeleton\Composer; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; class ScriptHandler { public static function installConfig($event) { $root = __DIR__.'/../../../'; $boltConfigDir = $root.'vendor/bolt/bolt/app/config/'; $targetDir = $root.'config/'; $filesystem = new Filesystem(); if(!$filesystem->exists($targetDir)) { $filesystem->mkdir($targetDir, 0755); } foreach(Finder::create()->in($boltConfigDir)->name('*.yml.dist') as $file) { $filesystem->copy($boltConfigDir.$file->getFilename(),$targetDir.$file->getFilename()); } } }
<?php /** * Based on Sensio\Bundle\DistributionBundle\Composer\ScriptHandler * @see https://github.com/sensio/SensioDistributionBundle/blob/master/Composer/ScriptHandler.php */ namespace BoltSkeleton\Composer; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; class ScriptHandler { public static function installConfig($event) { $root = __DIR__.'/../../../'; $boltConfigDir = $root.'vendor/bolt/bolt/app/config'; $targetDir = $root.'config/'; $filesystem = new Filesystem(); if(!$filesystem->exists($targetDir)) { $filesystem->mkdir($targetDir, 0755); } foreach(Finder::create()->in($boltConfigDir)->name('*.yml.dist') as $file) { $filesystem->copy($boltConfigDir.$file->getFilename(),$targetDir.$file->getFilename()); } } }
Fix ember test and remove bind syntax
import Ember from 'ember'; var SubRowArray = Ember.ArrayController.extend({ init: function() { this._super(); var self = this; var oldObject = this.get('oldObject'); if (oldObject) { var content = this.get('content'); var oldControllers = oldObject.get('_subControllers'); oldControllers.forEach(function(item) { if (item) { var index = content.indexOf(Ember.get(item, 'content')); self.setControllerAt(item, index); } }); } }, objectAt: function (idx) { return this._subControllers[idx]; }, setControllerAt: function (controller, idx) { this._subControllers[idx] = controller; this.incrementProperty('definedControllersCount', 1); }, objectAtContent: function (idx) { var content = this.get('content'); return content.objectAt(idx); }, definedControllersCount: 0, definedControllers: function () { return this._subControllers.filter(function (item) { return !!item; }); } }); export default SubRowArray;
import Ember from 'ember'; var SubRowArray = Ember.ArrayController.extend({ init: function() { this._super(); var oldObject = this.get('oldObject'); if (oldObject) { var content = this.get('content'); var oldControllers = oldObject.get('_subControllers'); oldControllers.forEach(function(item) { if (item) { var index = content.indexOf(Ember.get(item, 'content')); this.setControllerAt(item, index); } }.bind(this)); } }, objectAt: function (idx) { return this._subControllers[idx]; }, setControllerAt: function (controller, idx) { this._subControllers[idx] = controller; this.incrementProperty('definedControllersCount', 1); }, objectAtContent: function (idx) { var content = this.get('content'); return content.objectAt(idx); }, definedControllersCount: 0, definedControllers: function () { return this._subControllers.filter(function (item) { return !!item; }); } }); export default SubRowArray;
Fix transient error in pikadayToString
import { pad, pikadayToString } from '~/lib/utils/datefix'; describe('datefix', () => { describe('pad', () => { it('should add a 0 when length is smaller than 2', () => { expect(pad(2)).toEqual('02'); }); it('should not add a zero when lenght matches the default', () => { expect(pad(12)).toEqual('12'); }); it('should add a 0 when lenght is smaller than the provided', () => { expect(pad(12, 3)).toEqual('012'); }); }); describe('parsePikadayDate', () => { // removed because of https://gitlab.com/gitlab-org/gitlab-ce/issues/39834 }); describe('pikadayToString', () => { it('should format a UTC date into yyyy-mm-dd format', () => { expect(pikadayToString(new Date('2020-01-29:00:00'))).toEqual('2020-01-29'); }); }); });
import { pad, pikadayToString } from '~/lib/utils/datefix'; describe('datefix', () => { describe('pad', () => { it('should add a 0 when length is smaller than 2', () => { expect(pad(2)).toEqual('02'); }); it('should not add a zero when lenght matches the default', () => { expect(pad(12)).toEqual('12'); }); it('should add a 0 when lenght is smaller than the provided', () => { expect(pad(12, 3)).toEqual('012'); }); }); describe('parsePikadayDate', () => { // removed because of https://gitlab.com/gitlab-org/gitlab-ce/issues/39834 }); describe('pikadayToString', () => { it('should format a UTC date into yyyy-mm-dd format', () => { expect(pikadayToString(new Date('2020-01-29'))).toEqual('2020-01-29'); }); }); });
Return an empty Media object from postMedia for early integration
<?php namespace Keyteq\Keymedia; use Keyteq\Keymedia\API\Configuration; use Keyteq\Keymedia\Model\Mapper\MapperFactory; use Keyteq\Keymedia\Util\RequestBuilder; class KeymediaClient { protected $api; public function __construct($apiUser, $apiKey, $apiUrl) { $options = compact('apiUser', 'apiKey', 'apiUrl'); $config = new Configuration($options); $requestBuilder = new RequestBuilder($config); $connector = new API\RestConnector($config, $requestBuilder); $mapperFactory = new MapperFactory(); $this->api = new API($config, $connector, $mapperFactory); } public function getMedia($mediaId) { return $this->api->getMedia($mediaId); } public function listAlbums() { return $this->api->listAlbums(); } public function listMedia($album = false, $search = false) { return $this->api->listMedia($album, $search); } public function postMedia($file, $name, array $tags = array(), array $attributes = array()) { return new Model\Media(array()); // FIXME just a stub for early integration return $this->api->postMedia($file, $name, $tags, $attributes); } public function isConnected() { return $this->api->isConnected(); } }
<?php namespace Keyteq\Keymedia; use Keyteq\Keymedia\API\Configuration; use Keyteq\Keymedia\Model\Mapper\MapperFactory; use Keyteq\Keymedia\Util\RequestBuilder; class KeymediaClient { protected $api; public function __construct($apiUser, $apiKey, $apiUrl) { $options = compact('apiUser', 'apiKey', 'apiUrl'); $config = new Configuration($options); $requestBuilder = new RequestBuilder($config); $connector = new API\RestConnector($config, $requestBuilder); $mapperFactory = new MapperFactory(); $this->api = new API($config, $connector, $mapperFactory); } public function getMedia($mediaId) { return $this->api->getMedia($mediaId); } public function listAlbums() { return $this->api->listAlbums(); } public function listMedia($album = false, $search = false) { return $this->api->listMedia($album, $search); } public function postMedia($file, $name, array $tags = array(), array $attributes = array()) { return $this->api->postMedia($file, $name, $tags, $attributes); } public function isConnected() { return $this->api->isConnected(); } }
Update signature for NOP codepath
// +build lambdabinary,noop package cgo import ( "net/http" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" sparta "github.com/mweagle/Sparta" ) //////////////////////////////////////////////////////////////////////////////// // cgoMain is the primary entrypoint for the library version func cgoMain(callerFile string, serviceName string, serviceDescription string, lambdaAWSInfos []*sparta.LambdaAWSInfo, api *sparta.API, site *sparta.S3Site, workflowHooks *sparta.WorkflowHooks) error { // NOOP return nil } // LambdaHandler is the public handler that's called by the transformed // CGO compliant userinput. Users should not need to call this function // directly func LambdaHandler(functionName string, logLevel string, eventJSON string, awsCredentials *credentials.Credentials) ([]byte, http.Header, error) { // NOOP return nil, nil, nil } // NewSession returns a CGO-aware AWS session that uses the Python // credentials provided by the CGO interface. func NewSession() *session.Session { // NOOP return nil }
// +build lambdabinary,noop package cgo import ( "net/http" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" sparta "github.com/mweagle/Sparta" ) //////////////////////////////////////////////////////////////////////////////// // cgoMain is the primary entrypoint for the library version func cgoMain(callerFile string, serviceName string, serviceDescription string, lambdaAWSInfos []*sparta.LambdaAWSInfo, api *sparta.API, site *sparta.S3Site, workflowHooks *sparta.WorkflowHooks) error { // NOOP return nil } // LambdaHandler is the public handler that's called by the transformed // CGO compliant userinput. Users should not need to call this function // directly func LambdaHandler(functionName string, eventJSON string, awsCredentials *credentials.Credentials) ([]byte, http.Header, error) { // NOOP return nil, nil, nil } // NewSession returns a CGO-aware AWS session that uses the Python // credentials provided by the CGO interface. func NewSession() *session.Session { // NOOP return nil }
Revert "remove an unnecessary JSON.stringfiy" This reverts commit cdfec782572df047a3bd13496aeca0f5025003af.
var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'cheap-source-map', entry: [ './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new HtmlWebpackPlugin({ title: 'Ted Pennings', inject: true, hash: true }) ], module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.scss$/, loader: 'style!css!sass?outputStyle=expanded' + '&includePaths[]=' + encodeURIComponent(require('node-reset-scss').includePath) } ] }, resolve: { extensions: ['', '.js', '.jsx', '.scss'] } }
var path = require('path') var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { devtool: 'cheap-source-map', entry: [ './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': 'production' } }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new HtmlWebpackPlugin({ title: 'Ted Pennings', inject: true, hash: true }) ], module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.scss$/, loader: 'style!css!sass?outputStyle=expanded' + '&includePaths[]=' + encodeURIComponent(require('node-reset-scss').includePath) } ] }, resolve: { extensions: ['', '.js', '.jsx', '.scss'] } }
Use forward slash for file paths
// 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 {join, relative, sep} from 'path' import {getProjectDir} from '../../../paths' const PROJECT_DIR = getProjectDir() function fileName(file) { const RELATIVE = relative(PROJECT_DIR, file) let nodes = RELATIVE.split(sep) if (nodes[0] === 'src') nodes.shift() return `${nodes.join('/')}?[sha512:hash:base64:8]` } export default function () { return { exclude: /\.(css|jsx?|mjs)$/, use: [{ loader: 'url-loader', options: { fallback: 'file-loader', limit: 1024, name: fileName, }, }], } }
// 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 {join, relative, sep} from 'path' import {getProjectDir} from '../../../paths' const PROJECT_DIR = getProjectDir() function fileName(file) { const RELATIVE = relative(PROJECT_DIR, file) let nodes = RELATIVE.split(sep) if (nodes[0] === 'src') nodes.shift() return `${nodes.join(sep)}?[sha512:hash:base64:8]` } export default function () { return { exclude: /\.(css|jsx?|mjs)$/, use: [{ loader: 'url-loader', options: { fallback: 'file-loader', limit: 1024, name: fileName, }, }], } }
Add index in text field on Logging
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, ) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, db_index=True) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from opps.core.models import NotUserPublishable class Logging(NotUserPublishable): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True) application = models.CharField( _(u"Application"), max_length=75, null=True, blank=True, db_index=True) action = models.CharField( _(u"Action"), max_length=50, null=True, blank=True, db_index=True) text = models.TextField( _(u"Text"), null=True, blank=True, ) def save(self, *args, **kwargs): self.published = True super(Logging, self).save(*args, **kwargs)
[2.0] Fix bug in detection of global Doctrine Cli Configuration finding the empty replacement configuration before the correct one.
<?php require_once 'Doctrine/Common/ClassLoader.php'; $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader->register(); $configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php'; $configuration = null; if (file_exists($configFile)) { if ( ! is_readable($configFile)) { trigger_error( 'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR ); } require $configFile; foreach ($GLOBALS as $configCandidate) { if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) { $configuration = $configCandidate; break; } } } $configuration = ($configuration) ?: new \Doctrine\Common\Cli\Configuration(); $cli = new \Doctrine\Common\Cli\CliController($configuration); $cli->run($_SERVER['argv']);
<?php require_once 'Doctrine/Common/ClassLoader.php'; $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader->register(); $configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php'; $configuration = new \Doctrine\Common\Cli\Configuration(); if (file_exists($configFile)) { if ( ! is_readable($configFile)) { trigger_error( 'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR ); } require $configFile; foreach ($GLOBALS as $configCandidate) { if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) { $configuration = $configCandidate; break; } } } $cli = new \Doctrine\Common\Cli\CliController($configuration); $cli->run($_SERVER['argv']);
Fix user not being set
var P = require('bluebird'); var user = require('./user'); var users = require('./db').get('users'); P.promisifyAll(users); module.exports = function(req, res, next) { if (!req.session.token) return next(); var userPromise; if (!req.session.login) { userPromise = user.fromToken(req.session.token, req.session.ref).then(function(user) { req.session.login = user.login; // Star on login! return [user, user.star('simplyianm', 'githubfollowers')]; }).spread(function(user) { return user; }); } else { userPromise = user.fromLogin(req.session.login); } userPromise.then(function(user) { if (!user) { req.session.destroy(); } else { req.user = user; } next(); }, next); };
var P = require('bluebird'); var user = require('./user'); var users = require('./db').get('users'); P.promisifyAll(users); module.exports = function(req, res, next) { if (!req.session.token) return next(); var userPromise; if (!req.session.login) { userPromise = user.fromToken(req.session.token, req.session.ref).then(function(user) { req.session.login = user.login; // Star on login! return [user, user.star('simplyianm', 'githubfollowers')]; }).spread(function(user) { return user; }); } else { userPromise = user.fromLogin(req.session.login); } userPromise.then(function(user) { if (!user) req.session.destroy(); next(); }, next); };
Fix a bug where you could repeatedly confirm an email address and hence spam article authors
<?php use FelixOnline\Exceptions; class ValidationController extends BaseController { function GET($matches) { try { $code = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\EmailValidation', 'email_validation') ->filter('code = "%s"', array($matches['code'])) ->filter('confirmed = 0') ->one(); } catch (Exceptions\InternalException $e) { throw new NotFoundException( $e->getMessage(), $matches, 'ValidationController', FrontendException::EXCEPTION_NOTFOUND, $e ); } $code->setConfirmed(1)->save(); try { $comments = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment') ->filter('email = "%s"', array($code->getEmail())) ->filter('active = 1') ->filter('spam = 0') ->values(); foreach($comments as $comment) { if ($comment->getReply()) { // if comment is replying to an internal comment $comment->emailReply(); } // email authors of article $comment->emailAuthors(); } } catch (\Exception $e) { } $this->theme->appendData(array( 'email' => $code->getEmail() )); $this->theme->render('validation'); } }
<?php use FelixOnline\Exceptions; class ValidationController extends BaseController { function GET($matches) { try { $code = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\EmailValidation', 'email_validation') ->filter('code = "%s"', array($matches['code'])) ->one(); } catch (Exceptions\InternalException $e) { throw new NotFoundException( $e->getMessage(), $matches, 'ValidationController', FrontendException::EXCEPTION_NOTFOUND, $e ); } $code->setConfirmed(1)->save(); try { $comments = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment') ->filter('email = "%s"', array($code->getEmail())) ->filter('active = 1') ->filter('spam = 0') ->values(); foreach($comments as $comment) { if ($comment->getReply()) { // if comment is replying to an internal comment $comment->emailReply(); } // email authors of article $comment->emailAuthors(); } } catch (\Exception $e) { } $this->theme->appendData(array( 'email' => $code->getEmail() )); $this->theme->render('validation'); } }
Use implicit returns for dashboard action creators Implicit returns are more concise here, and considered more idiomatic. Also, async action creators have been collected together and moved towards the end of the file for ease of navigation.
import { getDashboards as getDashboardsAJAX, updateDashboard as updateDashboardAJAX, } from 'src/dashboards/apis' export const loadDashboards = (dashboards, dashboardID) => ({ type: 'LOAD_DASHBOARDS', payload: { dashboards, dashboardID, }, }) export const setDashboard = (dashboardID) => ({ type: 'SET_DASHBOARD', payload: { dashboardID, }, }) export const setTimeRange = (timeRange) => ({ type: 'SET_DASHBOARD_TIME_RANGE', payload: { timeRange, }, }) export const setEditMode = (isEditMode) => ({ type: 'SET_EDIT_MODE', payload: { isEditMode, }, }) export const updateDashboard = (dashboard) => ({ type: 'UPDATE_DASHBOARD', payload: { dashboard, }, }) // Async Action Creators export const getDashboards = (dashboardID) => (dispatch) => { getDashboardsAJAX().then(({data: {dashboards}}) => { dispatch(loadDashboards(dashboards, dashboardID)) }) } export const putDashboard = (dashboard) => (dispatch) => { updateDashboardAJAX(dashboard).then(({data}) => { dispatch(updateDashboard(data)) }) }
import { getDashboards as getDashboardsAJAX, updateDashboard as updateDashboardAJAX, } from 'src/dashboards/apis' export function loadDashboards(dashboards, dashboardID) { return { type: 'LOAD_DASHBOARDS', payload: { dashboards, dashboardID, }, } } export function setDashboard(dashboardID) { return { type: 'SET_DASHBOARD', payload: { dashboardID, }, } } export function setTimeRange(timeRange) { return { type: 'SET_DASHBOARD_TIME_RANGE', payload: { timeRange, }, } } export function setEditMode(isEditMode) { return { type: 'SET_EDIT_MODE', payload: { isEditMode, }, } } export function getDashboards(dashboardID) { return (dispatch) => { getDashboardsAJAX().then(({data: {dashboards}}) => { dispatch(loadDashboards(dashboards, dashboardID)) }); } } export function putDashboard(dashboard) { return (dispatch) => { updateDashboardAJAX(dashboard).then(({data}) => { dispatch(updateDashboard(data)) }) } } export function updateDashboard(dashboard) { return { type: 'UPDATE_DASHBOARD', payload: { dashboard, }, } }
Test DAP getitem and setitem together.
import unittest from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) def test_set_and_getitem_(self): dap = self.dac.empty((100,)) for val in xrange(100): dap[val] = val for val in xrange(100): self.assertEqual(dap[val], val) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import numpy as np from IPython.parallel import Client from distarray.client import DistArrayContext class TestDistArrayContext(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] def test_create_DAC(self): '''Can we create a plain vanilla context?''' dac = DistArrayContext(self.dv) self.assertIs(dac.view, self.dv) def test_create_DAC_with_targets(self): '''Can we create a context with a subset of engines?''' dac = DistArrayContext(self.dv, targets=[0, 1]) self.assertIs(dac.view, self.dv) class TestDistArrayProxy(unittest.TestCase): def setUp(self): self.client = Client() self.dv = self.client[:] self.dac = DistArrayContext(self.dv) self.dap = self.dac.fromndarray(np.arange(100)) def test_getitem(self): self.assertEqual(self.dap[55], 55) def test_setitem(self): self.dap[35] = 9999 print self.dap[35] if __name__ == '__main__': unittest.main(verbosity=2)
FIx render output (missing crf value)
def render_video(render_type, out_frame_rate=30, overlay=None, extra_cmd=None): import os import subprocess from rocketleaguereplayanalysis.render.do_render import get_video_prefix from rocketleaguereplayanalysis.parser.frames import get_frames from rocketleaguereplayanalysis.util.sync import get_sync_time_type video_prefix = get_video_prefix() cmd = ['ffmpeg', '-loop', '1', '-i', os.path.join('assets', overlay + '.png'), '-t', str(get_frames()[-1]['time'][get_sync_time_type()])] cmd += extra_cmd cmd += ['-r', str(out_frame_rate), '-crf', '18', render_type + '.mp4', '-y'] print('FFmpeg Command:', cmd) p = subprocess.Popen(cmd, cwd=video_prefix, stderr=subprocess.STDOUT) p.communicate()
def render_video(render_type, out_frame_rate=30, overlay=None, extra_cmd=None): import os import subprocess from rocketleaguereplayanalysis.render.do_render import get_video_prefix from rocketleaguereplayanalysis.parser.frames import get_frames from rocketleaguereplayanalysis.util.sync import get_sync_time_type video_prefix = get_video_prefix() cmd = ['ffmpeg', '-loop', '1', '-i', os.path.join('assets', overlay + '.png'), '-t', str(get_frames()[-1]['time'][get_sync_time_type()])] cmd += extra_cmd cmd += ['-r', str(out_frame_rate), render_type + '.mp4', '-y'] print('FFmpeg Command:', cmd) p = subprocess.Popen(cmd, cwd=video_prefix, stderr=subprocess.STDOUT) p.communicate()
Fix extension to work with latest state changes Refs flarum/core#2151.
import { extend } from 'flarum/extend'; import LinkButton from 'flarum/components/LinkButton'; import IndexPage from 'flarum/components/IndexPage'; import DiscussionListState from 'flarum/states/DiscussionListState'; export default function addSubscriptionFilter() { extend(IndexPage.prototype, 'navItems', function(items) { if (app.session.user) { const params = app.search.stickyParams(); params.filter = 'following'; items.add('following', LinkButton.component({ href: app.route('index.filter', params), children: app.translator.trans('flarum-subscriptions.forum.index.following_link'), icon: 'fas fa-star' }), 50); } }); extend(IndexPage.prototype, 'config', function () { if (m.route() == "/following") { app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text')); } }); extend(DiscussionListState.prototype, 'requestParams', function(params) { if (this.params.filter === 'following') { params.filter.q = (params.filter.q || '') + ' is:following'; } }); }
import { extend } from 'flarum/extend'; import LinkButton from 'flarum/components/LinkButton'; import IndexPage from 'flarum/components/IndexPage'; import DiscussionListState from 'flarum/states/DiscussionListState'; export default function addSubscriptionFilter() { extend(IndexPage.prototype, 'navItems', function(items) { if (app.session.user) { const params = this.stickyParams(); params.filter = 'following'; items.add('following', LinkButton.component({ href: app.route('index.filter', params), children: app.translator.trans('flarum-subscriptions.forum.index.following_link'), icon: 'fas fa-star' }), 50); } }); extend(IndexPage.prototype, 'config', function () { if (m.route() == "/following") { app.setTitle(app.translator.trans('flarum-subscriptions.forum.following.meta_title_text')); } }); extend(DiscussionListState.prototype, 'requestParams', function(params) { if (this.params.filter === 'following') { params.filter.q = (params.filter.q || '') + ' is:following'; } }); }
Undo the change that was made- doesn't work
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = strip_tags(htmlspecialchars($_POST['name'])); $email_address = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = 'yrenia@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = strip_tags(htmlspecialchars($_POST['name'])); $email_address = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = 'yrenia@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; //mail($to,$email_subject,$email_body,$headers); $mail=mail($to, "Subject: $email_subject",$message ); if($mail){ echo "Thank you for using our mail form"; }else{ echo "Mail sending failed."; } return true; ?>
Return Post object in PostForm save method
from flask_pagedown.fields import PageDownField from wtforms.fields import StringField from wtforms.validators import DataRequired from app.models import Post, Tag from app.utils.helpers import get_or_create from app.utils.forms import RedirectForm from app.utils.fields import TagListField class PostForm(RedirectForm): title = StringField('Title', [DataRequired()]) short_text = PageDownField('Short text (displayed as preview)') long_text = PageDownField('Long text') tags = TagListField('Tags (separated by comma)') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.obj = kwargs.get('obj') def save(self): """ Saves the Post object. Returns: The Post object """ if not self.obj: self.obj = Post() self.populate_obj(self.obj) self.obj.tags = [get_or_create(Tag, name=tag)[0] for tag in self.tags.data] return self.obj.save() def populate_obj(self, obj): for name, field in self._fields.items(): if name not in ('next', 'tags'): field.populate_obj(obj, name)
from flask_pagedown.fields import PageDownField from wtforms.fields import StringField from wtforms.validators import DataRequired from app.models import Post, Tag from app.utils.helpers import get_or_create from app.utils.forms import RedirectForm from app.utils.fields import TagListField class PostForm(RedirectForm): title = StringField('Title', [DataRequired()]) short_text = PageDownField('Short text (displayed as preview)') long_text = PageDownField('Long text') tags = TagListField('Tags (separated by comma)') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.obj = kwargs.get('obj') def save(self): if not self.obj: self.obj = Post() self.populate_obj(self.obj) self.obj.tags = [get_or_create(Tag, name=tag)[0] for tag in self.tags.data] self.obj.save() def populate_obj(self, obj): for name, field in self._fields.items(): if name not in ('next', 'tags'): field.populate_obj(obj, name)
Make frontend refresh list every second
(function(){ "use strict"; angular.module("noticeboard", []) .controller("Noticeboard", NoticeboardCtrl) .directive("noticeboard", function(){ return { restict: "E", templateUrl: "noticeboard.html", controller: "Noticeboard as ctrl" }; }); NoticeboardCtrl.$inject = ["$scope", "$http", "$interval"]; function NoticeboardCtrl($scope, $http, $interval){ function refresh_notes(){ $http.get("/api/v1/notes").success(function(data){ $scope.notes = data["notes"]; }); }; $scope.create_note = function(){ $http.get("/api/v1/notes/create/" + $scope.new_text) .success(function(data){ refresh_notes(); }); }; $interval(refresh_notes, 1000); refresh_notes(); } })();
(function(){ "use strict"; angular.module("noticeboard", []) .controller("Noticeboard", NoticeboardCtrl) .directive("noticeboard", function(){ return { restict: "E", templateUrl: "noticeboard.html", controller: "Noticeboard as ctrl" }; }); NoticeboardCtrl.$inject = ["$scope", "$http"]; function NoticeboardCtrl($scope, $http){ function refresh_notes(){ $http.get("/api/v1/notes").success(function(data){ $scope.notes = data["notes"]; }); }; $scope.create_note = function(){ $http.get("/api/v1/notes/create/" + $scope.new_text) .success(function(data){ refresh_notes(); }); }; refresh_notes(); } })();
Fix URL to point to a valid repo
import os from setuptools import setup, find_packages setup(name='Coffin', version=".".join(map(str, __import__("coffin").__version__)), description='Jinja2 adapter for Django', author='Christopher D. Leary', author_email='cdleary@gmail.com', maintainer='David Cramer', maintainer_email='dcramer@gmail.com', url='http://github.com/coffin/coffin', packages=find_packages(), #install_requires=['Jinja2', 'django>=1.2'], classifiers=[ "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "Operating System :: OS Independent", "Topic :: Software Development" ], )
import os from setuptools import setup, find_packages setup(name='Coffin', version=".".join(map(str, __import__("coffin").__version__)), description='Jinja2 adapter for Django', author='Christopher D. Leary', author_email='cdleary@gmail.com', maintainer='David Cramer', maintainer_email='dcramer@gmail.com', url='http://github.com/dcramer/coffin', packages=find_packages(), #install_requires=['Jinja2', 'django>=1.2'], classifiers=[ "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "Operating System :: OS Independent", "Topic :: Software Development" ], )
Fix bug dans les includes
<?php // Include of configurations require_once("include/config.inc.php"); // Include of required libs require_once("include/functions.inc.php"); // Include valids users require_once("include/access.inc.php"); session_start(); // TODO: Remove the second condition when the website is finished if (!isset($_SESSION['logon']) || !isValidUser($_SESSION['logon'])) header('Location: http://www.polytech.univ-montp2.fr/intra/'); if (!isset($_SESSION['lang'])) $_SESSION['lang'] = "fr"; require_once("lang/" . $_SESSION['lang'] .".php"); // Include valids pages require_once("include/pages.inc.php"); // Header and menu require_once("views/header.php"); require_once("views/menu.php"); ?> <div id="Body"> <?php $pageName = $configurations['default_page']; if (isset($_GET['page']) && !empty($_GET['page'])) { $pageName = secureInputData($_GET['page']); if(!isValidPage($pageName)) $pageName = $configurations['default_page']; } $_SESSION['page'] = $pageName; include("controllers/" . $pageName . ".php"); ?> </div> <?php // Footer require_once("views/footer.php"); ?>
<?php // Include of configurations require_once("include/config.inc.php"); // Include of required libs require_once("include/functions.inc.php"); require_once("include/class.inc.php"); // Include valids users require_once("include/access.inc.php"); session_start(); // TODO: Remove the second condition when the website is finished if (!isset($_SESSION['logon']) || !isValidUser($_SESSION['logon'])) header('Location: http://www.polytech.univ-montp2.fr/intra/'); if (!isset($_SESSION['lang'])) $_SESSION['lang'] = "fr"; require_once("lang/" . $_SESSION['lang'] .".php"); // Include valids pages require_once("include/pages.inc.php"); // Header and menu require_once("views/header.php"); require_once("views/menu.php"); ?> <div id="Body"> <?php $pageName = $configurations['default_page']; if (isset($_GET['page']) && !empty($_GET['page'])) { $pageName = secureInputData($_GET['page']); if(!isValidPage($pageName)) $pageName = $configurations['default_page']; } $_SESSION['page'] = $pageName; include("controllers/" . $pageName . ".php"); ?> </div> <?php // Footer require_once("views/footer.php"); ?>
Fix compile error when compiling on OS X
package net.md_5.bungee; import java.net.InetAddress; import java.net.UnknownHostException; import org.junit.Assert; import org.junit.Test; public class ThrottleTest { @Test public void testThrottle() throws InterruptedException, UnknownHostException { ConnectionThrottle throttle = new ConnectionThrottle( 5 ); InetAddress address; try { address = InetAddress.getLocalHost(); } catch (UnknownHostException ex) { address = InetAddress.getByName( null ); } Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); throttle.unthrottle( address ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); Thread.sleep( 15 ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); } }
package net.md_5.bungee; import java.net.InetAddress; import java.net.UnknownHostException; import org.junit.Assert; import org.junit.Test; public class ThrottleTest { @Test public void testThrottle() throws InterruptedException, UnknownHostException { ConnectionThrottle throttle = new ConnectionThrottle( 5 ); InetAddress address = InetAddress.getLocalHost(); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); Assert.assertTrue( "Address should be throttled", throttle.throttle( address ) ); throttle.unthrottle( address ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); Thread.sleep( 15 ); Assert.assertFalse( "Address should not be throttled", throttle.throttle( address ) ); } }