text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Create sample using new process create method.
(function (module) { module.controller("SamplesController", SamplesController); SamplesController.$inject = ["$state", "project", "$filter", "samples"]; function SamplesController($state, project, $filter, samples) { var ctrl = this; ctrl.project = project; ctrl.viewSample = viewSample; ctrl.samples = samples; ctrl.createSample = createSample; if (ctrl.samples.length !== 0) { var sortedSamples = $filter('orderBy')(ctrl.samples, 'name'); ctrl.current = sortedSamples[0]; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } ////////////////// function viewSample(sample) { ctrl.current = sample; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } function createSample() { $state.go('projects.project.processes.create', {process: 'As Received', process_id: ''}); } } }(angular.module('materialscommons')));
(function (module) { module.controller("SamplesController", SamplesController); SamplesController.$inject = ["$state", "project", "$filter", "samples", "processTemplates"]; function SamplesController($state, project, $filter, samples, processTemplates) { var ctrl = this; ctrl.project = project; ctrl.viewSample = viewSample; ctrl.samples = samples; ctrl.createSample = createSample; if (ctrl.samples.length !== 0) { var sortedSamples = $filter('orderBy')(ctrl.samples, 'name'); ctrl.current = sortedSamples[0]; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } ////////////////// function viewSample(sample) { ctrl.current = sample; $state.go('projects.project.samples.list.edit', {sample_id: ctrl.current.id}); } function createSample() { var template = processTemplates.getTemplateByName('As Received'); processTemplates.setActiveTemplate(template); $state.go('projects.project.processes.create'); } } }(angular.module('materialscommons')));
Refactor adding question to conversation This will make adding different types of questions easier.
const handleJoin = (bot, message) => bot.reply(message, 'This trusty survey bot is here to help.') const addTextQuestion = (convo, question, surveyId, recordAnswer) => { convo.addQuestion(question.text, (response, convo) => { recordAnswer(surveyId, question.id, response.text) convo.next() }) } const doSurvey = (bot, { roomId, personEmail, survey, recordAnswer }) => { bot.startConversation({ user: personEmail, channel: roomId }, (err, convo) => { for (const question of survey.data.questions) { let addQuestionFn = addTextQuestion switch(question.type) { case 'text': addQuestionFn = addTextQuestion break; } addQuestionFn(convo, question, survey.id, recordAnswer) } convo.addMessage('Thanks for your responses!') // convo.on('end', (convo) => { // //TODO: record survey completed // }) }) } export default { doSurvey, handleJoin }
const handleJoin = (bot, message) => bot.reply(message, 'This trusty survey bot is here to help.') const doSurvey = (bot, { roomId, personEmail, survey, recordAnswer }) => { console.log('starting survey', survey) bot.startConversation({ user: personEmail, channel: roomId }, (err, convo) => { for (const question of survey.data.questions) { if (question.type === 'text') { convo.addQuestion(question.text, (response, convo) => { recordAnswer(survey.id, question.id, response.text) convo.next() }) } } convo.addMessage('Thanks for your responses!') // convo.on('end', (convo) => { // //TODO: record survey completed // }) }) } export default { doSurvey, handleJoin }
Remove extra line in the end of file
'use babel'; import filesizeView from '../lib/filesize-view'; describe('View', () => { // Disable tooltip, only enable on tests when needed atom.config.set('filesize.EnablePopupAppearance', false); const workspaceView = atom.views.getView(atom.workspace); const view = filesizeView(workspaceView); describe('when refreshing the view', () => { it('should display the human readable size', () => { workspaceView.appendChild(view.container); const filesizeElement = workspaceView.querySelector('.current-size'); view.refresh({ size: 5 }); expect(filesizeElement.innerHTML).toEqual('5 bytes'); }); it('should react to config changes', () => { atom.config.set('filesize.UseDecimal', true); const filesizeElement = workspaceView.querySelector('.current-size'); view.refresh({ size: 1024 }); expect(filesizeElement.innerHTML).toEqual('1.02 kB'); }); }); describe('when cleaning the view', () => { it('should wipe the filesize contents', () => { view.clean(); const filesizeElement = workspaceView.querySelector('.current-size'); expect(filesizeElement.innerHTML).toEqual(''); }); }); describe('when destroying the view', () => { it('should remove the file-size element', () => { view.destroy(); const filesizeElement = workspaceView.querySelector('.file-size'); expect(filesizeElement).toEqual(null); }); }); });
'use babel'; import filesizeView from '../lib/filesize-view'; describe('View', () => { // Disable tooltip, only enable on tests when needed atom.config.set('filesize.EnablePopupAppearance', false); const workspaceView = atom.views.getView(atom.workspace); const view = filesizeView(workspaceView); describe('when refreshing the view', () => { it('should display the human readable size', () => { workspaceView.appendChild(view.container); const filesizeElement = workspaceView.querySelector('.current-size'); view.refresh({ size: 5 }); expect(filesizeElement.innerHTML).toEqual('5 bytes'); }); it('should react to config changes', () => { atom.config.set('filesize.UseDecimal', true); const filesizeElement = workspaceView.querySelector('.current-size'); view.refresh({ size: 1024 }); expect(filesizeElement.innerHTML).toEqual('1.02 kB'); }); }); describe('when cleaning the view', () => { it('should wipe the filesize contents', () => { view.clean(); const filesizeElement = workspaceView.querySelector('.current-size'); expect(filesizeElement.innerHTML).toEqual(''); }); }); describe('when destroying the view', () => { it('should remove the file-size element', () => { view.destroy(); const filesizeElement = workspaceView.querySelector('.file-size'); expect(filesizeElement).toEqual(null); }); }); });
Trim before testing for equality on unit tests.
var FILE = require("file"); var ASSERT = require("assert"); var Haml = require("../lib/haml"); FILE.glob("test/*.haml").forEach(function(hamlFile) { exports["test " + hamlFile] = function() { var scopeFile = hamlFile.replace(/haml$/, "js"); var htmlFile = hamlFile.replace(/haml$/, "html"); var haml = FILE.read(hamlFile); var expected = FILE.read(htmlFile); var scope = FILE.exists(scopeFile) ? eval("("+FILE.read(scopeFile)+")") : {}; var js = Haml.compile(haml); var js_opt = Haml.optimize(js); var actual = Haml.execute(js_opt, scope.context, scope.locals); ASSERT.equal(actual.trim(), expected.trim()); } }); if (module == require.main) require("os").exit(require("test").run(exports));
var FILE = require("file"); var ASSERT = require("assert"); var Haml = require("../lib/haml"); FILE.glob("test/*.haml").forEach(function(hamlFile) { exports["test " + hamlFile] = function() { var scopeFile = hamlFile.replace(/haml$/, "js"); var htmlFile = hamlFile.replace(/haml$/, "html"); var haml = FILE.read(hamlFile); var expected = FILE.read(htmlFile); var scope = FILE.exists(scopeFile) ? eval("("+FILE.read(scopeFile)+")") : {}; var js = Haml.compile(haml); var js_opt = Haml.optimize(js); var actual = Haml.execute(js_opt, scope.context, scope.locals); ASSERT.equal(actual, expected); } }); if (module == require.main) require("os").exit(require("test").run(exports));
Read only 4100 first bytes from response stream
const path = require('path') const fileType = require('file-type') const contentType = require('content-type') const mime = require('mime-types') async function parseType(token, options) { if (token.parsed) return false // First, we read a chunk and try to infer the type with it const chunk = await new Promise((resolve, reject) => { const handle = setTimeout( () => reject(new Error('Timeout when trying to get first chunk')), options.fetchTimeout ) token.response.body.once('data', firstChunk => { token.response.body.pause() clearTimeout(handle) token.response.body.unshift(firstChunk) resolve(firstChunk) }).read(4100) token.response.body.resume() }) const type = fileType(chunk) if (type) { token.fileType = type return } // Then, we try to extract the extension from the filename if (token.fileName) { const ext = path.extname(token.fileName).substring(1) token.fileType = { ext, mime: mime.lookup(ext) } return } // Finally, we retrieve the type from the content-type header const ct = contentType.parse(token.response) if (ct) { token.fileType = { ext: mime.extension(ct.type), mime: ct.type } } } module.exports = parseType
const path = require('path') const fileType = require('file-type') const contentType = require('content-type') const mime = require('mime-types') async function parseType(token, options) { if (token.parsed) return false // First, we read a chunk and try to infer the type with it const chunk = await new Promise((resolve, reject) => { const handle = setTimeout( () => reject(new Error('Timeout when trying to get first chunk')), options.fetchTimeout ) token.response.body.once('data', firstChunk => { token.response.body.pause() clearTimeout(handle) token.response.body.unshift(firstChunk) resolve(firstChunk) }).resume() }) const type = fileType(chunk) if (type) { token.fileType = type return } // Then, we try to extract the extension from the filename if (token.fileName) { const ext = path.extname(token.fileName).substring(1) token.fileType = { ext, mime: mime.lookup(ext) } return } // Finally, we retrieve the type from the content-type header const ct = contentType.parse(token.response) if (ct) { token.fileType = { ext: mime.extension(ct.type), mime: ct.type } } } module.exports = parseType
Change error handling to catch method.
var mongodb = require('mongodb'); var nodefn = require('when/node'); var util = require('util'); // ### Errors ### function MongoConnectionError(error) { this.name = 'MongoConnectionError'; this.message = error; } util.inherits(MongoConnectionError, Error); function MongoAdapter() { this._connectURI = 'mongodb://0.0.0.0:27017/'; this._databaseName = 'testowa'; this.collections = { 'users': undefined }; } MongoAdapter.prototype.connect = function () { var self = this; return function (req, res, next) { var MongoClient = mongodb.MongoClient; var promisedConnect = nodefn.call(MongoClient.connect, self._connectURI + self._databaseName); return promisedConnect.then(function (db) { for (var collection in self.collections) { self.collections[collection] = db.collection(collection); } next(); }).catch(function (error) { throw new MongoConnectionError(error); }); }; }; module.exports.MongoAdapter = MongoAdapter;
var mongodb = require('mongodb'); var nodefn = require('when/node'); var util = require('util'); // ### Errors ### function MongoConnectionError(error) { this.name = 'MongoConnectionError'; this.message = error; } util.inherits(MongoConnectionError, Error); function MongoAdapter() { this._connectURI = 'mongodb://0.0.0.0:27017/'; this._databaseName = 'testowa'; this.collections = { 'users': undefined }; } MongoAdapter.prototype.connect = function () { var self = this; return function (req, res, next) { var MongoClient = mongodb.MongoClient; var promisedConnect = nodefn.call(MongoClient.connect, self._connectURI + self._databaseName); promisedConnect.done(function (db) { for (var collection in self.collections) { self.collections[collection] = db.collection(collection); } next(); }, function (error) { throw new MongoConnectionError(error); }); }; }; module.exports.MongoAdapter = MongoAdapter;
Add note about which chars are used to generate room code
import Room from './room.js'; class RoomManager { constructor() { this.roomsById = {}; } getRoom(roomCode) { return this.roomsById[roomCode]; } openRoom() { let roomCode = this.obtainRoomCode(); let room = new Room({ players: [], code: roomCode }); this.roomsById[roomCode] = room; return room; } closeRoom({ roomCode }) { delete this.roomsById[roomCode]; } obtainRoomCode() { let roomCode; do { roomCode = this.generateRandomRoomCode(); } while (this.roomsById[roomCode]); return roomCode; } generateRandomRoomCode() { let roomCode = ''; // Uppercase letters A-Z let startIndex = 65; let endIndex = 90; for (var i = 0; i < RoomManager.roomCodeLength; i += 1) { roomCode += String.fromCharCode(Math.floor(startIndex + ((endIndex - startIndex + 1) * Math.random()))); } return roomCode; } } // The number of characters is a given room code RoomManager.roomCodeLength = 4; export default RoomManager;
import Room from './room.js'; class RoomManager { constructor() { this.roomsById = {}; } getRoom(roomCode) { return this.roomsById[roomCode]; } openRoom() { let roomCode = this.obtainRoomCode(); let room = new Room({ players: [], code: roomCode }); this.roomsById[roomCode] = room; return room; } closeRoom({ roomCode }) { delete this.roomsById[roomCode]; } obtainRoomCode() { let roomCode; do { roomCode = this.generateRandomRoomCode(); } while (this.roomsById[roomCode]); return roomCode; } generateRandomRoomCode() { let roomCode = ''; let startIndex = 65; let endIndex = 90; for (var i = 0; i < RoomManager.roomCodeLength; i += 1) { roomCode += String.fromCharCode(Math.floor(startIndex + ((endIndex - startIndex + 1) * Math.random()))); } return roomCode; } } // The number of characters is a given room code RoomManager.roomCodeLength = 4; export default RoomManager;
Ch23: Enable sorting of number of Post tags.
from django.contrib import admin from django.db.models import Count from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.annotate( tag_number=Count('tags')) def tag_count(self, post): return post.tag_number tag_count.short_description = 'Number of Tags' tag_count.admin_order_field = 'tag_number'
from django.contrib import admin from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): # list view date_hierarchy = 'pub_date' list_display = ( 'title', 'pub_date', 'tag_count') list_filter = ('pub_date',) search_fields = ('title', 'text') # form view fieldsets = ( (None, { 'fields': ( 'title', 'slug', 'author', 'text', )}), ('Related', { 'fields': ( 'tags', 'startups')}), ) filter_horizontal = ('tags', 'startups',) prepopulated_fields = {"slug": ("title",)} def tag_count(self, post): return post.tags.count() tag_count.short_description = 'Number of Tags'
Replace "lambda blob: blob" with "bool". This is legitimate (and even an improvement) since the function is passed to filter, which will use its return value in a boolean context anyway. This also cleans up a lint warning.
# Copyright 2013 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mapreduce to insert dummy data for GCI student data for safe-harboring.""" from google.appengine.ext import blobstore from google.appengine.ext import db from mapreduce import context from mapreduce import operation from soc.modules.gci.logic import profile as profile_logic def process(student_info): ctx = context.get() params = ctx.mapreduce_spec.mapper.params program_key_str = params['program_key'] program_key = db.Key.from_path('GCIProgram', program_key_str) # We can skip the student info entity not belonging to the given program. if student_info.program.key() != program_key: return entities, blobs = profile_logic.insertDummyData(student_info) blobstore.delete(filter(bool, blobs)) for entity in entities: yield operation.db.Put(entity) yield operation.counters.Increment("profile dummy data inserted")
# Copyright 2013 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mapreduce to insert dummy data for GCI student data for safe-harboring.""" from google.appengine.ext import blobstore from google.appengine.ext import db from mapreduce import context from mapreduce import operation from soc.modules.gci.logic import profile as profile_logic def process(student_info): ctx = context.get() params = ctx.mapreduce_spec.mapper.params program_key_str = params['program_key'] program_key = db.Key.from_path('GCIProgram', program_key_str) # We can skip the student info entity not belonging to the given program. if student_info.program.key() != program_key: return entities, blobs = profile_logic.insertDummyData(student_info) blobstore.delete(filter(lambda blob: blob, blobs)) for entity in entities: yield operation.db.Put(entity) yield operation.counters.Increment("profile dummy data inserted")
Make use of StateChanged signal of DBUS Server object git-svn-id: ff687e355030673c307e7da231f59639d58f56d5@172 941a03a8-eaeb-0310-b9a0-b1bbd8fe43fe
#!/usr/bin/python2.4 import dbus import dbus.glib import gtk from time import sleep bus = dbus.SystemBus() server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server') def server_state_changed_callback(t): print "Server::StateChanged: ", t server.connect_to_signal("StateChanged", server_state_changed_callback) print "Host name: %s" % server.GetHostName() print "Domain name: %s" % server.GetDomainName() print "FQDN: %s" % server.GetHostNameFqdn() g = dbus.Interface(bus.get_object("org.freedesktop.Avahi", server.EntryGroupNew()), 'org.freedesktop.Avahi.EntryGroup') def entry_group_state_changed_callback(t): print "EntryGroup::StateChanged: ", t g.connect_to_signal('StateChanged', entry_group_state_changed_callback) g.AddService(0, 0, "_http._tcp", "foo", "", "", dbus.UInt16(4712), ["fuck=hallo", "gurke=mega"]) g.AddAddress(0, 0, "foo.local", "47.11.8.15") g.Commit() try: gtk.main() except KeyboardInterrupt, k: pass g.Free() print "Quit"
#!/usr/bin/python2.4 import dbus import dbus.glib import gtk from time import sleep bus = dbus.SystemBus() server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server') print "Host name: %s" % server.GetHostName() print "Domain name: %s" % server.GetDomainName() print "FQDN: %s" % server.GetHostNameFqdn() g = dbus.Interface(bus.get_object("org.freedesktop.Avahi", server.EntryGroupNew()), 'org.freedesktop.Avahi.EntryGroup') def state_changed_callback(t): print "StateChanged: ", t g.connect_to_signal('StateChanged', state_changed_callback) g.AddService(0, 0, "_http._tcp", "foo", "", "", dbus.UInt16(4712), ["fuck=hallo", "gurke=mega"]) g.AddAddress(0, 0, "foo.local", "47.11.8.15") g.Commit() try: gtk.main() except KeyboardInterrupt, k: pass g.Free() print "Quit"
Use constants dictionary in lenCpStruct()
#!/usr/bin/python import argparse import os import struct import sys CP_STRUCT_SIZES = { 0xa:3 } ############### ### CLASSES ### ############### class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ################### ### SUBROUTINES ### ################### def lenCpStruct(tag): if tag in CP_STRUCT_SIZES: return CP_STRUCT_SIZES[tag] else: return -1 ############ ### MAIN ### ############ parser = MyParser('Run bytecode in jjvm') parser.add_argument('path', help='path to class') args = parser.parse_args() with open(args.path, "rb") as c: c.seek(8) cpCount = struct.unpack(">H", c.read(2))[0] - 1 print "Constant pool count: %d" % cpCount; while cpCount >= 0: cpTag = ord(c.read(1)) print "Got tag: %d" % cpTag cpStructSize = lenCpStruct(cpTag) if cpStructSize < 0: print "ERROR: cpStructSize %d for tag %d" % (cpStructSize, cpTag) sys.exit(1) print "Size: %d" % cpStructSize cpCount -= 1 c.seek(cpStructSize, os.SEEK_CUR)
#!/usr/bin/python import argparse import os import struct import sys ############### ### CLASSES ### ############### class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ################### ### SUBROUTINES ### ################### def lenCpStruct(tag): if tag == 0xa: return 3 else: return -1 ############ ### MAIN ### ############ parser = MyParser('Run bytecode in jjvm') parser.add_argument('path', help='path to class') args = parser.parse_args() with open(args.path, "rb") as c: c.seek(8) cpCount = struct.unpack(">H", c.read(2))[0] - 1 print "Constant pool count: %d" % cpCount; while cpCount >= 0: cpTag = ord(c.read(1)) print "Got tag: %d" % cpTag cpStructSize = lenCpStruct(cpTag) if cpStructSize < 0: print "ERROR: cpStructSize %d for tag %d" % (cpStructSize, cpTag) sys.exit(1) print "Size: %d" % cpStructSize cpCount -= 1 c.seek(cpStructSize, os.SEEK_CUR)
Fix Phinx configuration loading settings.
<?php /** * Phinx Configuration * @author John Kloor <kloor@bgsu.edu> * @copyright 2016 Bowling Green State University Libraries * @license MIT * @package Shortener */ use \Aura\Sql\ExtendedPdoInterface; // Load settings from the application $settings = require 'app/settings.php'; // Return Phinx Configuration. return [ 'paths' => [ 'migrations' => '%%PHINX_CONFIG_DIR%%/migrations' ], 'environments' => [ 'default_migration_table' => $settings['db']['prefix'] . 'phinx', 'default_database' => 'default', 'default' => [ 'name' => $settings['db']['name'], 'connection' => new \Pdo( $settings['db']['dsn'], $settings['db']['username'], $settings['db']['password'] ) ] ] ];
<?php /** * Phinx Configuration * @author John Kloor <kloor@bgsu.edu> * @copyright 2016 Bowling Green State University Libraries * @license MIT * @package Shortener */ use \Aura\Sql\ExtendedPdoInterface; // Load settings from the container. $container = require 'app/container.php'; // Return Phinx Configuration. return [ 'paths' => [ 'migrations' => '%%PHINX_CONFIG_DIR%%/migrations' ], 'environments' => [ 'default_migration_table' => $container['settings']['db']['prefix'] . 'phinx', 'default_database' => 'default', 'default' => [ 'name' => $container['settings']['db']['name'], 'connection' => $container[ExtendedPdoInterface::class] ] ] ];
Call the right register classes now
package info.u_team.u_team_core; import org.apache.logging.log4j.*; import info.u_team.u_team_core.intern.config.ClientConfig; import info.u_team.u_team_core.intern.init.*; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.*; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig.Type; @Mod(UCoreMod.MODID) public class UCoreMod { public static final String MODID = "uteamcore"; public static final Logger LOGGER = LogManager.getLogger("UTeamCore"); public UCoreMod() { JarSignVerifier.checkSigned(MODID); ModLoadingContext.get().registerConfig(Type.CLIENT, ClientConfig.CONFIG); UCoreCommonBusRegister.register(); DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> UCoreClientBusRegister::register); } }
package info.u_team.u_team_core; import org.apache.logging.log4j.*; import info.u_team.u_team_core.intern.config.ClientConfig; import info.u_team.u_team_core.intern.init.*; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.*; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig.Type; @Mod(UCoreMod.MODID) public class UCoreMod { public static final String MODID = "uteamcore"; public static final Logger LOGGER = LogManager.getLogger("UTeamCore"); public UCoreMod() { JarSignVerifier.checkSigned(MODID); ModLoadingContext.get().registerConfig(Type.CLIENT, ClientConfig.CONFIG); UCoreCommonBusRegister.register(); DistExecutor.safeRunWhenOn(Dist.CLIENT, () -> UCoreClientBusRegister::register); } }
Add omitted method - negate()
package net.folab.fo.runtime._fo._lang; import net.folab.fo.runtime._fo._lang._Boolean.negate; import net.folab.fo.runtime.Evaluable; import net.folab.fo.runtime.Value; import net.folab.fo.runtime._fo._lang._Boolean.choose; public class Boolean extends Value<Boolean> { public static final Boolean FALSE = new Boolean(false); public static final Boolean TRUE = new Boolean(true); private final boolean value; public final <T extends Evaluable<T>> choose<T> choose() { return new choose<T>(this); } public final negate negate = new negate(this); public negate negate() { return negate; } private Boolean(boolean value) { this.value = value; } public boolean getValue() { return value; } @Override public String toString() { return String.valueOf(value); } }
package net.folab.fo.runtime._fo._lang; import net.folab.fo.runtime._fo._lang._Boolean.negate; import net.folab.fo.runtime.Evaluable; import net.folab.fo.runtime.Value; import net.folab.fo.runtime._fo._lang._Boolean.choose; public class Boolean extends Value<Boolean> { public static final Boolean FALSE = new Boolean(false); public static final Boolean TRUE = new Boolean(true); private final boolean value; public final <T extends Evaluable<T>> choose<T> choose() { return new choose<T>(this); } public final negate negate = new negate(this); private Boolean(boolean value) { this.value = value; } public boolean getValue() { return value; } @Override public String toString() { return String.valueOf(value); } }
Fix incorrect holiday color in popover (full/half days)
import React from 'react'; import moment from 'moment'; import { Label } from 'react-bootstrap'; import { getDevHolidaysAfter } from './working-days-utils'; export default class DeveloperHolidayRow extends React.Component { prettyDate(date) { return moment(date).format('DD/MM/YYYY'); } render() { const { run, developer } = this.props; const developerHolidays = getDevHolidaysAfter(run.devHolidays, developer, run.version.startDate); return ( <tr key={developer._id}> <td>{`${developer.firstname} ${developer.lastname}`}</td> <td>{developerHolidays.map(holiday => ( <Label bsStyle={holiday.halfDay ? 'default' : 'info'} className="developer-holiday" key={holiday.date}> {this.prettyDate(holiday.date)} </Label> ))}</td> </tr> ); } } DeveloperHolidayRow.propTypes = { run: React.PropTypes.object, developer: React.PropTypes.object, };
import React from 'react'; import moment from 'moment'; import { Label } from 'react-bootstrap'; import { getDevHolidaysAfter } from './working-days-utils'; export default class DeveloperHolidayRow extends React.Component { prettyDate(date) { return moment(date).format('DD/MM/YYYY'); } render() { const { run, developer } = this.props; const developerHolidays = getDevHolidaysAfter(run.devHolidays, developer, run.version.startDate); return ( <tr key={developer._id}> <td>{`${developer.firstname} ${developer.lastname}`}</td> <td>{developerHolidays.map(holiday => ( <Label bsStyle={holiday.halfDay ? 'info' : 'default'} className="developer-holiday" key={holiday.date}> {this.prettyDate(holiday.date)} </Label> ))}</td> </tr> ); } } DeveloperHolidayRow.propTypes = { run: React.PropTypes.object, developer: React.PropTypes.object, };
Add help link to devrant menu
const path = require('path'); module.exports = (Franz, options) => { // Add back button to individual rants if ($('.addcomment-btn').length) { $('.rantlist').append('<li class="feed-prev-more"><a class="feed-back" onclick="window.history.back()" style="cursor: pointer"><span class="icon-back2 icon"></span><span class="feed-prev-more-link">Back</span></a><div class="clearfix"></div></li>'); } // Add target attribute to app buttons so they open in browser $('.app-btns-container a').each( function() { $(this).attr('target', '_blank'); }); // Add help link to devrant menu $('.menu-option-log-out').before('<li><a class="menu-franz" href="https://github.com/section214/franz-devrant/issues" target="_blank"><span class="icon-github2 icon"></span>Franz Integration</a></li>'); function getMessages() { let unread = ''; if ($('.top-bar-notif.notif-badge').length) { unread = $('.top-bar-notif.notif-badge').text(); } Franz.setBadge(unread); } Franz.loop(getMessages); };
const path = require('path'); module.exports = (Franz, options) => { // Add back button to individual rants if ($('.addcomment-btn').length) { $('.rantlist').append('<li class="feed-prev-more"><a class="feed-back" onclick="window.history.back()" style="cursor: pointer"><span class="icon-back2 icon"></span><span class="feed-prev-more-link">Back</span></a><div class="clearfix"></div></li>'); } // Add target attribute to app buttons so they open in browser $('.app-btns-container a').each( function() { $(this).attr('target', '_blank'); }); function getMessages() { let unread = ''; if ($('.top-bar-notif.notif-badge').length) { unread = $('.top-bar-notif.notif-badge').text(); } Franz.setBadge(unread); } Franz.loop(getMessages); };
Update docs for yamldumper test
# -*- coding: utf-8 -*- ''' Unit tests for salt.utils.yamldumper ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt Libs import salt.utils.yamldumper # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf from tests.support.mock import NO_MOCK, NO_MOCK_REASON @skipIf(NO_MOCK, NO_MOCK_REASON) class YamlDumperTestCase(TestCase): ''' TestCase for salt.utils.yamldumper module ''' def test_yaml_dump(self): ''' Test yaml.dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.dump(data) == '{!!python/unicode \'foo\': !!python/unicode \'bar\'}\n' assert salt.utils.yamldumper.dump(data, default_flow_style=False) == '!!python/unicode \'foo\': !!python/unicode \'bar\'\n' def test_yaml_safe_dump(self): ''' Test yaml.safe_dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.safe_dump(data) == '{foo: bar}\n' assert salt.utils.yamldumper.safe_dump(data, default_flow_style=False) == 'foo: bar\n'
# -*- coding: utf-8 -*- ''' Unit tests for salt.utils.yamldumper ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt Libs import salt.utils.yamldumper # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf from tests.support.mock import NO_MOCK, NO_MOCK_REASON @skipIf(NO_MOCK, NO_MOCK_REASON) class YamlDumperTestCase(TestCase): ''' TestCase for salt.utils.yamlloader module ''' def test_yaml_dump(self): ''' Test yaml.dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.dump(data) == '{!!python/unicode \'foo\': !!python/unicode \'bar\'}\n' assert salt.utils.yamldumper.dump(data, default_flow_style=False) == '!!python/unicode \'foo\': !!python/unicode \'bar\'\n' def test_yaml_safe_dump(self): ''' Test yaml.safe_dump a dict ''' data = {'foo': 'bar'} assert salt.utils.yamldumper.safe_dump(data) == '{foo: bar}\n' assert salt.utils.yamldumper.safe_dump(data, default_flow_style=False) == 'foo: bar\n'
Document and inherit please :D
/** * Get more info at : www.jrebirth.org . * Copyright JRebirth.org © 2011-2013 * Contact : sebastien.bordes@jrebirth.org * * 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.jrebirth.core.concurrent; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used to. * * @author Sébastien Bordes */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface RunInto { /** * Define the RunType value. * * The default value is RunType.JIT */ RunType value() default RunType.JIT; }
/** * Get more info at : www.jrebirth.org . * Copyright JRebirth.org © 2011-2013 * Contact : sebastien.bordes@jrebirth.org * * 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.jrebirth.core.concurrent; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used to. * * @author Sébastien Bordes */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface RunInto { /** * Define the RunType value. * * The default value is RunType.JIT */ RunType value() default RunType.JIT; }
Fix for downstream require-directory issues, make paths system-independent
/* * grunt-load-options * https://github.com/chriszarate/grunt-load-options * * Copyright (c) 2013-2014 Chris Zarate * Licensed under the MIT license. */ 'use strict'; var requireDirectory = require('require-directory'), path = require('path'); module.exports = function (grunt, options) { var config = {}; options = options || {}; options.folder = grunt.config.get('load-options.folder') || options.folder || './grunt'; options.configFolders = options.configFolders || ['config', 'options']; options.taskFolders = options.taskFolders || ['tasks', 'aliases']; // Load configuration. options.configFolders.forEach(function (configFolder) { var src = path.resolve(path.join(options.folder, configFolder)); if (grunt.file.exists(src) && grunt.file.isDir(src)) { var obj = requireDirectory(module, src); Object.keys(obj).forEach(function (prop) { config[prop] = (typeof obj[prop] === 'function') ? obj[prop](grunt) : obj[prop]; }); } }); grunt.initConfig(config); // Load tasks. options.taskFolders.forEach(function (taskFolder) { var src = path.resolve(path.join(options.folder, taskFolder)); if (grunt.file.exists(src) && grunt.file.isDir(src)) { grunt.loadTasks(src); } }); };
/* * grunt-load-options * https://github.com/chriszarate/grunt-load-options * * Copyright (c) 2013-2014 Chris Zarate * Licensed under the MIT license. */ 'use strict'; var requireDirectory = require('require-directory'); module.exports = function (grunt, options) { var config = {}; options = options || {}; options.folder = grunt.config.get('load-options.folder') || options.folder || './grunt'; options.configFolders = options.configFolders || ['config', 'options']; options.taskFolders = options.taskFolders || ['tasks', 'aliases']; // Load configuration. options.configFolders.forEach(function (configFolder) { var src = options.folder + '/' + configFolder; if (grunt.file.exists(src) && grunt.file.isDir(src)) { var obj = requireDirectory(module, src); Object.keys(obj).forEach(function (prop) { config[prop] = (typeof obj[prop] === 'function') ? obj[prop](grunt) : obj[prop]; }); } }); grunt.initConfig(config); // Load tasks. options.taskFolders.forEach(function (taskFolder) { var src = options.folder + '/' + taskFolder; if (grunt.file.exists(src) && grunt.file.isDir(src)) { grunt.loadTasks(src); } }); };
Fix auto slug generation for newly added parts Since moving to use nested forms, we now need to listen for a nested field added event and attach the auto slug generator handler accordingly.
// Javascript specific to guide admin // When we add a new part, ensure we add the auto slug generator handler $(document).on('nested:fieldAdded:parts', function(event){ addAutoSlugGeneration(); }); function addAutoSlugGeneration() { $('input.title'). on('change', function () { var elem = $(this); var value = elem.val(); // Set slug on change. var slug_field = elem.closest('.part').find('.slug'); if (slug_field.text() === '') { slug_field.val(GovUKGuideUtils.convertToSlug(value)); } // Set header on change. var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); } $(function() { var sortable_opts = { axis: "y", handle: "a.accordion-toggle", stop: function(event, ui) { $('.part').each(function (i, elem) { $(elem).find('input.order').val(i + 1); ui.item.find("a.accordion-toggle").addClass("highlight"); setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) }); } } $('#parts').sortable(sortable_opts) .find("a.accordion-toggle").css({cursor: 'move'}); addAutoSlugGeneration(); });
// Javascript specific to guide admin $(function() { var sortable_opts = { axis: "y", handle: "a.accordion-toggle", stop: function(event, ui) { $('.part').each(function (i, elem) { $(elem).find('input.order').val(i + 1); ui.item.find("a.accordion-toggle").addClass("highlight"); setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) }); } } $('#parts').sortable(sortable_opts) .find("a.accordion-toggle").css({cursor: 'move'}); $('input.title'). on('change', function () { var elem = $(this); var value = elem.val(); // Set slug on change. var slug_field = elem.closest('.part').find('.slug'); if (slug_field.text() === '') { slug_field.val(GovUKGuideUtils.convertToSlug(value)); } // Set header on change. var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); });
Change colour of command executed
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; let fatal = err => { console.error(`fatal: ${err}`); process.exit(1); }; process.argv.splice(0, 2); if (process.argv.length === 0) { fatal("No date string given"); }; let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (/Invalid Date/.test(parsedDate)) { fatal(`Could not parse ${date} into a valid date`); }; let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); let command = `GIT_COMMITTER_DATE="${dateString}" git commit --amend --date="${dateString}" --no-edit`; exec(command, (err, stdout, stderr) => { if (err) fatal("Could not modify the date of the previous commit"); console.log(chalk`\nModified previous commit:\n AUTHOR_DATE {grey ${dateString}}\n COMMITTER_DATE {grey ${dateString}}\n\nCommand executed:\n {grey ${command}}\n`); });
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; let fatal = err => { console.error(`fatal: ${err}`); process.exit(1); }; process.argv.splice(0, 2); if (process.argv.length === 0) { fatal("No date string given"); }; let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (/Invalid Date/.test(parsedDate)) { fatal(`Could not parse ${date} into a valid date`); }; let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); let command = `GIT_COMMITTER_DATE="${dateString}" git commit --amend --date="${dateString}" --no-edit`; exec(command, (err, stdout, stderr) => { if (err) fatal("Could not modify the date of the previous commit"); console.log(chalk`\nModified previous commit:\n AUTHOR_DATE {grey ${dateString}}\n COMMITTER_DATE {grey ${dateString}}\n\nCommand executed:\n {bgWhite.black ${command}}\n`); });
Change multiple to selectbox by default
<?php /** * PlumSearch plugin for CakePHP Rapid Development Framework * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @author Evgeny Tomenko * @since PlumSearch 0.1 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace PlumSearch\FormParameter; /** * Class MultipleParam * * @package PlumSearch\FormParameter */ class MultipleParameter extends SelectParameter { /** * Default configuration * * @var array */ protected $_defaultConfig = [ 'visible' => true, 'formConfig' => [ 'type' => 'select', 'multiple' => true, ], ]; }
<?php /** * PlumSearch plugin for CakePHP Rapid Development Framework * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @author Evgeny Tomenko * @since PlumSearch 0.1 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace PlumSearch\FormParameter; /** * Class MultipleParam * * @package PlumSearch\FormParameter */ class MultipleParam extends SelectParameter { /** * Default configuration * * @var array */ protected $_defaultConfig = [ 'visible' => true, 'formConfig' => [ 'type' => 'select', 'multiple' => 'checkbox', ], ]; }
Fix silly boiler plate copy issue.
from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" __description__ = "Information Measures on Causal Graphs." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
from .probability import ( vs, Variable, make_variables, UniformDist, JointDist, JointDistByState ) from .network import CausalGraph, Equation from .measure import MeasureCause, MeasureSuccess from .payoff import PayoffMatrix import equations __version__ = "0.1.0" __title__ = "causalinfo" __description__ = "Attributes without boilerplate." __uri__ = "http://github/brettc/causalinfo/" __author__ = "Brett Calcott" __email__ = "brett.calcott@gmail.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Brett Calcott" __all__ = [ "CausalGraph", "Equation", "vs", "Variable", "make_variables", "UniformDist", "JointDist", "JointDistByState", "MeasureCause", "MeasureSuccess", "PayoffMatrix", "equations", ]
Add getRandom() function and fix latlong function
/** * The 'leopard' namespace * @type {Object} */ 'use strict'; (function() { var leopard = { api: { key: 'AIzaSyCbPuQGIShYS-IYU1T6eIfhxH9yc-8biCg', direcctions: '', streetview: 'https://maps.googleapis.com/maps/api/streetview?size={{width}}x{{height}}&location={{location}}{{#heading}}&heading={{heading}}{{/heading}}{{#fov}}&fov={{fov}}{{/fov}}{{#pitch}}&pitch={{pitch}}{{/pitch}}&key={{key}}' }, images: { width: 250, height: 250 }, getRandom: function(from, to) { return Math.random() * (to - from) + from; }, getRandomLatLong: function() { var fixed = 3; // .toFixed() returns string, so ' * 1' is a trick to convert to number return { latitude: (this.getRandom(-90, 90)).toFixed(fixed) * 1, longitude: (this.getRandom(-180, 180)).toFixed(fixed) * 1 }; } }; window.leopard = leopard; })();
/** * The 'leopard' namespace * @type {Object} */ 'use strict'; (function() { var leopard = { api: { key: 'AIzaSyCbPuQGIShYS-IYU1T6eIfhxH9yc-8biCg', direcctions: '', streetview: 'https://maps.googleapis.com/maps/api/streetview?size={{width}}x{{height}}&location={{location}}{{#heading}}&heading={{heading}}{{/heading}}{{#fov}}&fov={{fov}}{{/fov}}{{#pitch}}&pitch={{pitch}}{{/pitch}}&key={{key}}' }, images: { width: 250, height: 250 }, getRandomLatLong: function(from, to, fixed) { // .toFixed() returns string, so ' * 1' is a trick to convert to number return { latitude: (Math.random() * (to - from) + from).toFixed(fixed) * 1, longitude: (Math.random() * (to - from) + from).toFixed(fixed) * 1 } } }; window.leopard = leopard; })();
Add two more test suites, pending containment and configuration.
/** * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.mockwire.guice2; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import net.stickycode.mockwire.MockwireTck; import net.stickycode.mockwire.direct.MockwireDirectTck; import net.stickycode.mockwire.junit4.MockwireRunnerTck; @RunWith(Suite.class) @SuiteClasses({ MockwireTck.class, MockwireDirectTck.class, MockwireRunnerTck.class }) public class MockwireTckTest { }
/** * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.mockwire.guice2; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import net.stickycode.mockwire.MockwireTck; @RunWith(Suite.class) @SuiteClasses({ MockwireTck.class }) public class MockwireTckTest { }
Rename SetDuration to CalcDuration and change attempts and factor to ints.
// Package utils contains common shared code. package utils import ( "math" "time" ) // Backoff holds the number of attempts as well as the min and max backoff delays. type Backoff struct { attempt, Factor int Min, Max time.Duration } // Duration calculates the backoff delay and increments the attempts count. func (b *Backoff) Duration(attempt int) time.Duration { d := b.CalcDuration(b.attempt) b.attempt++ return d } // CalcDuration calculates the backoff delay and caps it at the maximum delay. func (b *Backoff) CalcDuration(attempt int) time.Duration { if b.Min == 0 { b.Min = 100 * time.Millisecond } if b.Max == 0 { b.Max = 10 * time.Second } // Calculate the wait duration. duration := float64(b.Min) * math.Pow(float64(b.Factor), float64(attempt)) // Cap it at the maximum value. if duration > float64(b.Max) { return b.Max } return time.Duration(duration) } // Reset clears the number of attempts once the API call has succeeded. func (b *Backoff) Reset() { b.attempt = 0 } // Attempt returns the number of times the API call has failed. func (b *Backoff) Attempt() int { return b.attempt }
// Package utils contains common shared code. package utils import ( "math" "time" ) // Backoff holds the number of attempts as well as the min and max backoff delays. type Backoff struct { attempt, Factor float64 Min, Max time.Duration } // Duration calculates the backoff delay and increments the attempts count. func (b *Backoff) Duration(attempt float64) time.Duration { d := b.SetDuration(b.attempt) b.attempt++ return d } // SetDuration calculates the backoff delay and caps it at the maximum delay. func (b *Backoff) SetDuration(attempt float64) time.Duration { if b.Min == 0 { b.Min = 100 * time.Millisecond } if b.Max == 0 { b.Max = 10 * time.Second } // Calculate the wait duration. duration := float64(b.Min) * math.Pow(b.Factor, attempt) // Cap it at the maximum value. if duration > float64(b.Max) { return b.Max } return time.Duration(duration) } // Reset clears the number of attempts once the API call has succeeded. func (b *Backoff) Reset() { b.attempt = 0 } // Attempt returns the number of times the API call has failed. func (b *Backoff) Attempt() float64 { return b.attempt }
Fix for IE11 custom event
import assign from 'object-assign'; import { store } from './helpers'; export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW'; export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE'; export function dispatchGlobalEvent(eventName, opts, target = window) { // Compatibale with IE // @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work let event; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('CustomEvent'); event.initCustomEvent(eventName, false, true, opts); } if (target) { target.dispatchEvent(event); assign(store, opts); } } export function showMenu(opts = {}, target) { dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target); } export function hideMenu(opts = {}, target) { dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target); }
import assign from 'object-assign'; import { store } from './helpers'; export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW'; export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE'; export function dispatchGlobalEvent(eventName, opts, target = window) { // Compatibale with IE // @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work let event; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('Event'); event.initCustomEvent(eventName, false, true, opts); } if (target) { target.dispatchEvent(event); assign(store, opts); } } export function showMenu(opts = {}, target) { dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target); } export function hideMenu(opts = {}, target) { dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target); }
Remove class state from RarStream
//@flow import {Readable} from 'stream'; import RarFileChunk from './rar-file-chunk'; export default class RarStream extends Readable { constructor(...rarFileChunks: RarFileChunk[]){ super(); this._next(rarFileChunks); } pushData(stream: Readable, chunk: ?(Buffer | string)) : ?boolean { if (!super.push(chunk)){ stream.pause(); } } _next(rarFileChunks: RarFileChunk[]) { const chunk = rarFileChunks.shift(); if(!chunk){ this.push(null); } else { chunk.getStream().then((stream) => { stream.on('data', (data) => this.pushData(stream, data)); stream.on('end', () => this._next(rarFileChunks)); }); } } _read (){ this.resume(); } }
//@flow import {Readable} from 'stream'; import RarFileChunk from './rar-file-chunk'; export default class RarStream extends Readable { _rarFileChunks: RarFileChunk[]; _byteOffset: number = 0; constructor(...rarFileChunks: RarFileChunk[]){ super(); this._next(rarFileChunks); } pushData(stream: Readable, chunk: ?(Buffer | string)) : ?boolean { if (!super.push(chunk)){ stream.pause(); } } _next(rarFileChunks: RarFileChunk[]) { const chunk = rarFileChunks.shift(); if(!chunk){ this.push(null); } else { chunk.getStream().then((stream) => { stream.on('data', (data) => this.pushData(stream, data)); stream.on('end', () => this._next(rarFileChunks)); }); } } _read (){ this.resume(); } }
Set release version to 0.2.0 change repository for maintenance
from os.path import dirname, abspath, join, exists from setuptools import setup long_description = None if exists("README.md"): long_description = open("README.md").read() setup( name="mpegdash", packages=["mpegdash"], description="MPEG-DASH MPD(Media Presentation Description) Parser", long_description=long_description, author="sangwonl", author_email="gamzabaw@gmail.com", version="0.2.0", license="MIT", zip_safe=False, include_package_data=True, install_requires=["future"], url="https://github.com/sangwonl/python-mpegdash", tests_require=["unittest2"], test_suite="tests.my_module_suite", classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], )
from os.path import dirname, abspath, join, exists from setuptools import setup long_description = None if exists("README.md"): long_description = open("README.md").read() setup( name="mpegdash", packages=["mpegdash"], description="MPEG-DASH MPD(Media Presentation Description) Parser", long_description=long_description, author="supercast", author_email="gamzabaw@gmail.com", version="0.1.6", license="MIT", zip_safe=False, include_package_data=True, install_requires=["future"], url="https://github.com/caststack/python-mpegdash", tests_require=["unittest2"], test_suite="tests.my_module_suite", classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], )
Fix page ID for sanity check page...
<?php $config = SimpleSAML_Configuration::getInstance(); $sconfig = SimpleSAML_Configuration::getConfig('config-sanitycheck.php'); $info = array(); $errors = array(); $hookinfo = array( 'info' => &$info, 'errors' => &$errors, ); SimpleSAML_Module::callHooks('sanitycheck', $hookinfo); if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'text') { if (count($errors) === 0) { echo 'OK'; } else { echo 'FAIL'; } exit; } $t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php'); $t->data['pageid'] = 'sanitycheck'; $t->data['errors'] = $errors; $t->data['info'] = $info; $t->data['jquery'] = $jquery; $t->show();
<?php $config = SimpleSAML_Configuration::getInstance(); $sconfig = SimpleSAML_Configuration::getConfig('config-sanitycheck.php'); $info = array(); $errors = array(); $hookinfo = array( 'info' => &$info, 'errors' => &$errors, ); SimpleSAML_Module::callHooks('sanitycheck', $hookinfo); if (isset($_REQUEST['output']) && $_REQUEST['output'] == 'text') { if (count($errors) === 0) { echo 'OK'; } else { echo 'FAIL'; } exit; } $t = new SimpleSAML_XHTML_Template($config, 'sanitycheck:check-tpl.php'); $t->data['pageid'] = 'statistics'; $t->data['errors'] = $errors; $t->data['info'] = $info; $t->data['jquery'] = $jquery; $t->show();
Add EmployeeSimpleSerializer in order to avoid publish sensitive user data such passwords and other related fields
from .models import Star from employees.models import Employee from rest_framework import serializers class EmployeeSimpleSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('pk', 'username', 'first_name', 'last_name') class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): from_user = EmployeeSimpleSerializer() class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
from .models import Star from rest_framework import serializers class StarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'date', 'text', 'from_user', 'to_user', 'category', 'subcategory') class StarSmallSerializer(serializers.ModelSerializer): class Meta: model = Star depth = 1 fields = ('pk', 'date', 'text', 'category', 'from_user') class StarSwaggerSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('pk', 'category', 'subcategory', 'text') class StarEmployeesSubcategoriesSerializer(serializers.Serializer): subcategory__pk = serializers.IntegerField() subcategory__name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField() class StarTopEmployeeLists(serializers.Serializer): to_user__id = serializers.IntegerField() to_user__username = serializers.CharField(max_length=100) to_user__first_name = serializers.CharField(max_length=100) to_user__last_name = serializers.CharField(max_length=100) num_stars = serializers.IntegerField()
Make default port to 3000
'use strict'; const path = require('path'); const DEFAULT_PORT = 3000; const DEFAULT_DIRECTORY = ''; const HELP_FLAG = '--help'; const HELP_SHORTHAND_FLAG = '-h'; const SILENT_FLAG = '--silent'; const SILENT_SHORTHAND_FLAG = '-s'; const VERSION_FLAG = '--version'; const VERSION_SHORTHAND_FLAG = '-v'; const directory = process.env.npm_package_config_directory || process.env.npm_config_directory || process.argv[2] || DEFAULT_DIRECTORY; const port = ((val) => parseInt(val, 10))( process.env.npm_package_config_port || process.env.npm_config_port || process.argv[3] ) || DEFAULT_PORT; module.exports = { directory: path.join(process.cwd(), '', directory, '/'), port, help: process.argv.includes(HELP_FLAG) || process.argv.includes(HELP_SHORTHAND_FLAG), version: process.argv.includes(VERSION_FLAG) || process.argv.includes(VERSION_SHORTHAND_FLAG), silent: process.argv.includes(SILENT_FLAG) || process.argv.includes(SILENT_SHORTHAND_FLAG) };
'use strict'; const path = require('path'); const DEFAULT_PORT = 3360; const DEFAULT_DIRECTORY = ''; const HELP_FLAG = '--help'; const HELP_SHORTHAND_FLAG = '-h'; const SILENT_FLAG = '--silent'; const SILENT_SHORTHAND_FLAG = '-s'; const VERSION_FLAG = '--version'; const VERSION_SHORTHAND_FLAG = '-v'; const directory = process.env.npm_package_config_directory || process.env.npm_config_directory || process.argv[2] || DEFAULT_DIRECTORY; const port = ((val) => parseInt(val, 10))( process.env.npm_package_config_port || process.env.npm_config_port || process.argv[3] ) || DEFAULT_PORT; module.exports = { directory: path.join(process.cwd(), '', directory, '/'), port, help: process.argv.includes(HELP_FLAG) || process.argv.includes(HELP_SHORTHAND_FLAG), version: process.argv.includes(VERSION_FLAG) || process.argv.includes(VERSION_SHORTHAND_FLAG), silent: process.argv.includes(SILENT_FLAG) || process.argv.includes(SILENT_SHORTHAND_FLAG) };
Include composer.json in the WP distribution, to help WP-Packagist
module.exports = function(grunt) { grunt.initConfig({ copy: { main: { src: [ 'assets/**', '!assets/*/src/**', '!assets/*/src', 'includes/**', 'languages/**', 'CHANGELOG.md', 'composer.json', 'LICENSE.md', 'readme.txt', 'schemify.php' ], dest: 'dist/' }, }, makepot: { target: { options: { domainPath: 'languages/', mainFile: 'schemify.php', type: 'wp-plugin', updateTimestamp: false, updatePoFiles: true } } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-wp-i18n'); grunt.registerTask('i18n', ['makepot']); grunt.registerTask('build', ['i18n', 'copy']); };
module.exports = function(grunt) { grunt.initConfig({ copy: { main: { src: [ 'assets/**', '!assets/*/src/**', '!assets/*/src', 'inc/**', 'languages/**', 'CHANGELOG.md', 'schemify.php', 'LICENSE.md', 'readme.txt' ], dest: 'dist/' }, }, makepot: { target: { options: { domainPath: 'languages/', mainFile: 'schemify.php', type: 'wp-plugin', updateTimestamp: false, updatePoFiles: true } } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-wp-i18n'); grunt.registerTask('i18n', ['makepot']); grunt.registerTask('build', ['i18n', 'copy']); };
DanielWagnerHall: Fix test as well :) git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@17825 07704840-8298-11de-bf8c-fd130f914ac9
#!/usr/bin/python # Copyright 2012 Software Freedom Conservancy. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from selenium.webdriver.common.proxy import Proxy class ProxyTests(unittest.TestCase): def testCanAddToDesiredCapabilities(self): desired_capabilities = {} proxy = Proxy() proxy.http_proxy = 'some.url:1234' proxy.add_to_capabilities(desired_capabilities) expected_capabilities = { 'proxy': { 'proxyType': 'MANUAL', 'httpProxy': 'some.url:1234' } } self.assertEqual(expected_capabilities, desired_capabilities)
#!/usr/bin/python # Copyright 2012 Software Freedom Conservancy. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from selenium.webdriver.common.proxy import Proxy class ProxyTests(unittest.TestCase): def testCanAddToDesiredCapabilities(self): desired_capabilities = {} proxy = Proxy() proxy.http_proxy = 'some.url:1234' proxy.add_to_capabilities(desired_capabilities) expected_capabilities = { 'proxy': { 'proxyType': 'manual', 'httpProxy': 'some.url:1234' } } self.assertEqual(expected_capabilities, desired_capabilities)
[py] Sort files into dict with dir as key
#!/usr/bin/env python # -*- Coding: utf-8 -*- import os class Dirmuncher: def __init__(self, directory): self.directory = directory def getFiles(self): result = {} for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) result[dirname] = filenames return result if __name__ == "__main__": muncher = Dirmuncher('movies') print(muncher.getFiles())
#!/usr/bin/env python # -*- Coding: utf-8 -*- import os class Dirmuncher: def __init__(self, directory): self.directory = directory def directoryListing(self): for dirname, dirnames, filenames in os.walk(self.directory): # Subdirectories for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # Filenames for filename in filenames: print(os.path.join(dirname, filename)) if __name__ == "__main__": muncher = Dirmuncher('movies') muncher.directoryListing()
Change of the module version
# -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. # Copyright 2018 initOS GmbH # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', 'version': '8.0.1.0.0', 'author': "Eficent, " "initOS GmbH, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", 'category': 'Warehouse', 'summary': "Log changes being done in Inventory Adjustments", 'depends': ['stock'], "data": [ 'data/stock_data.xml', 'views/stock_inventory_view.xml', ], 'license': 'AGPL-3', 'installable': True, 'application': False, }
# -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', 'version': '9.0.1.0.0', 'author': "Eficent, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", 'category': 'Warehouse', 'summary': "Log changes being done in Inventory Adjustments", 'depends': ['stock'], "data": [ 'data/stock_data.xml', 'views/stock_inventory_view.xml', ], 'license': 'AGPL-3', 'installable': True, 'application': False, }
Add body_href method for getting a public url for a Style's body.
from geoserver.support import ResourceInfo, atom_link import re class Style(ResourceInfo): def __init__(self,catalog, node): self.catalog = catalog self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): ResourceInfo.update(self) self.name = self.metadata.find("name").text self.filename = self.metadata.find("filename").text # Get the raw sld sld_url = self.href.replace(".xml", ".sld") sld_xml = self.catalog.get_xml(sld_url) # Obtain the user style node where title and name are located user_style = sld_xml.find("{http://www.opengis.net/sld}NamedLayer/{http://www.opengis.net/sld}UserStyle") # Extract name and title nodes from user_style name_node = user_style.find("{http://www.opengis.net/sld}Name") title_node = user_style.find("{http://www.opengis.net/sld}Title") # Store the text value of sld name and title if present self.sld_name = name_node.text if hasattr(name_node, 'text') else None self.sld_title = title_node.text if hasattr(title_node, 'text') else None def body_href(self): style_container = re.sub(r"/rest$", "/styles", self.catalog.service_url) return "%s/%s" % (style_container, self.filename) def __repr__(self): return "Style[%s]" % self.name
from geoserver.support import ResourceInfo, atom_link class Style(ResourceInfo): def __init__(self,catalog, node): self.catalog = catalog self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): ResourceInfo.update(self) self.name = self.metadata.find("name").text self.filename = self.metadata.find("filename").text # Get the raw sld sld_url = self.href.replace(".xml", ".sld") sld_xml = self.catalog.get_xml(sld_url) # Obtain the user style node where title and name are located user_style = sld_xml.find("{http://www.opengis.net/sld}NamedLayer/{http://www.opengis.net/sld}UserStyle") # Extract name and title nodes from user_style name_node = user_style.find("{http://www.opengis.net/sld}Name") title_node = user_style.find("{http://www.opengis.net/sld}Title") # Store the text value of sld name and title if present self.sld_name = name_node.text if hasattr(name_node, 'text') else None self.sld_title = title_node.text if hasattr(title_node, 'text') else None def __repr__(self): return "Style[%s]" % self.name
Fix cd magic for ~ paths and add test
# Copyright (c) Metakernel Development Team. # Distributed under the terms of the Modified BSD License. from metakernel import Magic import os class CDMagic(Magic): def line_cd(self, path): """ %cd PATH - change current directory of session This line magic is used to change the directory of the notebook or console. Note that this is not the same directory as used by the %shell magics. Example: %cd .. """ path = os.path.expanduser(path) try: os.chdir(path) retval = os.path.abspath(path) except Exception as e: self.kernel.Error(str(e)) retval = None if retval: self.kernel.Print(retval) def register_magics(kernel): kernel.register_magics(CDMagic)
# Copyright (c) Metakernel Development Team. # Distributed under the terms of the Modified BSD License. from metakernel import Magic import os class CDMagic(Magic): def line_cd(self, path): """ %cd PATH - change current directory of session This line magic is used to change the directory of the notebook or console. Note that this is not the same directory as used by the %shell magics. Example: %cd .. """ try: os.chdir(path) retval = os.path.abspath(path) except Exception as e: self.kernel.Error(str(e)) retval = None if retval: self.kernel.Print(retval) def register_magics(kernel): kernel.register_magics(CDMagic)
Make sure timestamp of log message is UTC when it goes into DB
import redis import re from common import get_db from datetime import datetime MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$') CHANNEL = 'logfire' def listen(args): global MSGPATTERN rserver = redis.Redis('localhost') pubsub = rserver.pubsub() pubsub.subscribe(CHANNEL) db = get_db(args.mongohost) for packet in pubsub.listen(): try: if packet['type'] != 'message': continue match = MSGPATTERN.match(packet['data']) component = match.group(1) level = int(match.group(2)) message = match.group(3) db.insert(dict( tstamp=datetime.utcnow(),comp=component,lvl=level,msg=message)) except Exception, e: print e, packet
import redis import re from common import get_db from datetime import datetime MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$') CHANNEL = 'logfire' def listen(args): global MSGPATTERN rserver = redis.Redis('localhost') pubsub = rserver.pubsub() pubsub.subscribe(CHANNEL) db = get_db(args.mongohost) for packet in pubsub.listen(): try: if packet['type'] != 'message': continue match = MSGPATTERN.match(packet['data']) component = match.group(1) level = int(match.group(2)) message = match.group(3) db.insert(dict( tstamp=datetime.now(),comp=component,lvl=level,msg=message)) except Exception, e: print e, packet
Remove go 1.8 build tag for compatibility structs and constants
package avatica import ( "database/sql/driver" "fmt" ) type namedValue struct { Name string Ordinal int Value driver.Value } func driverValueToNamedValue(values []driver.Value) []namedValue { list := make([]namedValue, len(values)) for i, v := range values { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return list } func driverNamedValueToNamedValue(values []driver.NamedValue) ([]namedValue, error) { list := make([]namedValue, len(values)) for i, nv := range values { list[i] = namedValue(nv) if nv.Name != "" { return list, fmt.Errorf("named paramters are not supported: %s given", nv.Name) } } return list, nil } type isoLevel int32 const ( isolationUseCurrent isoLevel = -1 isolationNone isoLevel = 0 isolationReadUncommitted isoLevel = 1 isolationReadComitted isoLevel = 2 isolationRepeatableRead isoLevel = 4 isolationSerializable isoLevel = 8 )
// +build go1.8 package avatica import ( "database/sql/driver" "fmt" ) type namedValue struct { Name string Ordinal int Value driver.Value } func driverValueToNamedValue(values []driver.Value) []namedValue { list := make([]namedValue, len(values)) for i, v := range values { list[i] = namedValue{ Ordinal: i + 1, Value: v, } } return list } func driverNamedValueToNamedValue(values []driver.NamedValue) ([]namedValue,error ) { list := make([]namedValue, len(values)) for i, nv := range values { list[i] = namedValue(nv) if nv.Name != ""{ return list,fmt.Errorf("named paramters are not supported: %s given", nv.Name) } } return list, nil } type isoLevel int32 const ( isolationUseCurrent isoLevel = -1 isolationNone isoLevel = 0 isolationReadUncommitted isoLevel = 1 isolationReadComitted isoLevel = 2 isolationRepeatableRead isoLevel = 4 isolationSerializable isoLevel = 8 )
Add file transport and update log msg formatting to include pid and fn name
import os import logging def logger_setup(name): loglevel = '' try: if os.environ['PB_LOGLEVEL'] == 'DEBUG': loglevel = logging.DEBUG if os.environ['PB_LOGLEVEL'] == 'INFO': loglevel = logging.INFO if os.environ['PB_LOGLEVEL'] == 'WARN': loglevel = logging.WARN except: loglevel = logging.DEBUG # from https://docs.python.org/2/howto/logging.html#configuring-logging # set up new logger for this file logger = logging.getLogger(name) logger.setLevel(loglevel) # formatter formatter = logging.Formatter('PID: %(process)d - %(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s') # console handler for logging conLog = logging.StreamHandler() conLog.setLevel(loglevel) # format console logs using formatter conLog.setFormatter(formatter) # log to file handler fileLog = logging.FileHandler('pairing-bot.log', encoding='utf-8') fileLog.setLevel(logging.DEBUG) # format console logs using formatter fileLog.setFormatter(formatter) # add console logging transport to logger logger.addHandler(conLog) # add file transport to logger logger.addHandler(fileLog) return logger
import os import logging def logger_setup(name): loglevel = '' try: if os.environ['PB_LOGLEVEL'] == 'DEBUG': loglevel = logging.DEBUG if os.environ['PB_LOGLEVEL'] == 'INFO': loglevel = logging.INFO if os.environ['PB_LOGLEVEL'] == 'WARN': loglevel = logging.WARN except: loglevel = logging.DEBUG # from https://docs.python.org/2/howto/logging.html#configuring-logging # set up new logger for this file logger = logging.getLogger(name) logger.setLevel(loglevel) # console handler for logging conLog = logging.StreamHandler() conLog.setLevel(loglevel) # formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # format console logs using formatter conLog.setFormatter(formatter) # add console logging transport to logger logger.addHandler(conLog) return logger
Allow writing the expected AST using our own parser.
#!/usr/bin/env babel-node import print from './print-ast'; import { createWriteStream, readFileSync, readdirSync, statSync } from 'fs'; import { join, relative } from 'path'; import { parse as csrParse } from 'coffee-script-redux'; import { parse as dcParse } from '../src/parser'; let parse = source => csrParse(source, { raw: true }).toBasicObject(); let force = false; for (let i = 2; i < process.argv.length; i++) { switch (process.argv[i]) { case '--force': case '-f': force = true; break; case '--decaffeinate': parse = dcParse; break; default: throw new Error(`error: unexpected argument ${process.argv[i]}`); } } const examplesPath = join(__dirname, '../test/examples'); readdirSync(examplesPath).forEach(entry => { const dir = join(examplesPath, entry); const astPath = join(dir, 'output.json'); if (force || !existsWithContent(astPath)) { console.log(`Writing ${relative(process.cwd(), astPath)}.`); const input = readFileSync(join(dir, 'input.coffee'), { encoding: 'utf8' }); const output = createWriteStream(astPath); const printValue = (value, stream) => stream.write(JSON.stringify(value)); print(parse(input), output, printValue, printValue); } }); function existsWithContent(path) { try { const stat = statSync(path); return stat.size > 0; } catch (ex) { return false; } }
#!/usr/bin/env babel-node import { join, relative } from 'path'; import { parse as csrParse } from 'coffee-script-redux'; import print from './print-ast'; import { createWriteStream, readFileSync, readdirSync, statSync } from 'fs'; const examplesPath = join(__dirname, '../test/examples'); readdirSync(examplesPath).forEach(entry => { const dir = join(examplesPath, entry); const astPath = join(dir, 'output.json'); if (!existsWithContent(astPath)) { console.log(`Writing ${relative(process.cwd(), astPath)}.`); const input = readFileSync(join(dir, 'input.coffee'), { encoding: 'utf8' }); const output = createWriteStream(astPath); const printValue = (value, stream) => stream.write(JSON.stringify(value)); print(csrParse(input, { raw: true }).toBasicObject(), output, printValue, printValue); } }); function existsWithContent(path) { try { const stat = statSync(path); return stat.size > 0; } catch (ex) { return false; } }
Add special case for directory
#!/usr/bin/env node exports.command = { description: 'get an attribute for a project', arguments: '<project> <attribute>' }; if (require.main !== module) { return; } var program = require('commander'); var util = require('util'); var storage = require('../lib/storage.js'); var utilities = require('../lib/utilities.js'); program.option('--porcelain', 'Get the value in a machine-readable way'); program._name = 'get'; program.usage('<project> <attribute> <value>'); program.parse(process.argv); storage.setup(function () { if (program.args.length !== 2) { console.error('Please specify a project and attribute.'); process.exit(1); } // TODO: Support '.' for the project in the current directory var name = program.args[0]; var attribute = program.args[1]; var project = storage.getProjectOrDie(name); // XXX: Store the expanded directory instead? This feels hacky... if (attribute === 'directory') { project.directory = utilities.expand(project.directory); } if (program.porcelain) { console.log(project[attribute]); } else { console.log(util.format('%s:%s: "%s"', project.name, attribute, project[attribute])); } });
#!/usr/bin/env node exports.command = { description: 'get an attribute for a project', arguments: '<project> <attribute>' }; if (require.main !== module) { return; } var program = require('commander'); var util = require('util'); var storage = require('../lib/storage.js'); program.option('--porcelain', 'Get the value in a machine-readable way'); program._name = 'get'; program.usage('<project> <attribute> <value>'); program.parse(process.argv); storage.setup(function () { if (program.args.length !== 2) { console.error('Please specify a project and attribute.'); process.exit(1); } // TODO: Support '.' for the project in the current directory var name = program.args[0]; var attribute = program.args[1]; var project = storage.getProjectOrDie(name); if (program.porcelain) { console.log(project[attribute]); } else { console.log(util.format('%s:%s: "%s"', project.name, attribute, project[attribute])); } });
frontend/tests: Clean up AWS Credentials page tests and add assertions
const awsCredentialsPageCommands = { enterAwsCredentials(region) { const regionOption = `select#awsRegion option[value=${region}]`; this .setField('@awsAccessKey', process.env.AWS_ACCESS_KEY_ID) .setField('@secretAccesskey', process.env.AWS_SECRET_ACCESS_KEY) .waitForElementPresent(regionOption, 60000) .click(regionOption) .expect.element(regionOption).to.be.selected; return this.click('@nextStep'); }, }; module.exports = { url: '', commands: [awsCredentialsPageCommands], elements: { awsAccessKey: { selector: 'input#accessKeyId', }, secretAccesskey: { selector: 'input#secretAccessKey', }, nextStep: { selector: '//*[text()[contains(.,"Next Step")]]', locateStrategy: 'xpath', }, }, };
const awsCredentialsPageCommands = { enterAwsCredentials(region) { const regionOption = `select#awsRegion option[value=${region}]`; return this .setValue('@awsAccessKey', process.env.AWS_ACCESS_KEY_ID) .setValue('@secretAccesskey', process.env.AWS_SECRET_ACCESS_KEY) .waitForElementPresent(regionOption, 60000) .click(regionOption) .click('@nextStep'); }, }; module.exports = { url: '', commands: [awsCredentialsPageCommands], elements: { awsAccessKey: { selector: 'input#accessKeyId', }, secretAccesskey: { selector: 'input#secretAccessKey', }, nextStep: { selector: '//*[text()[contains(.,"Next Step")]]', locateStrategy: 'xpath', }, }, };
Fix translation key for deleted username
<?php $discussion = $document->data; $postsCount = count($discussion->relationships->posts->data); ?> <div class="container"> <h2>{{ $discussion->attributes->title }}</h2> <div> @foreach ($posts as $post) <div> <?php $user = $getResource($post->relationships->user->data); ?> <h3>{{ $user ? $user->attributes->username : $translator->trans('core.lib.username.deleted_text') }}</h3> <div class="Post-body"> {!! $post->attributes->contentHtml !!} </div> </div> <hr> @endforeach </div> @if ($page > 1) <a href="{{ $url(['page' => $page - 1]) }}">&laquo; {{ $translator->trans('core.views.discussion.previous_page_button') }}</a> @endif @if ($page < $postsCount / 20) <a href="{{ $url(['page' => $page + 1]) }}">{{ $translator->trans('core.views.discussion.next_page_button') }} &raquo;</a> @endif </div>
<?php $discussion = $document->data; $postsCount = count($discussion->relationships->posts->data); ?> <div class="container"> <h2>{{ $discussion->attributes->title }}</h2> <div> @foreach ($posts as $post) <div> <?php $user = $getResource($post->relationships->user->data); ?> <h3>{{ $user ? $user->attributes->username : $translator->trans('core.lib.deleted_user_text') }}</h3> <div class="Post-body"> {!! $post->attributes->contentHtml !!} </div> </div> <hr> @endforeach </div> @if ($page > 1) <a href="{{ $url(['page' => $page - 1]) }}">&laquo; {{ $translator->trans('core.views.discussion.previous_page_button') }}</a> @endif @if ($page < $postsCount / 20) <a href="{{ $url(['page' => $page + 1]) }}">{{ $translator->trans('core.views.discussion.next_page_button') }} &raquo;</a> @endif </div>
Allow views to be action-only (i.e. no markup returned)
<?php /* Copyright (c) 2012 Colin Rotherham, http://colinr.com https://github.com/colinrotherham */ namespace CRD\Core; class View { public $app; public $name; public $action; public $template; // All templates and partials public $templates = array(); public $partials = array(); // Shared array for passing from route action to view public $bag = array(); public function __construct($app, $name, $action) { $this->app = $app; $this->name = $name; $this->action = $action; if (!empty($this->name) && !file_exists($this->location())) throw new \Exception('Checking view: Missing view file'); // Allow views to access templates/partials $this->templates = $app->templates; $this->partials = $app->partials; // Provide caching helper $this->cache = $app->cache; } public function location() { return $this->app->path . '/views/' . $this->name . '.php'; } public function render() { // Run controller action if (is_callable($this->action)) { $action = $this->action; $action($this); } // Present view if provided if (!empty($this->name)) require_once ($this->location()); } } ?>
<?php /* Copyright (c) 2012 Colin Rotherham, http://colinr.com https://github.com/colinrotherham */ namespace CRD\Core; class View { public $app; public $name; public $action; public $template; // All templates and partials public $templates = array(); public $partials = array(); // Shared array for passing from route action to view public $bag = array(); public function __construct($app, $name, $action) { $this->app = $app; $this->name = $name; $this->action = $action; if (!file_exists($this->location())) throw new \Exception('Checking view: Missing view file'); // Allow views to access templates/partials $this->templates = $app->templates; $this->partials = $app->partials; // Provide caching helper $this->cache = $app->cache; } public function location() { return $this->app->path . '/views/' . $this->name . '.php'; } public function render() { // Run controller action if (is_callable($this->action)) { $action = $this->action; $action($this); } // Present view require_once ($this->location()); } } ?>
Add quick error messaging for easier debugging
import requests, json import pandas as pd class AT: def __init__(self, base, api): self.base = base self.api = api self.headers = {"Authorization": "Bearer "+self.api} def getTable(self,table): r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers) j = r.json() df = pd.DataFrame(dict(zip([i["id"] for i in j["records"]], [i["fields"] for i in j["records"]]))).transpose() return df def pushToTable(self, table, obj, typecast=False): h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) if r.status_code == requests.codes.ok: return r.json() else: print(r.json) return False
import requests, json import pandas as pd class AT: def __init__(self, base, api): self.base = base self.api = api self.headers = {"Authorization": "Bearer "+self.api} def getTable(self,table): r = requests.get("https://api.airtable.com/v0/"+self.base+"/"+table, headers=self.headers) j = r.json() df = pd.DataFrame(dict(zip([i["id"] for i in j["records"]], [i["fields"] for i in j["records"]]))).transpose() return df def pushToTable(self, table, obj, typecast=False): h = self.headers h["Content-type"] = "application/json" r = requests.post("https://api.airtable.com/v0/"+self.base+"/"+table, headers=h, data=json.dumps({"fields": obj, "typecast": typecast})) return r.json()
Update paragraph to new name
import React, { Component } from 'react'; /* component styles */ // import { styles } from './styles.scss'; export class About extends Component { render() { return ( // <about className={`${styles}`}> <about> <div className="container"> <div className="row"> <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <p> Chatson was created to give a user a visual representation of what is going on in a Twitch channel - the world’s leading social video platform and community for gamers. With our mood charts and graphs analyzing the realtime flow of comments, a user can instantly decide whether to join the channel. Chat messages are send to the Watson cognitive system API to return an analysis of emotional & social tone that is streamed to connected users. Users select one of the top 25 currently active streams and are presented with real­time visuals of the mood, frequency and length of incoming messages. Users may also view long term data from 4 channels selected by our team. </p> </div> </div> </div> </about> ); } }
import React, { Component } from 'react'; /* component styles */ // import { styles } from './styles.scss'; export class About extends Component { render() { return ( // <about className={`${styles}`}> <about> <div className="container"> <div className="row"> <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <p> twitchBot was created to give a user a visual representation of what is going on in a Twitch channel - the world’s leading social video platform and community for gamers. With our mood charts and graphs analyzing the realtime flow of comments, a user can instantly decide whether to join the channel. Chat messages are send to the Watson cognitive system API to return an analysis of emotional & social tone that is streamed to connected users. Users select one of the top 25 currently active twitch streams and are presented with real­time visuals of the mood, frequency and length of incoming messages. Users may also view long term data from 4 channels selected by our team. </p> </div> </div> </div> </about> ); } }
Append the button rather than pre-pend to give a natural z-index boost without having to specify overrides.
jQuery(function($){ $('#annotations').hide() var allTooltips = $(); $('<button class="btn btn-info"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> Toggle annotations</button>') .css({ position: 'fixed', right: '1em', top: '1em' }) .appendTo('body') .click(function(){ allTooltips.tooltip('toggle'); }); $('#annotations>[data-ref]').each(function(){ var tooltip = $($(this).data('ref')).tooltip({ trigger: 'manual', html: true, title: $(this).html(), placement: $(this).data('placement') || 'bottom' }); allTooltips = allTooltips.add(tooltip); }); });
jQuery(function($){ $('#annotations').hide() var allTooltips = $(); $('<button class="btn btn-info"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> Toggle annotations</button>') .css({ position: 'fixed', right: '1em', top: '1em' }) .prependTo('body') .click(function(){ allTooltips.tooltip('toggle'); }); $('#annotations>[data-ref]').each(function(){ var tooltip = $($(this).data('ref')).tooltip({ trigger: 'manual', html: true, title: $(this).html(), placement: $(this).data('placement') || 'bottom' }); allTooltips = allTooltips.add(tooltip); }); });
Configure RestTemplateCustomizer bean to provide ribbon client request factory to rest template
package org.dontpanic.spanners.springmvc.config; import com.netflix.client.http.HttpRequest; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.client.RestTemplateCustomizer; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.ribbon.RibbonClientHttpRequestFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * Configure the Rest client * * Implementation based on spring-cloud-netflix-core RibbonClientConfig. * * Created by stevie on 09/09/16. */ @Configuration @ConditionalOnClass(HttpRequest.class) @ConditionalOnProperty(value = "ribbon.http.client.enabled", matchIfMissing = false) @EnableDiscoveryClient public class RestClientConfig { /** * Customize the RestTemplate to use Ribbon load balancer to resolve service endpoints */ @Bean public RestTemplateCustomizer ribbonClientRestTemplateCustomizer( final RibbonClientHttpRequestFactory ribbonClientHttpRequestFactory) { return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { restTemplate.setRequestFactory(ribbonClientHttpRequestFactory); } }; } }
package org.dontpanic.spanners.springmvc.config; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.ribbon.RibbonClientHttpRequestFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Configure the Rest client * Created by stevie on 09/09/16. */ @Configuration @EnableDiscoveryClient public class RestClientConfig { private Logger logger = Logger.getLogger(RestClientConfig.class); @Autowired(required = false) private RibbonClientHttpRequestFactory ribbonRequestFactory; /** * Use Ribbon load balancer to resolve service endpoints */ @Bean public RestTemplateBuilder restTemplateBuilder() { RestTemplateBuilder builder = new RestTemplateBuilder(); if (ribbonRequestFactory != null) { builder = builder.requestFactory(ribbonRequestFactory); } else { logger.warn("Ribbon Http client disabled. Service endpoints will not be resolved by Eureka."); } return builder; } }
Use join instead of reduce
class Randomcase { /** * A function that transforms a normal string into Randomcase * * @static * @param {String} input * @memberof Randomcase */ static transform(input) { return input .split("") .map(char => Math.random() > 0.5 ? char.toUpperCase() : char.toLowerCase() ) .join(""); } } /** * Program definition - main */ const input = process.argv[2]; if (!input) { console.error('Input has to be provided! Use "--help" for help'); } else { processInput(input); } function processInput(input) { switch (input) { case "--help": case "-h": console.log("Usage: node index.js \"<string to randomcase>\""); break; default: console.log(Randomcase.transform(input)); break; } }
class Randomcase { /** * A function that transforms a normal string into Randomcase * * @static * @param {String} input * @memberof Randomcase */ static transform(input) { return input .split("") .map(char => Math.random() > 0.5 ? char.toUpperCase() : char.toLowerCase() ) .reduce((acc, curr) => acc += curr, ""); } } /** * Program definition - main */ const input = process.argv[2]; if(!input) { console.error('Input has to be provided! Use "--help" for help'); } else { processInput(input); } function processInput(input) { switch(input) { case "--help": case "-h": console.log("Usage: node index.js \"<string to randomcase>\""); break; default: console.log(Randomcase.transform(input)); break; } }
:skull: Create as much squares as possible within the canvas width
// Vanilla Javascript please document.addEventListener('DOMContentLoaded', function (event) { var canvas = document.querySelector('#canvas') // Canvas size var canvasHeight = 300 canvas.width = window.innerWidth canvas.height = canvasHeight // set context of the canvas 2d or webGL var c = canvas.getContext('2d', {alpha: true}) // Colors var rectMainColor = '#ff0000' // Square Dimension var squareD = 6 // spacing beetween squares var spacing = 3 c.fillStyle = 'chartreuse' c.fillRect(spacing, 50, squareD, squareD) c.fillRect((spacing * 2) + squareD, 50, squareD, squareD) c.fillRect((spacing * 3) + (squareD * 2), 50, squareD, squareD) c.fillRect((spacing * 4) + (squareD * 3), 50, squareD, squareD) c.fillStyle = rectMainColor // Create a line of squares var i = 1 var x = 0 var y = spacing while (x < canvas.width) { x = (spacing * i) + (squareD * (i - 1)) y = spacing c.fillRect(x, y, squareD, squareD) i++ } console.log(i) })
// Vanilla Javascript please document.addEventListener('DOMContentLoaded', function (event) { var canvas = document.querySelector('#canvas') // Canvas size var canvasHeight = 300 canvas.width = window.innerWidth canvas.height = canvasHeight // set context of the canvas 2d or webGL var c = canvas.getContext('2d', {alpha: true}) // Colors var rectMainColor = '#ff0000' // Square Dimension var squareD = 6 // spacing beetween squares var spacing = 3 c.fillStyle = 'chartreuse' c.fillRect(spacing, 50, squareD, squareD) c.fillRect((spacing * 2) + squareD, 50, squareD, squareD) c.fillRect((spacing * 3) + (squareD * 2), 50, squareD, squareD) c.fillRect((spacing * 4) + (squareD * 3), 50, squareD, squareD) c.fillStyle = rectMainColor for (var i = 1; i < 50; i++) { var x = (spacing * i) + (squareD * (i - 1)) var y = spacing c.fillRect(x, y, squareD, squareD) } })
Add todo about speeding up canvas clearing.
Doc = Base.extend({ beans: true, initialize: function(canvas) { if (canvas) { this.canvas = canvas; this.ctx = this.canvas.getContext('2d'); this.size = new Size(canvas.offsetWidth, canvas.offsetHeight); } Paper.documents.push(this); this.activate(); this.layers = []; this.activeLayer = new Layer(); this.currentStyle = null; this.symbols = []; }, getCurrentStyle: function() { return this._currentStyle; }, setCurrentStyle: function(style) { this._currentStyle = new PathStyle(this, style); }, activate: function() { Paper.activateDocument(this); }, redraw: function() { if (this.canvas) { // TODO: clearing the canvas by setting // this.canvas.width = this.canvas.width might be faster.. this.ctx.clearRect(0, 0, this.size.width + 1, this.size.height); for (var i = 0, l = this.layers.length; i < l; i++) { this.layers[i].draw(this.ctx); } } } });
Doc = Base.extend({ beans: true, initialize: function(canvas) { if (canvas) { this.canvas = canvas; this.ctx = this.canvas.getContext('2d'); this.size = new Size(canvas.offsetWidth, canvas.offsetHeight); } Paper.documents.push(this); this.activate(); this.layers = []; this.activeLayer = new Layer(); this.currentStyle = null; this.symbols = []; }, getCurrentStyle: function() { return this._currentStyle; }, setCurrentStyle: function(style) { this._currentStyle = new PathStyle(this, style); }, activate: function() { Paper.activateDocument(this); }, redraw: function() { if (this.canvas) { this.ctx.clearRect(0, 0, this.size.width + 1, this.size.height); for (var i = 0, l = this.layers.length; i < l; i++) { this.layers[i].draw(this.ctx); } } } });
Add test for content parser
/*! * unit asserts to ensure delivery of payload within * HTTP POST/PUT requests works * * @author pfleidi */ var assert = require('assert'); var Helper = require('./test_helper'); var HttpClient = require('../index'); var client = HttpClient.createClient({ parseContent: JSON.parse }); function _assertWithPayload(beforeExit, verb, payload) { var callbacks = 0; var echoServer = Helper.echoServer(); var upCase = verb.toUpperCase(); client[verb](echoServer.url + '/foo', payload) .on('success', function (data, resp) { callbacks += 1; assert.ok(data, 'Data must be provided'); assert.ok(resp, 'Response must be provided'); assert.strictEqual(data.method, upCase); assert.strictEqual(data.url, '/foo'); assert.strictEqual(data.headers['user-agent'], 'node-wwwdude'); assert.equal(data.headers['content-length'], payload.length); assert.strictEqual(data.payload, payload); }) .on('complete', function (data, resp) { callbacks += 1; }); beforeExit(function () { assert.strictEqual(callbacks, 2, 'Ensure all callbacks are called'); }); } exports.assertPayloadPut = function (beforeExit) { _assertWithPayload(beforeExit, 'put', 'ASAldfjsl'); }; exports.assertPayloadPost = function (beforeExit) { _assertWithPayload(beforeExit, 'post', '2342HurrDurrDerp!'); };
/*! * unit asserts to ensure delivery of payload within * HTTP POST/PUT requests works * * @author pfleidi */ var assert = require('assert'); var Helper = require('./test_helper'); var HttpClient = require('../index'); var client = HttpClient.createClient(); function _assertWithPayload(beforeExit, verb, payload) { var callbacks = 0; var echoServer = Helper.echoServer(); var upCase = verb.toUpperCase(); client[verb](echoServer.url + '/foo', payload) .on('success', function (data, resp) { callbacks += 1; var req = JSON.parse(data); assert.ok(data, 'Data must be provided'); assert.ok(resp, 'Response must be provided'); assert.strictEqual(req.method, upCase); assert.strictEqual(req.url, '/foo'); assert.strictEqual(req.headers['user-agent'], 'node-wwwdude'); assert.equal(req.headers['content-length'], payload.length); assert.strictEqual(req.payload, payload); }) .on('complete', function (data, resp) { callbacks += 1; }); beforeExit(function () { assert.strictEqual(callbacks, 2, 'Ensure all callbacks are called'); }); } exports.assertPayloadPut = function (beforeExit) { _assertWithPayload(beforeExit, 'put', 'ASAldfjsl'); }; exports.assertPayloadPost = function (beforeExit) { _assertWithPayload(beforeExit, 'post', '2342HurrDurrDerp!'); };
Correct bug in preflight check
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True return self.return_values = False
import simple_salesforce from cumulusci.tasks.salesforce import BaseSalesforceApiTask class is_rd2_enabled(BaseSalesforceApiTask): def _run_task(self): try: settings = self.sf.query( "SELECT IsRecurringDonations2Enabled__c " "FROM npe03__Recurring_Donations_Settings__c " "WHERE SetupOwnerId IN (SELECT Id FROM Organization)" ) except simple_salesforce.exceptions.SalesforceMalformedRequest: # The field does not exist in the target org, meaning it's # pre-RD2 self.return_values = False return if settings.get("records"): if settings["records"][0]["IsRecurringDonations2Enabled__c"]: self.return_values = True self.return_values = False
Remove wrapper function around StoreWatchMixin
module.exports = function() { var storeNames = Array.prototype.slice.call(arguments); return { componentWillMount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).on("change", this._setStateFromFlux) }, this); }, componentWillUnmount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).off("change", this._setStateFromFlux) }, this); }, _setStateFromFlux: function() { this.setState(this.getStateFromFlux()); }, getInitialState: function() { return this.getStateFromFlux(); } } };
module.exports = function(React) { return function() { var storeNames = Array.prototype.slice.call(arguments); return { componentWillMount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).on("change", this._setStateFromFlux) }, this); }, componentWillUnmount: function() { var flux = this.props.flux || this.context.flux; _.each(storeNames, function(store) { flux.store(store).off("change", this._setStateFromFlux) }, this); }, _setStateFromFlux: function() { this.setState(this.getStateFromFlux()); }, getInitialState: function() { return this.getStateFromFlux(); } } }; };
Store generated public key on chrome.storage.local.
function generate_key_pair() { generateKeyPair().then(function(key) { // export and store private key exportKey(key.privateKey).then(function(exported_private_key) { chrome.storage.local.set( { exported_private_key: exported_private_key }, function() { var status = document.getElementById('status'); status.textContent = 'Key pair was successfully created.'; setTimeout(function() { status.textContent = ''; }, 750); } ); }); // export and store public key exportKey(key.publicKey).then(function(exported_public_key) { chrome.storage.local.set( { exported_public_key: exported_public_key }, function() { setTimeout(function() { status.textContent = ''; }, 750); } ); }); }); } function export_public_key() {} document.getElementById('generate-key-pair').addEventListener('click', generate_key_pair); //document.getElementById('export-public-key').addEventListener('click', export_public_key);
function generate_key_pair() { generateKeyPair().then(function(key) { exportKey(key.privateKey).then(function(exported_private_key) { chrome.storage.local.set( { exported_private_key: exported_private_key }, function() { var status = document.getElementById('status'); status.textContent = 'Key pair was successfully created.'; setTimeout(function() { status.textContent = ''; }, 750); } ); }); }); } function export_public_key() {} document.getElementById('generate-key-pair').addEventListener('click', generate_key_pair); //document.getElementById('export-public-key').addEventListener('click', export_public_key);
LB-421: Create embed theme for STT fixed dust utf decode.
define(['utils/utf8'],function(utf8){ str = function(str){ this.init(str); } str.prototype = { init: function(str) { this.str = str; }, format: function() { var arg = arguments, idx = 0; if (arg.length == 1 && typeof arg[0] == 'object') arg = arg[0]; return utf8.decode(this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) { if (all[0] == all[1]) return all.substring(1); var value = arg[name || idx++]; if(typeof value === 'undefined') { return all; } return (type == 'i' || type == 'd') ? +value : value; })); }, toString: function() { return utf8.decode(this.str); } }; return str; });
define(['utils/utf8'],function(utf8){ str = function(str){ this.init(str); } str.prototype = { init: function(str) { this.str = str; }, format: function() { var arg = arguments, idx = 0; if (arg.length == 1 && typeof arg[0] == 'object') arg = arg[0]; return this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) { if (all[0] == all[1]) return all.substring(1); var value = arg[name || idx++]; if(typeof value === 'undefined') { return all; } return (type == 'i' || type == 'd') ? +value : utf8.decode(value); }); }, toString: function() { return utf8.decode(this.str); } }; return str; });
Update date format to be more correct
import {parse, format} from 'date-fns'; export function formatDate(startDate, endDate) { // If specific date is not defined yet. Meaning startDate is 2018-02 for instance if (startDate.length === 7) { return format(parse(`${startDate}-01`), 'MMMM'); } const parsedStartDate = parse(startDate); if (endDate && startDate !== endDate) { const parsedEndDate = parse(endDate); return `${format(parsedStartDate, 'MMMM D')}${format(parsedEndDate, '-D')}`; } else { return format(parsedStartDate, 'MMMM D'); } } export function generateEventJSONLD({name, url, city, country, startDate, endDate}) { const data = { '@context': 'http://schema.org', '@type': 'Event', location: { '@type': 'Place', address: { '@type': 'PostalAddress', addressLocality: city, addressCountry: country, }, name: `${city}, ${country}`, }, name, startDate, url, endDate: (endDate || startDate), }; return JSON.stringify(data); }
import {parse, format} from 'date-fns'; export function formatDate(startDate, endDate) { // If specific date is not defined yet. Meaning startDate is 2018-02 for instance if (startDate.length === 7) { return format(parse(`${startDate}-01`), 'MMMM'); } const parsedStartDate = parse(startDate); if (endDate && startDate !== endDate) { const parsedEndDate = parse(endDate); return `${format(parsedStartDate, 'MMMM, D')}${format(parsedEndDate, '-Do')}`; } else { return format(parsedStartDate, 'MMMM, Do'); } } export function generateEventJSONLD({name, url, city, country, startDate, endDate}) { const data = { '@context': 'http://schema.org', '@type': 'Event', location: { '@type': 'Place', address: { '@type': 'PostalAddress', addressLocality: city, addressCountry: country, }, name: `${city}, ${country}`, }, name, startDate, url, endDate: (endDate || startDate), }; return JSON.stringify(data); }
Remove nearby enemies on game start.
/* global game, Phaser, ms */ var Player = function(targetTile) { Phaser.Sprite.call(this, game, 0, 0, 'pix'); game.add.existing(this); ms.player = this; this.anchor.set(0.5); this.tint = 0x0000ff; this.height = 70; this.width = 40; this.x = targetTile.x; this.y = targetTile.y; if (targetTile.enemies.length > 0) targetTile.enemies.forEach(function(enemy) { enemy.kill(); enemy.destroy(); }); targetTile.enemies = []; targetTile.setExplored(); print(targetTile.getAdjacentTiles().length); targetTile.getAdjacentTiles().forEach(function(tile) { tile.setExplored(); tile.getAdjacentTiles().forEach(function(inner) { if (inner.enemies.length > 0) inner.enemies.forEach(function(enemy){ enemy.kill(); enemy.destroy(); }); inner.enemies = []; if (inner.state != 'explored') inner.setRevealed(); }); }); targetTile.events.onInputUp.dispatch(); }; Player.prototype = Object.create(Phaser.Sprite.prototype); Player.prototype.constructor = Player; module.exports = Player;
/* global game, Phaser, ms */ var Player = function(targetTile) { Phaser.Sprite.call(this, game, 0, 0, 'pix'); game.add.existing(this); ms.player = this; this.anchor.set(0.5); this.tint = 0x0000ff; this.height = 70; this.width = 40; this.x = targetTile.x; this.y = targetTile.y; if (targetTile.enemies.length > 0) targetTile.enemies.forEach(function(enemy) { enemy.kill(); enemy.destroy(); }); targetTile.enemies = []; targetTile.setExplored(); targetTile.events.onInputUp.dispatch(); print(targetTile.getAdjacentTiles().length); targetTile.getAdjacentTiles().forEach(function(tile) { tile.setExplored(); tile.getAdjacentTiles().forEach(function(inner) { if (inner.state != 'explored') inner.setRevealed(); }); }); }; Player.prototype = Object.create(Phaser.Sprite.prototype); Player.prototype.constructor = Player; module.exports = Player;
Remove use of findIndex to keep IE compatibility.
const directive = { instances: [] } directive.onEvent = function (event) { directive.instances.forEach(({ el, fn }) => { if (event.target !== el && !el.contains(event.target)) { fn && fn(event) } }) } directive.bind = function (el) { directive.instances.push({ el, fn: null }) if (directive.instances.length === 1) { document.addEventListener('click', directive.onEvent) } } directive.update = function (el, binding) { if (typeof binding.value !== 'function') { throw new Error('Argument must be a function') } const instance = directive.instances.find(i => i.el === el) instance.fn = binding.value } directive.unbind = function (el) { const instance = directive.instances.find(i => i.el === el) const instanceIndex = directive.instances.indexOf(instance) directive.instances.splice(instanceIndex, 1) if (directive.instances.length === 0) { document.removeEventListener('click', directive.onEvent) } } export default directive
const directive = { instances: [] } directive.onEvent = function (event) { directive.instances.forEach(({ el, fn }) => { if (event.target !== el && !el.contains(event.target)) { fn && fn(event) } }) } directive.bind = function (el) { directive.instances.push({ el, fn: null }) if (directive.instances.length === 1) { document.addEventListener('click', directive.onEvent) } } directive.update = function (el, binding) { if (typeof binding.value !== 'function') { throw new Error('Argument must be a function') } const instance = directive.instances.find(i => i.el === el) instance.fn = binding.value } directive.unbind = function (el) { const instanceIndex = directive.instances.findIndex(i => i.el === el) directive.instances.splice(instanceIndex, 1) if (directive.instances.length === 0) { document.removeEventListener('click', directive.onEvent) } } export default directive
Fix for if on the same page
// Copyright 2019 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. let highlightedId = 0; function initMap(mapLocation) { let myLatLng = {lat: mapLocation.lat, lng: mapLocation.lng}; map = new google.maps.Map(document.getElementById('map'), { zoom: 13, center: myLatLng, mapTypeControl: false }); } function createMarker(listing, cardNumber) { let marker = new google.maps.Marker({ position: {lat: listing.mapLocation.lat, lng: listing.mapLocation.lng}, }); marker.addListener('click', function() { document.getElementById(highlightedId).style.backgroundColor = '#fff'; map.setCenter(marker.getPosition()); map.setZoom(16); let firstId = document.getElementById('results-content').firstChild.id; // If card is not on the current page if ((cardNumber-firstId < 0) || (cardNumber-firstId >= 3)) { displayCards(cardNumber-firstId); } document.getElementById(cardNumber).style.backgroundColor = '#b3ffb3'; highlightedId = cardNumber; }); marker.setMap(map); }
// Copyright 2019 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. function initMap(mapLocation) { let myLatLng = {lat: mapLocation.lat, lng: mapLocation.lng}; map = new google.maps.Map(document.getElementById('map'), { zoom: 13, center: myLatLng, mapTypeControl: false }); } function createMarker(listing, cardNumber) { let marker = new google.maps.Marker({ position: {lat: listing.mapLocation.lat, lng: listing.mapLocation.lng}, }); marker.addListener('click', function() { map.setZoom(16); map.setCenter(marker.getPosition()); let firstId = document.getElementById('results-content').firstChild.id; console.log(firstId); displayCards(cardNumber-firstId); document.getElementById(cardNumber).style.backgroundColor = '#b3ffb3'; }); marker.setMap(map); }
Add authentication to Home route
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux' import { Router, Route, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import Home from './routes/Home/HomeContainer'; import Login from './routes/Login/LoginContainer'; import SignUp from './routes/SignUp/SignUpContainer'; import requiresAuth from './shared/components/requiresAuth/requiresAuth' import configureStore from './store/configureStore' import './index.css'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store) ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/login" component={Login} /> <Route path="/signup" component={SignUp} /> <Route path="/" component={requiresAuth(Home)} /> </Router> </Provider>, document.getElementById('root') );
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux' import { Router, Route, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import HomeContainer from './routes/Home/HomeContainer'; import LoginContainer from './routes/Login/LoginContainer'; import SignUpContainer from './routes/SignUp/SignUpContainer'; import requiresAuth from './shared/components/requiresAuth/requiresAuth' import configureStore from './store/configureStore' import './index.css'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store) ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/login" component={LoginContainer} /> <Route path="/signup" component={SignUpContainer} /> <Route path="/" component={HomeContainer} /> </Router> </Provider>, document.getElementById('root') );
Apply the content before creating post object
<?php namespace Isotop\Cargo\Content; class Post extends Abstract_Content { /** * Post constructor. * * @param mixed $post */ public function __construct( $post ) { // Bail if empty. if ( empty( $post ) ) { return; } // Bail if a revision post. if ( wp_is_post_revision( $post ) ) { return; } // Bail if `nav_menu_item` post type. if ( get_post_type( $post ) === 'nav_menu_item' ) { return; } $post = get_post( $post ); // Bail if empty. if ( empty( $post ) ) { return; } // Apply the content filter before creating post object. $post->post_content = apply_filters( 'the_content', $post->post_content ); // Create post object. $this->create( 'post', $post ); // Add meta data. $this->add( 'meta', $this->prepare_meta( $post->ID, get_post_meta( $post->ID ) ) ); // Add extra data. $this->add( 'extra', [ 'permalink' => get_permalink( $post ), 'site_id' => get_current_blog_id() ] ); } }
<?php namespace Isotop\Cargo\Content; class Post extends Abstract_Content { /** * Post constructor. * * @param mixed $post */ public function __construct( $post ) { // Bail if empty. if ( empty( $post ) ) { return; } // Bail if a revision post. if ( wp_is_post_revision( $post ) ) { return; } // Bail if `nav_menu_item` post type. if ( get_post_type( $post ) === 'nav_menu_item' ) { return; } $post = get_post( $post ); // Bail if empty. if ( empty( $post ) ) { return; } // Create post object. $this->create( 'post', $post ); // Add meta data. $this->add( 'meta', $this->prepare_meta( $post->ID, get_post_meta( $post->ID ) ) ); // Add extra data. $this->add( 'extra', [ 'permalink' => get_permalink( $post ), 'site_id' => get_current_blog_id() ] ); } }
Add test to construct FileUtilities
package com.sanctionco.thunder.util; import com.google.common.io.Resources; import java.io.IOException; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mockStatic; class FileUtilitiesTest { @Test void testConstructInstance() { new FileUtilities(); } @Test void shouldReadTestFile() { assertEquals("test", FileUtilities.readFileAsResources("fixtures/test.txt")); } @Test void shouldThrowOnNonexistentFile() { IllegalStateException nonexistent = assertThrows(IllegalStateException.class, () -> FileUtilities.readFileAsResources("not-exist")); assertTrue(nonexistent.getCause() instanceof IllegalArgumentException); } @Test void shouldThrowOnError() { try (MockedStatic<Resources> resourcesMock = mockStatic(Resources.class)) { resourcesMock.when(() -> Resources.toString(any(), any())).thenThrow(IOException.class); IllegalStateException exception = assertThrows(IllegalStateException.class, () -> FileUtilities.readFileAsResources("not-exist")); assertTrue(exception.getCause() instanceof IOException); } } }
package com.sanctionco.thunder.util; import com.google.common.io.Resources; import java.io.IOException; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mockStatic; class FileUtilitiesTest { @Test void shouldReadTestFile() { assertEquals("test", FileUtilities.readFileAsResources("fixtures/test.txt")); } @Test void shouldThrowOnNonexistentFile() { IllegalStateException nonexistent = assertThrows(IllegalStateException.class, () -> FileUtilities.readFileAsResources("not-exist")); assertTrue(nonexistent.getCause() instanceof IllegalArgumentException); } @Test void shouldThrowOnError() { try (MockedStatic<Resources> resourcesMock = mockStatic(Resources.class)) { resourcesMock.when(() -> Resources.toString(any(), any())).thenThrow(IOException.class); IllegalStateException exception = assertThrows(IllegalStateException.class, () -> FileUtilities.readFileAsResources("not-exist")); assertTrue(exception.getCause() instanceof IOException); } } }
Rename http-random-user key to category
import Cycle from '@cycle/core'; import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom'; import {makeHTTPDriver} from '@cycle/http'; function main(sources) { const getRandomUser$ = sources.DOM.select('.get-random').events('click') .map(() => { const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), category: 'users', method: 'GET' }; }); const user$ = sources.HTTP .filter(res$ => res$.request.category === 'users') .mergeAll() .map(res => res.body) .startWith(null); const vtree$ = user$.map(user => div('.users', [ button('.get-random', 'Get random user'), user === null ? null : div('.user-details', [ h1('.user-name', user.name), h4('.user-email', user.email), a('.user-website', {href: user.website}, user.website) ]) ]) ); return { DOM: vtree$, HTTP: getRandomUser$ }; } Cycle.run(main, { DOM: makeDOMDriver('#main-container'), HTTP: makeHTTPDriver() });
import Cycle from '@cycle/core'; import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom'; import {makeHTTPDriver} from '@cycle/http'; function main(sources) { const getRandomUser$ = sources.DOM.select('.get-random').events('click') .map(() => { const randomNum = Math.round(Math.random() * 9) + 1; return { url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum), key: 'users', method: 'GET' }; }); const user$ = sources.HTTP .filter(res$ => res$.request.key === 'users') .mergeAll() .map(res => res.body) .startWith(null); const vtree$ = user$.map(user => div('.users', [ button('.get-random', 'Get random user'), user === null ? null : div('.user-details', [ h1('.user-name', user.name), h4('.user-email', user.email), a('.user-website', {href: user.website}, user.website) ]) ]) ); return { DOM: vtree$, HTTP: getRandomUser$ }; } Cycle.run(main, { DOM: makeDOMDriver('#main-container'), HTTP: makeHTTPDriver() });
Update test for the getattr method.
# Copyright 2014 PressLabs SRL # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } assert simple_view.getattr("/fake/test/path") == asserted_getattr
# Copyright 2014 PressLabs SRL # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } assert simple_view.getattr() == asserted_getattr
Add const for configurator method name.
<?php namespace Limoncello\Contracts\Application; /** * Copyright 2015-2017 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Limoncello\Contracts\Routing\GroupInterface; /** * @package Limoncello\Application */ interface RoutesConfiguratorInterface { /** * Configurator's method name. */ const METHOD_NAME = 'configureRoutes'; /** * @return string[] */ public static function getMiddleware(): array; /** * @param GroupInterface $routes * * @return void */ public static function configureRoutes(GroupInterface $routes); }
<?php namespace Limoncello\Contracts\Application; /** * Copyright 2015-2017 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Limoncello\Contracts\Routing\GroupInterface; /** * @package Limoncello\Application */ interface RoutesConfiguratorInterface { /** * @return string[] */ public static function getMiddleware(): array; /** * @param GroupInterface $routes * * @return void */ public static function configureRoutes(GroupInterface $routes); }
Use new line style for Implementation item
""" Implementation of interface. """ from gaphor import UML from gaphor.UML.modelfactory import stereotypes_str from gaphor.diagram.presentation import LinePresentation from gaphor.diagram.shapes import Box, Text from gaphor.diagram.support import represents @represents(UML.Implementation) class ImplementationItem(LinePresentation): def __init__(self, id=None, model=None): super().__init__(id, model, style={"dash-style": (7.0, 5.0)}) self._solid = False self.shape_middle = Box( Text( text=lambda: stereotypes_str(self.subject), style={"min-width": 0, "min-height": 0}, ) ) self.watch("subject.appliedStereotype.classifier.name") def draw_head(self, context): cr = context.cairo cr.move_to(0, 0) if not self._solid: cr.set_dash((), 0) cr.line_to(15, -10) cr.line_to(15, 10) cr.close_path() cr.stroke() cr.move_to(15, 0)
""" Implementation of interface. """ from gaphor import UML from gaphor.diagram.diagramline import DiagramLine class ImplementationItem(DiagramLine): __uml__ = UML.Implementation def __init__(self, id=None, model=None): DiagramLine.__init__(self, id, model) self._solid = False def draw_head(self, context): cr = context.cairo cr.move_to(0, 0) if not self._solid: cr.set_dash((), 0) cr.line_to(15, -10) cr.line_to(15, 10) cr.close_path() cr.stroke() cr.move_to(15, 0) def draw(self, context): if not self._solid: context.cairo.set_dash((7.0, 5.0), 0) super(ImplementationItem, self).draw(context) # vim:sw=4
Fix bin scripts having python2 or python3 specific path.
# -*- coding: utf-8 -*- # Copyright (C) 2012-2014 MUJIN Inc from distutils.core import setup try: from mujincommon.setuptools import Distribution except ImportError: from distutils.dist import Distribution version = {} exec(open('python/mujincontrollerclient/version.py').read(), version) setup( distclass=Distribution, name='mujincontrollerclient', version=version['__version__'], packages=['mujincontrollerclient'], package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'}, data_files=[ # using scripts= will cause the first line of the script being modified for python2 or python3 # put the scripts in data_files will copy them as-is ('bin', ['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py']), ], locale_dir='locale', license='Apache License, Version 2.0', long_description=open('README.rst').read(), # flake8 compliance configuration enable_flake8=True, # Enable checks fail_on_flake=True, # Fail builds when checks fail install_requires=[], )
# -*- coding: utf-8 -*- # Copyright (C) 2012-2014 MUJIN Inc from distutils.core import setup try: from mujincommon.setuptools import Distribution except ImportError: from distutils.dist import Distribution version = {} exec(open('python/mujincontrollerclient/version.py').read(), version) setup( distclass=Distribution, name='mujincontrollerclient', version=version['__version__'], packages=['mujincontrollerclient'], package_dir={'mujincontrollerclient': 'python/mujincontrollerclient'}, scripts=['bin/mujin_controllerclientpy_registerscene.py', 'bin/mujin_controllerclientpy_applyconfig.py'], locale_dir='locale', license='Apache License, Version 2.0', long_description=open('README.rst').read(), # flake8 compliance configuration enable_flake8=True, # Enable checks fail_on_flake=True, # Fail builds when checks fail install_requires=[], )
Read file with fs module
/* * grunt-rev * https://github.com/cbas/grunt-rev * * Copyright (c) 2013 Sebastiaan Deckers * Licensed under the MIT license. */ 'use strict'; var fs = require('fs'), path = require('path'), crypto = require('crypto'); module.exports = function(grunt) { function md5(filepath, algorithm, encoding, fileEncoding) { var hash = crypto.createHash(algorithm); grunt.log.verbose.write('Hashing ' + filepath + '...'); hash.update(fs.readFileSync(filepath), fileEncoding); return hash.digest(encoding); } grunt.registerMultiTask('rev', 'Prefix static asset file names with a content hash', function() { var options = this.options({ encoding: 'utf8', algorithm: 'md5', length: 8 }); this.files.forEach(function(filePair) { filePair.src.forEach(function(f) { var hash = md5(f, options.algorithm, 'hex', options.encoding), prefix = hash.slice(0, options.length), renamed = [prefix, path.basename(f)].join('.'), outPath = path.resolve(path.dirname(f), renamed); grunt.verbose.ok().ok(hash); fs.renameSync(f, outPath); grunt.log.write(f + ' ').ok(renamed); }); }); }); };
/* * grunt-rev * https://github.com/cbas/grunt-rev * * Copyright (c) 2013 Sebastiaan Deckers * Licensed under the MIT license. */ 'use strict'; var fs = require('fs'), path = require('path'), crypto = require('crypto'); module.exports = function(grunt) { function md5(filepath, algorithm, encoding, fileEncoding) { var hash = crypto.createHash(algorithm); grunt.log.verbose.write('Hashing ' + filepath + '...'); hash.update(grunt.file.read(filepath), fileEncoding); return hash.digest(encoding); } grunt.registerMultiTask('rev', 'Prefix static asset file names with a content hash', function() { var options = this.options({ encoding: 'utf8', algorithm: 'md5', length: 8 }); this.files.forEach(function(filePair) { filePair.src.forEach(function(f) { var hash = md5(f, options.algorithm, 'hex', options.encoding), prefix = hash.slice(0, options.length), renamed = [prefix, path.basename(f)].join('.'), outPath = path.resolve(path.dirname(f), renamed); grunt.verbose.ok().ok(hash); fs.renameSync(f, outPath); grunt.log.write(f + ' ').ok(renamed); }); }); }); };
Make text based repaint output not appear in images BUG=345027 Review URL: https://codereview.chromium.org/197553008 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@169165 bbb929c8-8fbe-4397-9dbb-9b2b20218538
// Asynchronous tests should manually call finishRepaintTest at the appropriate time. window.testIsAsync = false; function runRepaintTest() { if (!window.testRunner || !window.internals) { setTimeout(repaintTest, 100); return; } if (window.enablePixelTesting) testRunner.dumpAsTextWithPixelResults(); else testRunner.dumpAsText(); if (window.testIsAsync) testRunner.waitUntilDone(); if (document.body) document.body.offsetTop; else if (document.documentElement) document.documentElement.offsetTop; window.internals.startTrackingRepaints(document); repaintTest(); if (!window.testIsAsync) finishRepaintTest(); } function finishRepaintTest() { // Force a style recalc. var dummy = document.body.offsetTop; var repaintRects = window.internals.repaintRectsAsText(document); internals.stopTrackingRepaints(document); var pre = document.createElement('pre'); pre.style.opacity = 0; // appear in text dumps, but not images document.body.appendChild(pre); pre.textContent += repaintRects; if (window.afterTest) window.afterTest(); if (window.testIsAsync) testRunner.notifyDone(); }
// Asynchronous tests should manually call finishRepaintTest at the appropriate time. window.testIsAsync = false; function runRepaintTest() { if (!window.testRunner || !window.internals) { setTimeout(repaintTest, 100); return; } if (window.enablePixelTesting) testRunner.dumpAsTextWithPixelResults(); else testRunner.dumpAsText(); if (window.testIsAsync) testRunner.waitUntilDone(); if (document.body) document.body.offsetTop; else if (document.documentElement) document.documentElement.offsetTop; window.internals.startTrackingRepaints(document); repaintTest(); if (!window.testIsAsync) finishRepaintTest(); } function finishRepaintTest() { // Force a style recalc. var dummy = document.body.offsetTop; var repaintRects = window.internals.repaintRectsAsText(document); internals.stopTrackingRepaints(document); var pre = document.createElement('pre'); document.body.appendChild(pre); pre.textContent += repaintRects; if (window.afterTest) window.afterTest(); if (window.testIsAsync) testRunner.notifyDone(); }
Fix test for dateTime inequality over time
import * as slimdom from 'slimdom'; import { evaluateXPathToBoolean, evaluateXPathToString } from 'fontoxpath'; let documentNode; beforeEach(() => { documentNode = new slimdom.Document(); }); describe('Context related functions', () => { describe('fn:current-dateTime', () => { it('returns the current dateTime', () => chai.assert.isOk(evaluateXPathToString('current-dateTime()', documentNode))); it('returns the same value during the execution of the query', () => chai.assert.isTrue(evaluateXPathToBoolean('current-dateTime() eq current-dateTime()'))); it('returns different values for different queries', async () => { const dateTime = evaluateXPathToString('current-dateTime()'); const dateTimeLater = await new Promise(resolve => setTimeout(() => resolve(evaluateXPathToString('current-dateTime()')), 100)); chai.assert.notEqual(dateTime, dateTimeLater); }); }); describe('fn:current-date', () => { it('returns the current date', () => chai.assert.isOk(evaluateXPathToString('current-date()', documentNode))); }); describe('fn:current-time', () => { it('returns the current time', () => chai.assert.isOk(evaluateXPathToString('current-time()', documentNode))); }); describe('fn:implicit-timezone', () => { it('returns the implicit timezone', () => chai.assert.isOk(evaluateXPathToString('implicit-timezone()', documentNode))); }); });
import * as slimdom from 'slimdom'; import { evaluateXPathToBoolean, evaluateXPathToString } from 'fontoxpath'; let documentNode; beforeEach(() => { documentNode = new slimdom.Document(); }); describe('Context related functions', () => { describe('fn:current-dateTime', () => { it('returns the current dateTime', () => chai.assert.isOk(evaluateXPathToString('current-dateTime()', documentNode))); it('returns the same value during the execution of the query', () => chai.assert.isTrue(evaluateXPathToBoolean('current-dateTime() eq current-dateTime()'))); it('returns different values for different queries', () => chai.assert.notEqual(evaluateXPathToString('current-dateTime()'), setTimeout(evaluateXPathToString('current-dateTime()'), 100))); }); describe('fn:current-date', () => { it('returns the current date', () => chai.assert.isOk(evaluateXPathToString('current-date()', documentNode))); }); describe('fn:current-time', () => { it('returns the current time', () => chai.assert.isOk(evaluateXPathToString('current-time()', documentNode))); }); describe('fn:implicit-timezone', () => { it('returns the implicit timezone', () => chai.assert.isOk(evaluateXPathToString('implicit-timezone()', documentNode))); }); });
Use this.emitChange() instead of old API
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var createStore = require('fluxible-app/utils/createStore'); var TimeStore = createStore({ storeName: 'TimeStore', initialize: function (dispatcher) { this.time = new Date(); }, handleTimeChange: function (payload) { this.time = new Date(); this.emitChange(); }, handlers: { 'CHANGE_ROUTE_START': 'handleTimeChange', 'UPDATE_TIME': 'handleTimeChange' }, getState: function () { return { time: this.time.toString() }; }, dehydrate: function () { return this.getState(); }, rehydrate: function (state) { this.time = new Date(state.time); } }); module.exports = TimeStore;
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var createStore = require('fluxible-app/utils/createStore'); var TimeStore = createStore({ storeName: 'TimeStore', initialize: function (dispatcher) { this.time = new Date(); }, handleTimeChange: function (payload) { this.time = new Date(); this.emit('change'); }, handlers: { 'CHANGE_ROUTE_START': 'handleTimeChange', 'UPDATE_TIME': 'handleTimeChange' }, getState: function () { return { time: this.time.toString() }; }, dehydrate: function () { return this.getState(); }, rehydrate: function (state) { this.time = new Date(state.time); } }); module.exports = TimeStore;
Add sending a message to event subscribers
import json from channels import Group from channels.auth import channel_session_user, channel_session_user_from_http from django.dispatch import receiver from django.db.models.signals import post_save from event.models import Event @receiver(post_save, sender=Event) def send_update(sender, instance, **kwargs): for user in instance.users.all(): channel = Group('user-{}'.format(user.id)) channel.send({ 'text': json.dumps({ 'id': instance.id, 'title': instance.title, }) }) @channel_session_user_from_http def ws_connect(message): message.reply_channel.send({'accept': True}) if message.user.is_authenticated: Group('user-{}'.format(message.user.id)).add(message.reply_channel) @channel_session_user def ws_disconnect(message): Group('user-{}'.format(message.user.id)).discard(message.reply_channel)
import json from channels import Group from channels.auth import channel_session_user, channel_session_user_from_http from django.dispatch import receiver from django.db.models.signals import post_save from event.models import Event @receiver(post_save, sender=Event) def send_update(sender, instance, **kwargs): Group('users').send({ 'text': json.dumps({ 'id': instance.id, 'title': instance.title, }) }) @channel_session_user_from_http def ws_connect(message): Group('users').add(message.reply_channel) message.reply_channel.send({ 'accept': True }) @channel_session_user def ws_disconnect(message): Group('users').discard(message.reply_channel)
Remove window.location.href in advanced search js
Blacklight.onLoad(function() { $(window).on('load', function(){ //remove default mast search to fix duplicate IDs $(".blacklight-catalog-advanced_search #search-navbar").remove(); $(".blacklight-trln-advanced_search #search-navbar").remove(); // change adv search scope $(".blacklight-trln-advanced_search").length > 0 ? $('#option_trln').attr('checked',true) : $('#option_catalog').attr('checked',true); $("input[type='radio'][name='option']").change(function() { var action = $(this).val(); $(".advanced").attr("action", "/" + action); }); // fix labeling for fields generated by Chosen jquery library (https://harvesthq.github.io/chosen/) $("[id$='_chosen']").each(function() { $the_id = $(this).attr('id'); $aria_label = $(this).attr('id').replace('_chosen', '_label'); $('#' + $the_id + ' .chosen-search-input').attr('aria-labelledby', $aria_label); }); }); });
Blacklight.onLoad(function() { $(window).on('load', function(){ //remove default mast search to fix duplicate IDs $(".blacklight-catalog-advanced_search #search-navbar").remove(); $(".blacklight-trln-advanced_search #search-navbar").remove(); // change adv search scope window.location.href.indexOf('advanced_trln') != -1 ? $('#option_trln').attr('checked',true) : $('#option_catalog').attr('checked',true); $("input[type='radio'][name='option']").change(function() { var action = $(this).val(); $(".advanced").attr("action", "/" + action); }); // fix labeling for fields generated by Chosen jquery library (https://harvesthq.github.io/chosen/) $("[id$='_chosen']").each(function() { $the_id = $(this).attr('id'); $aria_label = $(this).attr('id').replace('_chosen', '_label'); $('#' + $the_id + ' .chosen-search-input').attr('aria-labelledby', $aria_label); }); }); });
Add missing ensure_str for PY2
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 default_encoding = "UTF-8" def with_metaclass(meta, *bases): class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) if PY3: basestring = (str, bytes) def ensure_bytes(s): if type(s) == str: return bytes(s, default_encoding) else: return bytes(s) def ensure_str(s): if type(s) == bytes: return s.decode(default_encoding) else: return s else: range = xrange ensure_bytes = lambda s: s ensure_str = lambda s: s
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 default_encoding = "UTF-8" def with_metaclass(meta, *bases): class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) if PY3: basestring = (str, bytes) def ensure_bytes(s): if type(s) == str: return bytes(s, default_encoding) else: return bytes(s) def ensure_str(s): if type(s) == bytes: return s.decode(default_encoding) else: return s else: range = xrange ensure_bytes = lambda s: s
Fix header shifting to also shift closing tags Closes #55
var fs = require("fs") var markdown = (require("markdown-it")({html: true})).use(require("markdown-it-deflist")) var Mold = require("mold-template") module.exports = function loadTemplates(config) { var mold = new Mold(config.env || {}) fs.readdirSync(config.dir).forEach(function(filename) { var match = /^(.*?)\.html$/.exec(filename) if (match) mold.bake(match[1], fs.readFileSync(config.dir + match[1] + ".html", "utf8").trim()) }) mold.defs.markdown = function(options) { if (typeof options == "string") options = {text: options} let text = markdown.render(config.markdownFilter ? config.markdownFilter(options.text) : options.text) if (options.shiftHeadings) text = text.replace(/<(\/?)h(\d)\b/ig, (_, cl, d) => "<" + cl + "h" + (+d + options.shiftHeadings)) return text } mold.defs.markdownFile = function(options) { if (typeof options == "string") options = {file: options} options.text = fs.readFileSync(config.markdownDir + options.file + ".md", "utf8") return mold.defs.markdown(options) } return mold }
var fs = require("fs") var markdown = (require("markdown-it")({html: true})).use(require("markdown-it-deflist")) var Mold = require("mold-template") module.exports = function loadTemplates(config) { var mold = new Mold(config.env || {}) fs.readdirSync(config.dir).forEach(function(filename) { var match = /^(.*?)\.html$/.exec(filename) if (match) mold.bake(match[1], fs.readFileSync(config.dir + match[1] + ".html", "utf8").trim()) }) mold.defs.markdown = function(options) { if (typeof options == "string") options = {text: options} let text = markdown.render(config.markdownFilter ? config.markdownFilter(options.text) : options.text) if (options.shiftHeadings) text = text.replace(/<h(\d)\b/ig, (_, d) => "<h" + (+d + options.shiftHeadings)) return text } mold.defs.markdownFile = function(options) { if (typeof options == "string") options = {file: options} options.text = fs.readFileSync(config.markdownDir + options.file + ".md", "utf8") return mold.defs.markdown(options) } return mold }
Move master version to 0.1.1.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Kaede Hoshikawa # # 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. __all__ = ["__version__"] _tag_version = (0, 1, 1) _dev = 0 _version_fragments = [str(i) for i in _tag_version[:3]] if _dev is not None: _version_fragments.append(f"dev{_dev}") __version__ = ".".join(_version_fragments)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Kaede Hoshikawa # # 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. __all__ = ["__version__"] _tag_version = (0, 1, 0) _dev = 0 _version_fragments = [str(i) for i in _tag_version[:3]] if _dev is not None: _version_fragments.append(f"dev{_dev}") __version__ = ".".join(_version_fragments)
Update Chakra regex to grab latest version Fixes #31. Closes #32.
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // <https://apache.org/licenses/LICENSE-2.0>. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an “AS IS” BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const get = require('../../shared/get.js'); const getLatestVersion = () => { const url = 'https://github.com/Microsoft/ChakraCore/releases/latest'; return new Promise(async (resolve, reject) => { try { const response = await get(url); // https://stackoverflow.com/a/1732454/96656 const regex = /href="\/Microsoft\/ChakraCore\/tree\/v(\d+\.\d+.\d+)"/; const version = regex.exec(response.body)[1]; resolve(version); } catch (error) { reject(error); } }); }; module.exports = getLatestVersion;
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // <https://apache.org/licenses/LICENSE-2.0>. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an “AS IS” BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const get = require('../../shared/get.js'); const getLatestVersion = () => { const url = 'https://github.com/Microsoft/ChakraCore/releases/latest'; return new Promise(async (resolve, reject) => { try { const response = await get(url); // https://stackoverflow.com/a/1732454/96656 const regex = /<a href="\/Microsoft\/ChakraCore\/compare\/v(\d+\.\d+.\d+)\.\.\.master">/; const version = regex.exec(response.body)[1]; resolve(version); } catch (error) { reject(error); } }); }; module.exports = getLatestVersion;
Increase buffer to 5 megabytes
package main import ( "io" "time" ) func Start(stop chan int) { for _, in := range Plugins.Inputs { go CopyMulty(in, Plugins.Outputs...) } for { select { case <-stop: return case <-time.After(1 * time.Second): } } } // Copy from 1 reader to multiple writers func CopyMulty(src io.Reader, writers ...io.Writer) (err error) { buf := make([]byte, 5*1024*1024) wIndex := 0 for { nr, er := src.Read(buf) if nr > 0 && len(buf) > nr { Debug("Sending", src, ": ", string(buf[0:nr])) if Settings.splitOutput { // Simple round robin writers[wIndex].Write(buf[0:nr]) wIndex++ if wIndex >= len(writers) { wIndex = 0 } } else { for _, dst := range writers { dst.Write(buf[0:nr]) } } } if er == io.EOF { break } if er != nil { err = er break } } return err }
package main import ( "io" "time" ) func Start(stop chan int) { for _, in := range Plugins.Inputs { go CopyMulty(in, Plugins.Outputs...) } for { select { case <-stop: return case <-time.After(1 * time.Second): } } } // Copy from 1 reader to multiple writers func CopyMulty(src io.Reader, writers ...io.Writer) (err error) { buf := make([]byte, 32*1024) wIndex := 0 for { nr, er := src.Read(buf) if nr > 0 && len(buf) > nr { Debug("Sending", src, ": ", string(buf[0:nr])) if Settings.splitOutput { // Simple round robin writers[wIndex].Write(buf[0:nr]) wIndex++ if wIndex >= len(writers) { wIndex = 0 } } else { for _, dst := range writers { dst.Write(buf[0:nr]) } } } if er == io.EOF { break } if er != nil { err = er break } } return err }
Use CachingConnectionFactory when creating Rabbit connections Change-Id: I1b56a6c701d35dbf5823e342d43f1a778e38e528
package org.cloudfoundry.runtime.service.messaging; import org.cloudfoundry.runtime.env.CloudEnvironment; import org.cloudfoundry.runtime.env.RabbitServiceInfo; import org.cloudfoundry.runtime.service.AbstractServiceCreator; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; /** * Simplified access to creating RabbitMQ service objects. * * @author Ramnivas Laddad * @author Dave Syer * */ public class RabbitServiceCreator extends AbstractServiceCreator<ConnectionFactory, RabbitServiceInfo> { public RabbitServiceCreator(CloudEnvironment cloudEnvironment) { super(cloudEnvironment, RabbitServiceInfo.class); } public ConnectionFactory createService(RabbitServiceInfo serviceInfo) { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(serviceInfo.getHost()); connectionFactory.setVirtualHost(serviceInfo.getVirtualHost()); connectionFactory.setUsername(serviceInfo.getUserName()); connectionFactory.setPassword(serviceInfo.getPassword()); connectionFactory.setPort(serviceInfo.getPort()); return connectionFactory; } }
package org.cloudfoundry.runtime.service.messaging; import org.cloudfoundry.runtime.env.CloudEnvironment; import org.cloudfoundry.runtime.env.RabbitServiceInfo; import org.cloudfoundry.runtime.service.AbstractServiceCreator; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.connection.SingleConnectionFactory; /** * Simplified access to creating RabbitMQ service objects. * * @author Ramnivas Laddad * */ public class RabbitServiceCreator extends AbstractServiceCreator<ConnectionFactory, RabbitServiceInfo> { public RabbitServiceCreator(CloudEnvironment cloudEnvironment) { super(cloudEnvironment, RabbitServiceInfo.class); } public ConnectionFactory createService(RabbitServiceInfo serviceInfo) { SingleConnectionFactory connectionFactory = new SingleConnectionFactory(serviceInfo.getHost()); connectionFactory.setVirtualHost(serviceInfo.getVirtualHost()); connectionFactory.setUsername(serviceInfo.getUserName()); connectionFactory.setPassword(serviceInfo.getPassword()); connectionFactory.setPort(serviceInfo.getPort()); return connectionFactory; } }
Fix the bug hidden in astring plugin
import astring from 'astring'; // Create a custom generator that inherits from Astring's default generator const customGenerator = Object.assign({}, astring.defaultGenerator, { Literal(node, state) { if (node.raw != null) { const first = node.raw.charAt(0).charCodeAt(); const last = node.raw.charAt(node.raw.length - 1).charCodeAt(); if ((first === 12300 && last === 12301) // 「」 || (first === 8216 && last === 8217)) { // ‘’ state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`); } else if ((first === 12302 && last === 12303) // 『』 || (first === 8220 && last === 8221)) { // “” state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`); } else if ((first === 34 && last === 34) || (first === 39 && last === 39)) { // "" or '' state.output.write(node.raw); } else { // HaLang-specific string literals state.output.write(node.value); } } else if (node.regex != null) { this.RegExpLiteral(node, state); } else { state.output.write(JSON.stringify(node.value)); } }, }); export default customGenerator;
import astring from 'astring'; // Create a custom generator that inherits from Astring's default generator const customGenerator = Object.assign({}, astring.defaultGenerator, { Literal(node, state) { if (node.raw != null) { const first = node.raw.charAt(0); const last = node.raw.charAt(node.raw.length - 1); if ((first === 12300 && last === 12301) // 「」 || (first === 8216 && last === 8217)) { // ‘’ state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`); } if ((first === 12302 && last === 12303) // 『』 || (first === 8220 && last === 8221)) { // “” state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`); } if ((first === 34 && last === 34) || (first === 39 && last === 39)) { // "" or '' state.output.write(node.raw); } else { // HaLang-specific string literals state.output.write(node.value); } } else if (node.regex != null) { this.RegExpLiteral(node, state); } else { state.output.write(JSON.stringify(node.value)); } }, }); export default customGenerator;
Add databaseinfra get engine name
# -*- coding: utf-8 -*- class DatabaseAsAServiceApi(object): def __init__(self, databaseinfra): self.databaseinfra = databaseinfra self.driver = self.get_databaseinfra_driver() self.database_instances = self.get_database_instances() def get_all_instances(self, ): return self.databaseinfra.instances.all() def get_databaseinfra_driver(self): return self.databaseinfra.get_driver() def get_database_instances(self): return self.driver.get_database_instances() def get_non_database_instances(self,): return self.driver.get_non_database_instances() def get_hosts(self,): instances = self.get_all_instances() return list(set([instance.hostname for instance in instances])) def get_environment(self): return self.databaseinfra.environment def get_databaseifra_name(self): return self.databaseinfra.name def get_databaseinfra_secondary_ips(self): return self.databaseinfra.cs_dbinfra_attributes.all() def get_databaseinfra_availability(self): return self.databaseinfra.plan.is_ha def get_databaseinfra_engine_name(self): return self.databaseinfra.engine.engine_type.name
# -*- coding: utf-8 -*- class DatabaseAsAServiceApi(object): def __init__(self, databaseinfra): self.databaseinfra = databaseinfra self.driver = self.get_databaseinfra_driver() self.database_instances = self.get_database_instances() def get_all_instances(self, ): return self.databaseinfra.instances.all() def get_databaseinfra_driver(self): return self.databaseinfra.get_driver() def get_database_instances(self): return self.driver.get_database_instances() def get_non_database_instances(self,): return self.driver.get_non_database_instances() def get_hosts(self,): instances = self.get_all_instances() return list(set([instance.hostname for instance in instances])) def get_environment(self): return self.databaseinfra.environment def get_databaseifra_name(self): return self.databaseinfra.name def get_databaseinfra_secondary_ips(self): return self.databaseinfra.cs_dbinfra_attributes.all() def get_databaseinfra_availability(self): return self.databaseinfra.plan.is_ha
Add known location for HIT when loading pyhit (refs #17108)
import os import sys import subprocess import mooseutils moose_dir = mooseutils.git_root_dir(os.path.dirname(__file__)) status = mooseutils.git_submodule_status(moose_dir) # Use framework/contrib/hit because moosetools submodule is not available if status['moosetools'] == '-': hit_dir = os.path.join(moose_dir, 'framework', 'contrib', 'hit') sys.path.append(hit_dir) try: import hit except: moose_test_dir = os.path.abspath(os.path.join(moose_dir, 'test')) subprocess.run(['make', 'hit'], cwd=moose_test_dir) import hit # Use hit in moosetools submodule else: hit_dir = os.path.join(moose_dir, 'moosetools', 'contrib', 'hit') sys.path.append(hit_dir) try: import hit except: subprocess.run(['make', 'hit.so'], cwd=hit_dir) import hit from hit import TokenType, Token from .pyhit import Node, load, write, parse, tokenize
import os import sys import subprocess import mooseutils moose_dir = mooseutils.git_root_dir(os.path.dirname(__file__)) status = mooseutils.git_submodule_status(moose_dir) # Use framework/contrib/hit because moosetools submodule is not available if status['moosetools'] == '-': try: from . import hit except: moose_test_dir = os.path.abspath(os.path.join(moose_dir, 'test')) subprocess.run(['make', 'hit'], cwd=moose_test_dir) from . import hit # Use hit in moosetools submodule else: hit_dir = os.path.join(moose_dir, 'moosetools', 'contrib', 'hit') try: sys.path.append(hit_dir) import hit except: subprocess.run(['make', 'hit.so'], cwd=hit_dir) import hit from hit import TokenType, Token from .pyhit import Node, load, write, parse, tokenize
Use synchronous writes in node runtime. Fixes #3408
var i$putStr = (function() { var fs = require('fs'); return function(s) { fs.writeSync(1,s); }; })(); var i$getLine = (function() { var fs = require( "fs" ) return function() { var ret = ""; var b = new Buffer(1024); var i = 0; while(true) { fs.readSync(0, b, i, 1 ) if (b[i] == 10) { ret = b.toString('utf8', 0, i); break; } i++; if (i == b.length) { nb = new Buffer (b.length*2); b.copy(nb) b = nb; } } return ret; }; })(); var i$systemInfo = function(index) { var os = require('os') switch(index) { case 0: return "node"; case 1: return os.platform(); } return ""; }
var i$putStr = (function() { var fs = require('fs'); return function(s) { fs.write(1,s); }; })(); var i$getLine = (function() { var fs = require( "fs" ) return function() { var ret = ""; var b = new Buffer(1024); var i = 0; while(true) { fs.readSync(0, b, i, 1 ) if (b[i] == 10) { ret = b.toString('utf8', 0, i); break; } i++; if (i == b.length) { nb = new Buffer (b.length*2); b.copy(nb) b = nb; } } return ret; }; })(); var i$systemInfo = function(index) { var os = require('os') switch(index) { case 0: return "node"; case 1: return os.platform(); } return ""; }
Fix breaking change in RN 47
package io.palette; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; public class RNPalettePackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNPaletteModule(reactContext)); } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package io.palette; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; public class RNPalettePackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNPaletteModule(reactContext)); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Fix and ungodly number of linter errors
angular.module('achievements.controller', []) .controller('AchievementsController', function ($scope) { $scope.gold = 15; // Place holder for user-specific data $scope.silver = 13; // Place holder for user-specific data $scope.bronze = 5; // Place holder for user-specific data var medalCounts = [ $scope.gold.toString(), $scope.silver.toString(), $scope.bronze.toString() ]; $scope.incrementCounts = function (width) { selection = d3.select("body") .selectAll("span.number") .data(medalCounts); selection.transition() .tween("html", function (d) { var i = d3.interpolate(this.textContent, d); return function (t) { this.textContent = Math.round(i(t)); }; }) .duration(1500) .style('width', width + 'px'); }; $scope.incrementCounts(); });
angular.module('achievements.controller', []) .controller('AchievementsController', function($scope) { $scope.gold = 15; // Place holder for user-specific data $scope.silver = 13; // Place holder for user-specific data $scope.bronze = 5; // Place holder for user-specific data var medalCounts = [$scope.gold.toString(), $scope.silver.toString(), $scope.bronze.toString()]; $scope.incrementCounts = function(width) { selection = d3.select("body").selectAll("span.number").data(medalCounts); selection.transition() .tween("html", function(d) { var i = d3.interpolate(this.textContent, d); return function(t) { this.textContent = Math.round(i(t)); }; }) .duration(1500) .style('width', width + 'px') } $scope.incrementCounts(); });
Refactor setting of request body Code could be tidied up to not use Object.assign
const { pick, pickBy } = require('lodash') const { search } = require('../../search/services') const { transformApiResponseToSearchCollection } = require('../../search/transformers') const { transformContactToListItem } = require('../transformers') const removeArray = require('../../../lib/remove-array') async function getContactsCollection (req, res, next) { try { res.locals.results = await search({ searchEntity: 'contact', requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }) .then(transformApiResponseToSearchCollection( { query: req.query }, transformContactToListItem, )) next() } catch (error) { next(error) } } function getRequestBody (req, res, next) { const selectedFiltersQuery = removeArray(pick(req.query, [ 'archived', 'name', 'company_name', 'company_sector_descends', 'address_country', 'company_uk_region', ]), 'archived') const selectedSortBy = req.query.sortby ? { sortby: req.query.sortby } : null req.body = { ...req.body, ...selectedSortBy, ...pickBy(selectedFiltersQuery), } next() } module.exports = { getContactsCollection, getRequestBody, }
const { pick, pickBy } = require('lodash') const { search } = require('../../search/services') const { transformApiResponseToSearchCollection } = require('../../search/transformers') const { transformContactToListItem } = require('../transformers') const removeArray = require('../../../lib/remove-array') async function getContactsCollection (req, res, next) { try { res.locals.results = await search({ searchEntity: 'contact', requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }) .then(transformApiResponseToSearchCollection( { query: req.query }, transformContactToListItem, )) next() } catch (error) { next(error) } } function getRequestBody (req, res, next) { const selectedFiltersQuery = removeArray(pick(req.query, [ 'archived', 'name', 'company_name', 'company_sector_descends', 'address_country', 'company_uk_region', ]), 'archived') const selectedSortBy = req.query.sortby ? { sortby: req.query.sortby } : null req.body = Object.assign({}, req.body, selectedSortBy, pickBy(selectedFiltersQuery)) next() } module.exports = { getContactsCollection, getRequestBody, }
Make Python example output identical to C++ and Java by removing redundant spaces.
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #:", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #:", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #:", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
#! /usr/bin/python # See README.txt for information and build instructions. import addressbook_pb2 import sys # Iterates though all people in the AddressBook and prints info about them. def ListPeople(address_book): for person in address_book.person: print "Person ID:", person.id print " Name:", person.name if person.HasField('email'): print " E-mail address:", person.email for phone_number in person.phone: if phone_number.type == addressbook_pb2.Person.MOBILE: print " Mobile phone #: ", elif phone_number.type == addressbook_pb2.Person.HOME: print " Home phone #: ", elif phone_number.type == addressbook_pb2.Person.WORK: print " Work phone #: ", print phone_number.number # Main procedure: Reads the entire address book from a file and prints all # the information inside. if len(sys.argv) != 2: print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE" sys.exit(-1) address_book = addressbook_pb2.AddressBook() # Read the existing address book. f = open(sys.argv[1], "rb") address_book.ParseFromString(f.read()) f.close() ListPeople(address_book)
Fix scaleCategory prop types and docs Have recently been renamed.
import React from 'react'; import PropTypes from 'prop-types'; import styles from './Text.module.css'; /** * Render some text using the default typography scale. * * @param {Object} props * @param {string} props.scaleCategory - * One of the styles `'heading-lg'`, `'heading-md'`, `'heading-sm'`, * `'heading-xs'`, `'body'`, `'caption'`. * @param {string} [props.inline] - Render a span instread of a div. * @param {string} props.children - Nodes to render with specified typography. */ export function Text({inline, scaleCategory, children}) { return React.createElement(inline ? 'span' : 'div', {className: styles[scaleCategory]}, children); } Text.propTypes = { children: PropTypes.node.isRequired, inline: PropTypes.bool, scaleCategory: PropTypes.oneOf([ 'heading-lg', 'heading-md', 'heading-sm', 'heading-xs', 'body', 'caption' ]), }
import React from 'react'; import PropTypes from 'prop-types'; import styles from './Text.module.css'; /** * Render some text using the default typography scale. * * @param {Object} props * @param {string} props.scaleCategory - * One of the styles `'h1'`, `'h1-medium'`, `'h2'`, `'h3'`, `'body'`, `'caption'`. * @param {string} [props.inline] - Render a span instread of a div. * @param {string} props.children - Nodes to render with specified typography. */ export function Text({inline, scaleCategory, children}) { return React.createElement(inline ? 'span' : 'div', {className: styles[scaleCategory]}, children); } Text.propTypes = { children: PropTypes.node.isRequired, inline: PropTypes.bool, scaleCategory: PropTypes.oneOf(['h1', 'h1-medium', 'h2', 'body', 'caption']), }
FIX user are sorted case insensitive
<?php class Default_Model_UserMapper extends Default_Model_AbstractMapper { public function findNickname($nickname) { $select = $this->getDbTable()->select() ->where('nickname = ?', $nickname); $record = $this->getDbTable()->fetchRow($select); return $record; } public function findEmailPassword($email, $password) { $select = $this->getDbTable()->select() ->where('email = ?', $email) ->where('password = ?', $password); $record = $this->getDbTable()->fetchRow($select); return $record; } public function find($id) { $result = $this->getDbTable()->find($id); return $result->current(); } public function fetchAll() { $resultSet = $this->getDbTable()->fetchAll(null, 'LOWER(nickname)'); return $resultSet; } } ?>
<?php class Default_Model_UserMapper extends Default_Model_AbstractMapper { public function findNickname($nickname) { $select = $this->getDbTable()->select() ->where('nickname = ?', $nickname); $record = $this->getDbTable()->fetchRow($select); return $record; } public function findEmailPassword($email, $password) { $select = $this->getDbTable()->select() ->where('email = ?', $email) ->where('password = ?', $password); $record = $this->getDbTable()->fetchRow($select); return $record; } public function find($id) { $result = $this->getDbTable()->find($id); return $result->current(); } public function fetchAll() { $resultSet = $this->getDbTable()->fetchAll(null, 'nickname'); return $resultSet; } } ?>
Use es.through instead of es.map See https://github.com/gulpjs/gulp/issues/75#issuecomment-31581317 Partial results for continue-on-error behaviour.
var es = require('event-stream'); var coffee = require('coffee-script'); var gutil = require('gulp-util'); var formatError = require('./lib/formatError'); var Buffer = require('buffer').Buffer; module.exports = function(opt){ function modifyFile(file){ if (file.isNull()) return this.emit('data', file); // pass along if (file.isStream()) return this.emit('error', new Error("gulp-coffee: Streaming not supported")); var str = file.contents.toString('utf8'); try { file.contents = new Buffer(coffee.compile(str, opt)); } catch (err) { var newError = formatError(file, err); return this.emit('error', newError); } file.path = gutil.replaceExtension(file.path, ".js"); this.emit('data', file); } return es.through(modifyFile); };
var es = require('event-stream'); var coffee = require('coffee-script'); var gutil = require('gulp-util'); var formatError = require('./lib/formatError'); var Buffer = require('buffer').Buffer; module.exports = function(opt){ function modifyFile(file, cb){ if (file.isNull()) return cb(null, file); // pass along if (file.isStream()) return cb(new Error("gulp-coffee: Streaming not supported")); var str = file.contents.toString('utf8'); try { file.contents = new Buffer(coffee.compile(str, opt)); } catch (err) { var newError = formatError(file, err); return cb(newError); } file.path = gutil.replaceExtension(file.path, ".js"); cb(null, file); } return es.map(modifyFile); };
Create anchor tag for logout
import React from 'react' class LessonData extends React.Component { constructor(props){ super(props); this.state = { lessonId: this.props.params.lessonId, className: 'get this from the DB query', polls: ['get this from the DB query'] }; } render(){ return (<div> <h2>{this.state.className}</h2> <p>Polls for {this.state.className}</p> <button>Add thumbs check</button> <button>Add multiple choice</button> </div>) } componentWillMount(){ //get the poll responses from the lessonId given in the URL param //set the className from the DB query } const AddPoll = (hide) => { // add to state // post to DB return ( <div> <button>Thumbs Check</button> <button>Multiple Choice</button> </div> ) }; module.exports = LessonData;
import React from 'react' class LessonData extends React.Component { constructor(props){ super(props); this.state = { lessonId: this.props.params.lessonId, className: 'get this from the DB query', polls: ['get this from the DB query'] }; } render(){ return (<div> <h2>{this.state.className}</h2> <p>Polls for {this.state.className}</p> </div>) } componentWillMount(){ //get the poll responses from the lessonId given in the URL param //set the className from the DB query } const AddPoll = (hide) => { // add to state // post to DB return ( <div> <button>Thumbs Check</button> <button>Multiple Choice</button> </div> ) }; module.exports = LessonData;
Update dummy test with with new goto treatment version
package fr.insee.eno.main; import java.io.File; import fr.insee.eno.GenerationService; import fr.insee.eno.generation.PoguesXML2DDIGenerator; import fr.insee.eno.postprocessing.DDIPostprocessor; import fr.insee.eno.preprocessing.PoguesXMLPreprocessor; import fr.insee.eno.preprocessing.PoguesXMLPreprocessorGoToTreatment; public class DummyTestPoguesXML2DDI { public static void main(String[] args) { String basePath = "src/test/resources/pogues-xml-to-ddi"; GenerationService genService = new GenerationService(new PoguesXMLPreprocessorGoToTreatment(), new PoguesXML2DDIGenerator(), new DDIPostprocessor()); File in = new File(String.format("%s/in.xml", basePath)); try { File output = genService.generateQuestionnaire(in, "test"); System.out.println(output.getAbsolutePath()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package fr.insee.eno.main; import java.io.File; import fr.insee.eno.GenerationService; import fr.insee.eno.generation.PoguesXML2DDIGenerator; import fr.insee.eno.postprocessing.DDIPostprocessor; import fr.insee.eno.preprocessing.PoguesXMLPreprocessor; public class DummyTestPoguesXML2DDI { public static void main(String[] args) { String basePath = "src/test/resources/pogues-xml-to-ddi"; GenerationService genService = new GenerationService(new PoguesXMLPreprocessor(), new PoguesXML2DDIGenerator(), new DDIPostprocessor()); File in = new File(String.format("%s/in.xml", basePath)); try { File output = genService.generateQuestionnaire(in, "test"); System.out.println(output.getAbsolutePath()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Support CORS wildcard for serverless function
'use strict' const { ApolloServer } = require('apollo-server-lambda') const { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, DateTimeTypeDefinition } = require('graphql-scalars') const connect = require('../src/utils/connect') const isDemoMode = require('../src/utils/isDemoMode') const isDevelopmentMode = require('../src/utils/isDevelopmentMode') const { createServerlessContext } = require('../src/utils/createContext') const allowOrigin = process.env.ACKEE_ALLOW_ORIGIN || '' const dbUrl = process.env.ACKEE_MONGODB || process.env.MONGODB_URI if (dbUrl == null) { throw new Error('MongoDB connection URI missing in environment') } connect(dbUrl) const apolloServer = new ApolloServer({ introspection: isDemoMode === true || isDevelopmentMode === true, playground: isDemoMode === true || isDevelopmentMode === true, debug: isDevelopmentMode === true, cors: { origin: allowOrigin === '*' ? true : allowOrigin.split(','), methods: 'GET,POST,PATCH,OPTIONS', allowedHeaders: 'Content-Type' }, typeDefs: [ UnsignedIntTypeDefinition, DateTimeTypeDefinition, require('../src/types') ], resolvers: { UnsignedInt: UnsignedIntResolver, DateTime: DateTimeResolver, ...require('../src/resolvers') }, context: createServerlessContext }) exports.handler = apolloServer.createHandler()
'use strict' const { ApolloServer } = require('apollo-server-lambda') const { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, DateTimeTypeDefinition } = require('graphql-scalars') const connect = require('../src/utils/connect') const isDemoMode = require('../src/utils/isDemoMode') const isDevelopmentMode = require('../src/utils/isDevelopmentMode') const { createServerlessContext } = require('../src/utils/createContext') const allowOrigin = process.env.ACKEE_ALLOW_ORIGIN || '' const dbUrl = process.env.ACKEE_MONGODB || process.env.MONGODB_URI if (dbUrl == null) { throw new Error('MongoDB connection URI missing in environment') } connect(dbUrl) const apolloServer = new ApolloServer({ introspection: isDemoMode === true || isDevelopmentMode === true, playground: isDemoMode === true || isDevelopmentMode === true, debug: isDevelopmentMode === true, cors: { origin: allowOrigin.split(','), methods: 'GET,POST,PATCH,OPTIONS', allowedHeaders: 'Content-Type' }, typeDefs: [ UnsignedIntTypeDefinition, DateTimeTypeDefinition, require('../src/types') ], resolvers: { UnsignedInt: UnsignedIntResolver, DateTime: DateTimeResolver, ...require('../src/resolvers') }, context: createServerlessContext }) exports.handler = apolloServer.createHandler()
Add missing timestamps database table fields
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttributeEntityTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create(config('rinvex.attributable.tables.attribute_entity'), function (Blueprint $table) { // Columns $table->integer('attribute_id')->unsigned(); $table->string('entity_type'); $table->timestamps(); // Indexes $table->unique(['attribute_id', 'entity_type'], 'attributable_attribute_id_entity_type'); $table->foreign('attribute_id')->references('id')->on(config('rinvex.attributable.tables.attributes')) ->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('rinvex.attributable.tables.attribute_entity')); } }
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAttributeEntityTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create(config('rinvex.attributable.tables.attribute_entity'), function (Blueprint $table) { // Columns $table->integer('attribute_id')->unsigned(); $table->string('entity_type'); // Indexes $table->unique(['attribute_id', 'entity_type'], 'attributable_attribute_id_entity_type'); $table->foreign('attribute_id')->references('id')->on(config('rinvex.attributable.tables.attributes')) ->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('rinvex.attributable.tables.attribute_entity')); } }
Change hunger values for beef pattie
package net.shadowfacts.foodies.item; import cpw.mods.fml.common.registry.GameRegistry; /** * Helper class for registering items. * @author shadowfacts */ public class FItems { // Foods public static Food toast; public static Food tomato; public static Food beefPattie; public static Food hamburger; public static void preInit() { // Create Items toast = new Food(3, 0.3f).setUnlocalizedName("foodToast").setTextureName("foodToast"); tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato"); beefPattie = new Food(3, 0.6f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie"); hamburger = new Food(5, 0.7f).setUnlocalizedName("foodHamburger").setTextureName("foodHamburger"); // Register items GameRegistry.registerItem(toast, "foodToast"); GameRegistry.registerItem(tomato, "fruitTomato"); GameRegistry.registerItem(beefPattie, "foodBeefPattie"); GameRegistry.registerItem(hamburger, "foodHamburger"); } public static void load() { } public static void postInit() { } }
package net.shadowfacts.foodies.item; import cpw.mods.fml.common.registry.GameRegistry; /** * Helper class for registering items. * @author shadowfacts */ public class FItems { // Foods public static Food toast; public static Food tomato; public static Food beefPattie; public static Food hamburger; public static void preInit() { // Create Items toast = new Food(3, 0.3f).setUnlocalizedName("foodToast").setTextureName("foodToast"); tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato"); beefPattie = new Food(7, 0.4f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie"); hamburger = new Food(5, 0.7f).setUnlocalizedName("foodHamburger").setTextureName("foodHamburger"); // Register items GameRegistry.registerItem(toast, "foodToast"); GameRegistry.registerItem(tomato, "fruitTomato"); GameRegistry.registerItem(beefPattie, "foodBeefPattie"); GameRegistry.registerItem(hamburger, "foodHamburger"); } public static void load() { } public static void postInit() { } }
Fix wrong scaling of lessons in module detail view
package org.pma.nutrifami.activity; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import org.pma.nutrifami.R; import org.pma.nutrifami.adapter.LessonPagePagerAdaptor; import org.pma.nutrifami.lib.ModuleManager; import org.pma.nutrifami.model.Module; import me.crosswall.lib.coverflow.CoverFlow; public class ModuleActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_module_carousel); ModuleManager moduleManager = ModuleManager.getInstance(); // TODO: Get real module Module module = moduleManager.getModules()[0]; ViewPager mPager = (ViewPager) findViewById(R.id.lesson_page_pager); mPager.setOffscreenPageLimit(2); PagerAdapter mPagerAdapter = new LessonPagePagerAdaptor(getSupportFragmentManager(), module); mPager.setAdapter(mPagerAdapter); new CoverFlow.Builder() .with(mPager) .scale(0.15f) .build(); } }
package org.pma.nutrifami.activity; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import org.pma.nutrifami.R; import org.pma.nutrifami.adapter.LessonPagePagerAdaptor; import org.pma.nutrifami.lib.ModuleManager; import org.pma.nutrifami.model.Module; import me.crosswall.lib.coverflow.CoverFlow; public class ModuleActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_module_carousel); ModuleManager moduleManager = ModuleManager.getInstance(); // TODO: Get real module Module module = moduleManager.getModules()[0]; ViewPager mPager = (ViewPager) findViewById(R.id.lesson_page_pager); PagerAdapter mPagerAdapter = new LessonPagePagerAdaptor(getSupportFragmentManager(), module); mPager.setAdapter(mPagerAdapter); new CoverFlow.Builder() .with(mPager) .scale(0.15f) .build(); } }
Fix Ghost execution bug and multiple execution bug http://www.concrete5.org/developers/bugs/5-6-2-1/ghost-execution-of-queuable-jobs/ http://www.concrete5.org/developers/bugs/5-6-2-1/slices-of-many-queable-jobs-could-be-executed-together/
<? defined('C5_EXECUTE') or die("Access Denied."); if (!ini_get('safe_mode')) { @set_time_limit(0); } $json = Loader::helper('json'); if (Job::authenticateRequest($_REQUEST['auth'])) { $list = Job::getList(); foreach($list as $job) { if ($job->supportsQueue()) { $q = $job->getQueueObject(); // don't process queues that are empty if($q->count() <1){ continue; } $obj = new stdClass; $js = Loader::helper('json'); try { $messages = $q->receive($job->getJobQueueBatchSize()); foreach($messages as $key => $p) { $job->processQueueItem($p); $q->deleteMessage($p); } $totalItems = $q->count(); $obj->totalItems = $totalItems; if ($q->count() == 0) { $result = $job->finish($q); $obj = $job->markCompleted(0, $result); $obj->totalItems = $totalItems; } } catch(Exception $e) { $obj = $job->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage()); $obj->message = $obj->result; // needed for progressive library. } print $js->encode($obj); // End when one queue has processed a batch step break; } } }
<? defined('C5_EXECUTE') or die("Access Denied."); if (!ini_get('safe_mode')) { @set_time_limit(0); } $json = Loader::helper('json'); if (Job::authenticateRequest($_REQUEST['auth'])) { $list = Job::getList(); foreach($list as $job) { if ($job->supportsQueue()) { $q = $job->getQueueObject(); $obj = new stdClass; $js = Loader::helper('json'); try { $messages = $q->receive($job->getJobQueueBatchSize()); foreach($messages as $key => $p) { $job->processQueueItem($p); $q->deleteMessage($p); } $totalItems = $q->count(); $obj->totalItems = $totalItems; if ($q->count() == 0) { $result = $job->finish($q); $obj = $job->markCompleted(0, $result); $obj->totalItems = $totalItems; } } catch(Exception $e) { $obj = $job->markCompleted(Job::JOB_ERROR_EXCEPTION_GENERAL, $e->getMessage()); $obj->message = $obj->result; // needed for progressive library. } print $js->encode($obj); } } }