text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change the programme to avoid error, NEED TO BE FIXED
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;
public class Programme {
public static void main(String[] args) throws FileNotFoundException {
ArrayList array = new ArrayList<Double>();
Scanner lineReader = new Scanner(new File("data/EURUSD.dat"));
while(lineReader.hasNext()){
String line = lineReader.nextLine();
String[] tmp = line.split("/")[0].split(" ");
array.add(Double.parseDouble(tmp[tmp.length - 1]));
}
ARL arl = new ARL(13);
// arl.loop(array.subList(200000,260000), 1000);
// arl.loop(array.subList(260000,270000), 1000);
System.out.println(arl.toString());
}
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;
public class Programme {
public static void main(String[] args) throws FileNotFoundException {
ArrayList array = new ArrayList<Double>();
Scanner lineReader = new Scanner(new File("data/EURUSD.dat"));
while(lineReader.hasNext()){
String line = lineReader.nextLine();
String[] tmp = line.split("/")[0].split(" ");
array.add(Double.parseDouble(tmp[tmp.length - 1]));
}
ARL arl = new ARL(13);
arl.loop(array.subList(200000,260000), false, 1000);
arl.loop(array.subList(260000,270000), true, 1000);
System.out.println(arl.toString());
}
}
|
Refactor to create role if not existing
|
Meteor.methods({
"createRoleIfNotExisting": function (roleName) {
/*
Check if a given role exists
create the role if it doesn't exist
*/
// Placeholder variable for role check
var roleExists;
// Get all existing roles
var roles = Meteor.roles.find().fetch();
// Flatten the roles to an array of role names
var roleNames = _.map(roles, function (role) {
// Return the name of the role
return role.name;
});
// Check if admin role is defined in Roles collection
roleExists = _.contains(roleNames, roleName);
// Create the admin role if it is not already defined
if (!roleExists) {
console.log('Defining "' + roleName + '" role.');
Roles.createRole(roleName);
}
}
});
|
Meteor.methods({
"createAdminRoleIfNotDefined": function () {
// TODO: Refactor this process to allow user to specify admin role as parameter
// E.g. a config page where the user can input the desired string
// Define the admin role
var adminRole = 'admin';
// Placeholder variable for admin check
var adminIsDefined;
// Get all existing roles
var roles = Roles.getAllRoles().fetch();
// Flatten the roles to an array of role names
var roleNames = _.map(roles, function (role) {
// Return the name of the role
return role.name;
});
// Check if admin role is defined in Roles collection
adminIsDefined = _.contains(roleNames, adminRole);
// Create the admin role if it is not already defined
if (!adminIsDefined) {
console.log('Defining "' + adminRole + '" role.');
Roles.createRole(adminRole);
}
}
});
|
Improve formatting for NoIdItem in ResultSet tests
|
from .config import TweepyTestCase
from tweepy.models import ResultSet
class NoIdItem:
pass
class IdItem:
def __init__(self, id):
self.id = id
ids_fixture = [1, 10, 8, 50, 2, 100, 5]
class TweepyResultSetTests(TweepyTestCase):
def setUp(self):
self.results = ResultSet()
for i in ids_fixture:
self.results.append(IdItem(i))
self.results.append(NoIdItem())
def testids(self):
ids = self.results.ids()
self.assertListEqual(ids, ids_fixture)
def testmaxid(self):
self.assertEqual(self.results.max_id, 0)
def testsinceid(self):
self.assertEqual(self.results.since_id, 100)
|
from .config import TweepyTestCase
from tweepy.models import ResultSet
class NoIdItem: pass
class IdItem:
def __init__(self, id):
self.id = id
ids_fixture = [1, 10, 8, 50, 2, 100, 5]
class TweepyResultSetTests(TweepyTestCase):
def setUp(self):
self.results = ResultSet()
for i in ids_fixture:
self.results.append(IdItem(i))
self.results.append(NoIdItem())
def testids(self):
ids = self.results.ids()
self.assertListEqual(ids, ids_fixture)
def testmaxid(self):
self.assertEqual(self.results.max_id, 0)
def testsinceid(self):
self.assertEqual(self.results.since_id, 100)
|
Use the session user to fetch org repos
|
/*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';
require("babel/register");
var GitHub = require('../github');
var redis = require('../redis');
var Repo = require('../repo');
module.exports = function(req, res) {
var owner = req.params.owner;
var name = req.params.repo;
return redis.get(req.session.user)
.then( (token) => {
var gh = new GitHub(token);
var repo = new Repo(owner, name, gh);
return repo.findDependencies()
.then( (manifests) => {
return Promise.all([
repo.fetchVersions(manifests),
gh.get(`/repos/${owner}/${name}`)
]);
})
.then( (values) => {
let [manifests, _repo] = values;
res.render('repo', {repo: _repo, manifests: manifests});
});
})
.catch( (err) => {
console.log(err);
console.log(err.stack);
res.render('error');
});
};
|
/*jshint strict:true, trailing:false, unused:true, node:true */
'use strict';
require("babel/register");
var GitHub = require('../github');
var redis = require('../redis');
var Repo = require('../repo');
module.exports = function(req, res) {
var owner = req.params.owner;
var name = req.params.repo;
return redis.get(owner)
.then( (token) => {
var gh = new GitHub(token);
var repo = new Repo(owner, name, gh);
return repo.findDependencies()
.then( (manifests) => {
return Promise.all([
repo.fetchVersions(manifests),
gh.get(`/repos/${owner}/${name}`)
]);
})
.then( (values) => {
let [manifests, _repo] = values;
res.render('repo', {repo: _repo, manifests: manifests});
});
})
.catch( (err) => {
console.log(err.stack);
res.render('error');
});
};
|
Fix travis testing on node < 8
|
const gulp = require('gulp');
const util = require('gulp-util');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const src = 'src/index.js';
gulp.task('lint', () => (
gulp.src([src, 'test/*.js'])
.pipe(eslint())
.pipe(eslint.format())
));
gulp.task('test', ['lint'], () => (
gulp.src('test')
.pipe(mocha())
.on('error', util.log)
));
gulp.task('build', ['test'], () => (
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest('dist'))
));
gulp.task('watch', () => {
gulp.watch(src, ['test']);
});
gulp.task('develop', ['watch']);
gulp.task('default', ['develop']);
|
const gulp = require('gulp');
const util = require('gulp-util');
const babel = require('gulp-babel');
const mocha = require('gulp-mocha');
const eslint = require('gulp-eslint');
const src = 'src/index.js';
gulp.task('lint', () =>
gulp.src([src, 'test/*.js'])
.pipe(eslint())
.pipe(eslint.format()),
);
gulp.task('test', ['lint'], () => (
gulp.src('test')
.pipe(mocha())
.on('error', util.log)
));
gulp.task('build', ['test'], () => (
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest('dist'))
));
gulp.task('watch', () => {
gulp.watch(src, ['test']);
});
gulp.task('develop', ['watch']);
gulp.task('default', ['develop']);
|
Fix import in test loot tables provider
|
package info.u_team.u_team_test.data.provider;
import java.util.function.BiConsumer;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
import net.minecraft.loot.LootTable;
import net.minecraft.util.ResourceLocation;
public class TestLootTablesProvider extends CommonLootTablesProvider {
public TestLootTablesProvider(GenerationData data) {
super(data);
}
@Override
protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) {
registerBlock(TestBlocks.BASIC, addFortuneBlockLootTable(TestBlocks.BASIC.get(), TestItems.BASIC.get()), consumer);
registerBlock(TestBlocks.BASIC_TILEENTITY, addTileEntityBlockLootTable(TestBlocks.BASIC_TILEENTITY.get()), consumer);
registerBlock(TestBlocks.BASIC_ENERGY_CREATOR, addTileEntityBlockLootTable(TestBlocks.BASIC_ENERGY_CREATOR.get()), consumer);
registerBlock(TestBlocks.BASIC_FLUID_INVENTORY, addTileEntityBlockLootTable(TestBlocks.BASIC_FLUID_INVENTORY.get()), consumer);
}
}
|
package info.u_team.u_team_test.data.provider;
import java.util.function.BiConsumer;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootTable;
public class TestLootTablesProvider extends CommonLootTablesProvider {
public TestLootTablesProvider(GenerationData data) {
super(data);
}
@Override
protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) {
registerBlock(TestBlocks.BASIC, addFortuneBlockLootTable(TestBlocks.BASIC.get(), TestItems.BASIC.get()), consumer);
registerBlock(TestBlocks.BASIC_TILEENTITY, addTileEntityBlockLootTable(TestBlocks.BASIC_TILEENTITY.get()), consumer);
registerBlock(TestBlocks.BASIC_ENERGY_CREATOR, addTileEntityBlockLootTable(TestBlocks.BASIC_ENERGY_CREATOR.get()), consumer);
registerBlock(TestBlocks.BASIC_FLUID_INVENTORY, addTileEntityBlockLootTable(TestBlocks.BASIC_FLUID_INVENTORY.get()), consumer);
}
}
|
Remove JS to not load hidden divs
|
// $(function () {
// $("img").not(":visible").each(function () {
// $(this).data("src", this.src);
// this.src = "";
// });
// var reveal = function (selector) {
// var img = $(selector);
// img[0].src = img.data("src");
// }
// });
$("#post_link6").click(function() {
event.preventDefault();
$( ".post.6" ).slideToggle( "slow" );
});
$("#post_link5").click(function() {
event.preventDefault();
$( ".post.5" ).slideToggle( "slow" );
});
$("#post_link4").click(function() {
event.preventDefault();
$( ".post.4" ).slideToggle( "slow" );
});
$("#post_link3").click(function() {
event.preventDefault();
$( ".post.3" ).slideToggle( "slow" );
});
$("#post_link2").click(function() {
event.preventDefault();
$( ".post.2" ).slideToggle( "slow" );
});
$("#post_link1").click(function() {
event.preventDefault();
$( ".post.1" ).slideToggle( "slow" );
});
$("#comment_box_link").click(function() {
event.preventDefault();
$( ".comment_box" ).slideToggle( "slow" );
});
|
$(function () {
$("img").not(":visible").each(function () {
$(this).data("src", this.src);
this.src = "";
});
var reveal = function (selector) {
var img = $(selector);
img[0].src = img.data("src");
}
});
$("#post_link6").click(function() {
event.preventDefault();
$( ".post.6" ).slideToggle( "slow" );
});
$("#post_link5").click(function() {
event.preventDefault();
$( ".post.5" ).slideToggle( "slow" );
});
$("#post_link4").click(function() {
event.preventDefault();
$( ".post.4" ).slideToggle( "slow" );
});
$("#post_link3").click(function() {
event.preventDefault();
$( ".post.3" ).slideToggle( "slow" );
});
$("#post_link2").click(function() {
event.preventDefault();
$( ".post.2" ).slideToggle( "slow" );
});
$("#post_link1").click(function() {
event.preventDefault();
$( ".post.1" ).slideToggle( "slow" );
});
$("#comment_box_link").click(function() {
event.preventDefault();
$( ".comment_box" ).slideToggle( "slow" );
});
|
Fix for bad merge decision
|
"""
@author: JD Chodera
@author: JH Prinz
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
from openpathsampling.engines import features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature,
toy_feats.engine
])
class ToySnapshot(BaseSnapshot):
"""
Simulation snapshot. Only references to coordinates and velocities
"""
@property
def topology(self):
return self.engine.topology
@property
def masses(self):
return self.topology.masses
# The following code does almost the same as above
# ToySnapshot = SnapshotFactory(
# name='ToySnapshot',
# features=[
# features.velocities,
# features.coordinates,
# features.engine
# ],
# description="Simulation snapshot. Only references to coordinates and "
# "velocities",
# base_class=BaseSnapshot
# )
|
"""
@author: JD Chodera
@author: JH Prinz
"""
from openpathsampling.engines import BaseSnapshot, SnapshotFactory
import openpathsampling.engines.features as feats
from . import features as toy_feats
@feats.attach_features([
toy_feats.velocities,
toy_feats.coordinates,
toy_feats.instantaneous_temperature,
toy_feats.engine
])
class ToySnapshot(BaseSnapshot):
"""
Simulation snapshot. Only references to coordinates and velocities
"""
@property
def topology(self):
return self.engine.topology
@property
def masses(self):
return self.topology.masses
# The following code does almost the same as above
# ToySnapshot = SnapshotFactory(
# name='ToySnapshot',
# features=[
# features.velocities,
# features.coordinates,
# features.engine
# ],
# description="Simulation snapshot. Only references to coordinates and "
# "velocities",
# base_class=BaseSnapshot
# )
|
RESCOI-876: Check for characters in file path
|
/*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import fs from 'fs';
import path from 'path';
const filePath = process.env.LOCAL_FILE_DESTINATION || 'uploads/';
function cleanKey(key) {
return key.replace(/(\.\.)|\/|\\/g, '');
}
export function getFile(dbInfo, key, callback) {
const stream = fs.createReadStream(path.join(filePath, cleanKey(key)));
stream.on('error', err => {
callback(err);
});
return stream;
}
export function deleteFile(key, callback) {
fs.unlink(path.join(filePath, cleanKey(key)), err => {
callback(err);
});
}
|
/*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import fs from 'fs';
import path from 'path';
const filePath = process.env.LOCAL_FILE_DESTINATION || 'uploads/';
export function getFile(dbInfo, key, callback) {
const stream = fs.createReadStream(path.join(filePath, key));
stream.on('error', err => {
callback(err);
});
return stream;
}
export function deleteFile(key, callback) {
fs.unlink(path.join(filePath, key), err => {
callback(err);
});
}
|
Define fallback case just once
|
<?php
namespace Concrete\Core\Support\Facade;
class Image extends Facade
{
public static function getFacadeAccessor()
{
if (class_exists('Imagick')) {
$imagick = new \Imagick();
$v = $imagick->getVersion();
list($version, $year, $month, $day, $q, $website) = sscanf(
$v['versionString'],
'ImageMagick %s %04d-%02d-%02d %s %s');
if (version_compare($version, '6.2.9') >= 0) {
return 'image/imagick';
}
}
return 'image/gd';
}
}
|
<?php
namespace Concrete\Core\Support\Facade;
class Image extends Facade
{
public static function getFacadeAccessor()
{
if (class_exists('Imagick')) {
$imagick = new \Imagick();
$v = $imagick->getVersion();
list($version, $year, $month, $day, $q, $website) = sscanf(
$v['versionString'],
'ImageMagick %s %04d-%02d-%02d %s %s');
if (version_compare($version, '6.2.9') < 1) {
return 'image/gd';
} else {
return 'image/imagick';
}
}
return 'image/gd';
}
}
|
Check if array index has content
|
<?php
/**
* GitScrum v0.1.
*
* @author Renato Marinho <renato.marinho@s2move.com>
* @license http://opensource.org/licenses/GPL-3.0 GPLv3
*/
namespace GitScrum\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use GitScrum\Models\Sprint;
class IssueRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
];
}
protected function getValidatorInstance()
{
$data = $this->all();
if (isset($data['slug_sprint']) && !empty($data['slug_sprint'])) {
$data['sprint_id'] = Sprint::where('slug', '=', $data['slug_sprint'])->first()->id;
unset($data['slug_sprint']);
}
$this->getInputSource()->replace($data);
return parent::getValidatorInstance();
}
}
|
<?php
/**
* GitScrum v0.1.
*
* @author Renato Marinho <renato.marinho@s2move.com>
* @license http://opensource.org/licenses/GPL-3.0 GPLv3
*/
namespace GitScrum\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use GitScrum\Models\Sprint;
class IssueRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
];
}
protected function getValidatorInstance()
{
$data = $this->all();
if (isset($data['slug_sprint'])) {
$data['sprint_id'] = Sprint::where('slug', '=', $data['slug_sprint'])->first()->id;
unset($data['slug_sprint']);
}
$this->getInputSource()->replace($data);
return parent::getValidatorInstance();
}
}
|
Fix fos user mailer generated route to be absolute
|
<?php
namespace Redking\ParseBundle\Bridge\FOSUser;
use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class Mailer extends BaseMailer
{
/**
* {@inheritdoc}
*/
public function sendResettingEmailMessage(UserInterface $user, $route = 'fos_user_resetting_reset')
{
$template = $this->parameters['template']['resetting'];
$url = $this->router->generate($route, array('token' => $user->getConfirmationToken()), UrlGeneratorInterface::ABSOLUTE_URL);
$context = array(
'user' => $user,
'confirmationUrl' => $url
);
$this->sendMessage($template, $context, $this->parameters['from_email']['resetting'], $user->getEmail());
}
}
|
<?php
namespace Redking\ParseBundle\Bridge\FOSUser;
use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use FOS\UserBundle\Model\UserInterface;
class Mailer extends BaseMailer
{
/**
* {@inheritdoc}
*/
public function sendResettingEmailMessage(UserInterface $user, $route = 'fos_user_resetting_reset')
{
$template = $this->parameters['template']['resetting'];
$url = $this->router->generate($route, array('token' => $user->getConfirmationToken()), true);
$context = array(
'user' => $user,
'confirmationUrl' => $url
);
$this->sendMessage($template, $context, $this->parameters['from_email']['resetting'], $user->getEmail());
}
}
|
Use buffered channel for graceful shutdown
According to https://golang.org/pkg/os/signal/#example_Notify
buffered channel should be used to avoid missing signal.
|
package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
)
func main() {
// Setup
e := echo.New()
e.Logger.SetLevel(log.INFO)
e.GET("/", func(c echo.Context) error {
time.Sleep(5 * time.Second)
return c.JSON(http.StatusOK, "OK")
})
// Start server
go func() {
if err := e.Start(":1323"); err != nil {
e.Logger.Info("shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 10 seconds.
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}
|
package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
)
func main() {
// Setup
e := echo.New()
e.Logger.SetLevel(log.INFO)
e.GET("/", func(c echo.Context) error {
time.Sleep(5 * time.Second)
return c.JSON(http.StatusOK, "OK")
})
// Start server
go func() {
if err := e.Start(":1323"); err != nil {
e.Logger.Info("shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 10 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}
|
fix(test-config): Change browser-name case, add browser list
|
/**
* From where to look for files, starting with the location of this file.
*/
basePath = '../';
/**
* This is the list of file patterns to load into the browser during testing.
*/
files = [
JASMINE,
JASMINE_ADAPTER,
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'src/**/*.js',
'dist/tmp/**/*.js'
];
/**
* How to report, by default.
*/
reporters = 'dots';
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port = 9018;
runnerPort = 9100;
urlRoot = '/';
/**
* Log at a very low level, but not quite debug.
*/
logLevel = LOG_INFO;
/**
* Disable file watching by default.
*/
autoWatch = false;
/**
* The list of browsers to launch to test on. This is empty by default, so you
* will need to manually open your browser to http://localhot:9018/ for the
* tests to work. Currently available browser names:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*/
browsers = [
'Firefox'
];
|
/**
* From where to look for files, starting with the location of this file.
*/
basePath = '../';
/**
* This is the list of file patterns to load into the browser during testing.
*/
files = [
JASMINE,
JASMINE_ADAPTER,
'vendor/angular/angular.js',
'vendor/angular/angular-mocks.js',
'src/**/*.js',
'dist/tmp/**/*.js'
];
/**
* How to report, by default.
*/
reporters = 'dots';
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port = 9018;
runnerPort = 9100;
urlRoot = '/';
/**
* Log at a very low level, but not quite debug.
*/
logLevel = LOG_INFO;
/**
* Disable file watching by default.
*/
autoWatch = false;
/**
* The list of browsers to launch to test on. This is empty by default, so you
* will need to manually open your browser to http://localhot:9018/ for the
* tests to work. You can also just add the executable name of your browser(s)
* here, e.g. 'firefox', 'chrome', 'chromium'.
*/
browsers = [
'firefox'
];
|
Update location of python file and send messages.
|
var pyshell = require('python-shell');
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
});
pyshell.run('/home/pi/node-red-contrib-adafruit-max31855/thermocouple/spi_read.py', function (err) {
if (err) throw err;
console.log('finished');
});
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
node.send(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) throw err;
console.log('finished');
node.send('finished');
});
}
RED.nodes.registerType("adafruit-max31855",LowerCaseNode);
}
|
var pyshell = require('python-shell');
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
});
pyshell.run('spi_read.py', function (err) {
if (err) throw err;
console.log('finished');
});
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err) throw err;
console.log('finished');
});
}
RED.nodes.registerType("adafruit-max31855",LowerCaseNode);
}
|
Fix defaulting to events page, maybe....
|
---
layout: null
---
$(document).ready(function () {
$('a.events-button').click(function (e) {
if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
currentWidth = $('.panel-cover').width()
if (currentWidth < 960) {
$('.panel-cover').addClass('panel-cover--collapsed')
$('.content-wrapper').addClass('animated slideInRight')
} else {
$('.panel-cover').css('max-width', currentWidth)
$('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
}
})
if (window.location.hash && window.location.hash == '#events') {
$('.panel-cover').addClass('panel-cover--collapsed')
}
if (window.location.pathname !== '{{ site.baseurl }}') {
$('.panel-cover').addClass('panel-cover--collapsed')
}
$('.btn-mobile-menu').click(function () {
$('.navigation-wrapper').toggleClass('visible animated bounceInDown')
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
})
$('.navigation-wrapper .events-button').click(function () {
$('.navigation-wrapper').toggleClass('visible')
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
})
})
|
---
layout: null
---
$(document).ready(function () {
$('a.events-button').click(function (e) {
if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
currentWidth = $('.panel-cover').width()
if (currentWidth < 960) {
$('.panel-cover').addClass('panel-cover--collapsed')
$('.content-wrapper').addClass('animated slideInRight')
} else {
$('.panel-cover').css('max-width', currentWidth)
$('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
}
})
if (window.location.hash && window.location.hash == '#events') {
$('.panel-cover').addClass('panel-cover--collapsed')
}
if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') {
$('.panel-cover').addClass('panel-cover--collapsed')
}
$('.btn-mobile-menu').click(function () {
$('.navigation-wrapper').toggleClass('visible animated bounceInDown')
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
})
$('.navigation-wrapper .events-button').click(function () {
$('.navigation-wrapper').toggleClass('visible')
$('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
})
})
|
Fix django model field docstring.
|
"""
************************
Django model integration
************************
**Static Model** provides custom Django model fields in the
``staticmodel.django.models`` package:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelTextField`` (sub-class of ``django.db.models.TextField``)
* ``StaticModelIntegerField`` (sub-class of ``django.db.models.IntegerField``)
Static model members are returned, and can be set, as the value of the
fields on a django model object.
All fields take the following keyword arguments in addition to the
arguments taken by their respective parent classes:
* ``static_model``: The static model class associated with this field.
* ``value_field_name``: The static model field name whose value will
be stored in the database. Defaults to the first field name in
``static_model._field_names``.
* ``display_field_name``: The static model field name whose value will
be used as the display value in the ``choices`` passed to the parent
field. Defaults to the value of ``value_field_name``.
When the model field is instantiated, it validates the values of
``value_field_name`` and ``display_field_name`` against
**every member** of the static model to insure the fields exist and
contain a value appropriate for the value of the field. This ensures
that error-causing inconsistencies are detected early during
development.
"""
|
"""
******************
Django integration
******************
**Static Model** provides two custom Django model fields in the
``staticmodel.django.fields`` module:
* ``StaticModelCharField`` (sub-class of ``django.db.models.CharField``)
* ``StaticModelIntegerField`` (sub-class of ``django.db.models.IntegerField``)
Static model members are returned, and can be set, as the value of the
fields on a django model object.
Both fields take the following keyword arguments in addition to the
arguments taken by their respective sub-classes:
* ``static_model``: The static model class associated with this field.
* ``value_field_name``: The static model field name whose value will
be stored in the database. Defaults to the first field name in
``static_model._field_names``.
* ``display_field_name``: The static model field name whose value will
be used as the display value in the ``choices`` passed to the parent
field. Defaults to the value of ``value_field_name``.
When the model field is instantiated, it validates the values of
``value_field_name`` and ``display_field_name`` against
**every member** of the static model to insure the fields exist and
contain a value appropriate for the value of the field. This ensures
that error-causing inconsistencies are detected early during
development.
"""
|
Make `refresh` return self for chaining actions
|
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.client and self._data == other._data
def __ne__(self, other):
return not (self == other)
def __getattr__(self, name):
try:
return self.__dict__['_data'][name]
except KeyError:
raise AttributeError(name)
def refresh(self):
self._data = self._fetch()
return self
def _fetch(self):
return self.client.api.get(self.api_path, raw=True)[self._data['type']]
def __repr__(self):
return '<API:{data[type]}:{data[id]}>'.format(data=self._data)
|
class APIObject(object):
def __init__(self, client, json_data):
super(APIObject, self).__init__()
self.client = client
self._data = json_data
def __eq__(self, other):
if not isinstance(other, APIObject):
return NotImplemented
return self.client is other.client and self._data == other._data
def __ne__(self, other):
return not (self == other)
def __getattr__(self, name):
try:
return self.__dict__['_data'][name]
except KeyError:
raise AttributeError(name)
def refresh(self):
self._data = self._fetch()
def _fetch(self):
return self.client.api.get(self.api_path, raw=True)[self._data['type']]
def __repr__(self):
return '<API:{data[type]}:{data[id]}>'.format(data=self._data)
|
Stop confirming ETA is 10 seconds ago, as it's possible that AutoFleetCharge
interrupt within that duration.
|
#!/usr/bin/env python
import logging
import time
import base
from kcaa import screens
logger = logging.getLogger('kcaa.manipulators.automission')
class CheckMissionResult(base.Manipulator):
def run(self):
logger.info('Checking mission result')
yield self.screen.check_mission_result()
class AutoCheckMissionResult(base.AutoManipulator):
@classmethod
def can_trigger(cls, owner):
if not screens.in_category(owner.screen_id, screens.PORT):
return
mission_list = owner.objects.get('MissionList')
if not mission_list:
return
now = int(1000 * time.time())
count = 0
for mission in mission_list.missions:
if mission.eta and mission.eta < now:
count += 1
if count != 0:
return {'count': count}
def run(self, count):
for _ in xrange(count):
yield self.do_manipulator(CheckMissionResult)
|
#!/usr/bin/env python
import logging
import time
import base
from kcaa import screens
logger = logging.getLogger('kcaa.manipulators.automission')
class CheckMissionResult(base.Manipulator):
def run(self):
logger.info('Checking mission result')
yield self.screen.check_mission_result()
class AutoCheckMissionResult(base.AutoManipulator):
@classmethod
def can_trigger(cls, owner):
if not screens.in_category(owner.screen_id, screens.PORT):
return
mission_list = owner.objects.get('MissionList')
if not mission_list:
return
now = int(1000 * time.time())
count = 0
for mission in mission_list.missions:
# Make sure the ETA has passed 10000 milliseconds ago.
if mission.eta and mission.eta + 10000 < now:
count += 1
if count != 0:
return {'count': count}
def run(self, count):
for _ in xrange(count):
yield self.do_manipulator(CheckMissionResult)
|
Fix email case issues when restoring user pointers.
(imported from commit 84d3288dffc1cb010d8cd2a749fe71aa2a4d0df3)
|
from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-pointers", "w").write(simplejson.dumps(pointers) + "\n")
def restore(change):
for (email, pointer) in simplejson.loads(file("dumped-pointers").read()):
u = UserProfile.objects.get(user__email__iexact=email)
print "%s: pointer %s => %s" % (email, u.pointer, pointer)
if change:
u.pointer = pointer
u.save()
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--restore', default=False, action='store_true'),
make_option('--dry-run', '-n', default=False, action='store_true'),)
def handle(self, *args, **options):
if options["restore"]:
restore(change=not options['dry_run'])
else:
dump()
|
from optparse import make_option
from django.core.management.base import BaseCommand
from zephyr.models import Realm, UserProfile
import simplejson
def dump():
pointers = []
for u in UserProfile.objects.select_related("user__email").all():
pointers.append((u.user.email, u.pointer))
file("dumped-pointers", "w").write(simplejson.dumps(pointers) + "\n")
def restore(change):
for (email, pointer) in simplejson.loads(file("dumped-pointers").read()):
u = UserProfile.objects.get(user__email=email)
print "%s: pointer %s => %s" % (email, u.pointer, pointer)
if change:
u.pointer = pointer
u.save()
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--restore', default=False, action='store_true'),
make_option('--dry-run', '-n', default=False, action='store_true'),)
def handle(self, *args, **options):
if options["restore"]:
restore(change=not options['dry_run'])
else:
dump()
|
Check for globally installed binary
|
'use strict';
var BinWrapper = require('bin-wrapper');
var path = require('path');
var pkg = require('../package.json');
/**
* Variables
*/
var BIN_VERSION = '0.7.5';
var BASE_URL = 'https://raw.github.com/imagemin/optipng-bin/v' + pkg.version + '/vendor/';
/**
* Initialize a new BinWrapper
*/
var bin = new BinWrapper({ global: true, progress: false })
.src(BASE_URL + 'osx/optipng', 'darwin')
.src(BASE_URL + 'linux/x86/optipng', 'linux', 'x86')
.src(BASE_URL + 'linux/x64/optipng', 'linux', 'x64')
.src(BASE_URL + 'freebsd/optipng', 'freebsd')
.src(BASE_URL + 'sunos/x86/optipng', 'sunos', 'x86')
.src(BASE_URL + 'sunos/x64/optipng', 'sunos', 'x64')
.src(BASE_URL + 'win/optipng.exe', 'win32')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'optipng.exe' : 'optipng')
.version('>=' + BIN_VERSION);
/**
* Module exports
*/
module.exports = bin;
module.exports.v = BIN_VERSION;
|
'use strict';
var BinWrapper = require('bin-wrapper');
var path = require('path');
var pkg = require('../package.json');
/**
* Variables
*/
var BIN_VERSION = '0.7.5';
var BASE_URL = 'https://raw.github.com/imagemin/optipng-bin/v' + pkg.version + '/vendor/';
/**
* Initialize a new BinWrapper
*/
var bin = new BinWrapper({ progress: false })
.src(BASE_URL + 'osx/optipng', 'darwin')
.src(BASE_URL + 'linux/x86/optipng', 'linux', 'x86')
.src(BASE_URL + 'linux/x64/optipng', 'linux', 'x64')
.src(BASE_URL + 'freebsd/optipng', 'freebsd')
.src(BASE_URL + 'sunos/x86/optipng', 'sunos', 'x86')
.src(BASE_URL + 'sunos/x64/optipng', 'sunos', 'x64')
.src(BASE_URL + 'win/optipng.exe', 'win32')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'optipng.exe' : 'optipng')
.version('>=' + BIN_VERSION);
/**
* Module exports
*/
module.exports = bin;
module.exports.v = BIN_VERSION;
|
Fix commented PaymentExpress card number
|
<?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\PaymentExpress\Message;
/**
* PaymentExpress PxPost Store Request
*/
class PxPostStoreRequest extends PxPostAuthorizeRequest
{
public function getData()
{
$this->validate('card');
$this->getCard()->validate();
$data = $this->getBaseData();
$data->Amount = '1.00';
$data->EnableAddBillCard = 1;
$data->CardNumber = $this->getCard()->getNumber();
$data->CardHolderName = $this->getCard()->getName();
$data->DateExpiry = $this->getCard()->getExpiryDate('my');
$data->Cvc2 = $this->getCard()->getCvv();
return $data;
}
}
|
<?php
/*
* This file is part of the Omnipay package.
*
* (c) Adrian Macneil <adrian@adrianmacneil.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Omnipay\PaymentExpress\Message;
/**
* PaymentExpress PxPost Store Request
*/
class PxPostStoreRequest extends PxPostAuthorizeRequest
{
public function getData()
{
$this->validate('card');
$this->getCard()->validate();
$data = $this->getBaseData();
$data->Amount = '1.00';
$data->EnableAddBillCard = 1;
// $data->CardNumber = $this->getCard()->getNumber();
$data->CardHolderName = $this->getCard()->getName();
$data->DateExpiry = $this->getCard()->getExpiryDate('my');
$data->Cvc2 = $this->getCard()->getCvv();
return $data;
}
}
|
Replace print statement with `warnings.warn`.
Also so that it doesn't need to be converted for Python3 compat.
|
#!/usr/bin/python
import optparse
import sys
import warnings
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
warnings.warn('Trying default SDK path.', RuntimeWarning)
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern)
|
#!/usr/bin/python
import optparse
import sys
# Install the Python unittest2 package before you run this script.
import unittest2
USAGE = """%prog SDK_PATH
Run unit tests for App Engine apps.
The SDK Path is probably /usr/local/google_appengine on Mac OS
SDK_PATH Path to the SDK installation"""
def main(sdk_path, test_pattern):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover("tests", test_pattern)
tests = unittest2.TextTestRunner(verbosity=2).run(suite)
if tests.wasSuccessful() == True:
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 1:
print 'Warning: Trying default SDK path.'
sdk_path = "/usr/local/google_appengine"
else:
sdk_path = args[0]
test_pattern = "test*.py"
if len(args) > 1:
test_pattern = args[1]
main(sdk_path, test_pattern)
|
Exclude test_runner from dist package
|
from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='baldr',
version='0.4.5',
url='https://github.com/timsavage/baldr',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredbypenguins.org',
description='Odin integration to Django',
long_description=long_description,
packages=find_packages(exclude=("django_test_runner",)),
install_requires=['six', 'odin>=0.5', 'django>=1.5'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='baldr',
version='0.4.5',
url='https://github.com/timsavage/baldr',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredbypenguins.org',
description='Odin integration to Django',
long_description=long_description,
packages=find_packages(),
install_requires=['six', 'odin>=0.5', 'django>=1.5'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Convert plugin to use Symfony events
|
<?php
namespace Grav\Plugin;
use Grav\Common\Plugin;
use Grav\Plugin\Taxonomylist;
class TaxonomylistPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents() {
return [
'onAfterTwigTemplatesPaths' => ['onAfterTwigTemplatesPaths', 0],
'onAfterTwigSiteVars' => ['onAfterTwigSiteVars', 0]
];
}
/**
* Add current directory to twig lookup paths.
*/
public function onAfterTwigTemplatesPaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
}
/**
* Set needed variables to display the taxonomy list.
*/
public function onAfterTwigSiteVars()
{
require_once __DIR__ . '/classes/taxonomylist.php';
$twig = $this->grav['twig'];
$twig->twig_vars['taxonomylist'] = new Taxonomylist();
$twig->twig_vars['list_url'] = $this->config->get(
'site.blog.route',
$this->config->get('plugins.taxonomylist.route')
);
}
}
|
<?php
namespace Grav\Plugin;
use \Grav\Common\Plugin;
use \Grav\Common\Registry;
use \Grav\Plugin\Taxonomylist;
class TaxonomylistPlugin extends Plugin
{
/**
* Add current directory to twig lookup paths.
*/
public function onAfterTwigTemplatesPaths()
{
Registry::get('Twig')->twig_paths[] = __DIR__ . '/templates';
}
/**
* Set needed variables to display the taxonomy list.
*/
public function onAfterTwigSiteVars()
{
require_once __DIR__ . '/classes/taxonomylist.php';
$twig = Registry::get('Twig');
$twig->twig_vars['taxonomylist'] = new Taxonomylist();
$twig->twig_vars['list_url'] = $this->config->get(
'site.blog.route',
$this->config->get('plugins.taxonomylist.route')
);
}
}
|
Fix namespace of HTTP binding for jolie2wsdl.
|
package joliex.wsdl;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Francesco
*/
public enum NameSpacesEnum {
//TNS("tns","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.wsdl"),
//TNS_SCH("tnsxs","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.xsd"),
XML_SCH("xs","http://www.w3.org/2001/XMLSchema"),
SOAP("soap","http://schemas.xmlsoap.org/wsdl/soap/"),
SOAPoverHTTP("soapOhttp","http://schemas.xmlsoap.org/soap/http"),
WSDL("wsdl","http://schemas.xmlsoap.org/wsdl/");
private String prefix;
private String nameSpaceURI;
NameSpacesEnum(String prefix,String nameSpaceURI){
this.prefix=prefix;
this.nameSpaceURI=nameSpaceURI;
}
/**
* @return the nameSpace
*/ public String getNameSpaceURI()
{
return nameSpaceURI;
}
/**
* @return the prefix
*/ public String getNameSpacePrefix()
{
return prefix;
}
}
|
package joliex.wsdl;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Francesco
*/
public enum NameSpacesEnum {
//TNS("tns","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.wsdl"),
//TNS_SCH("tnsxs","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.xsd"),
XML_SCH("xs","http://www.w3.org/2001/XMLSchema"),
SOAP("soap","http://schemas.xmlsoap.org/wsdl/soap/"),
SOAPoverHTTP("soapOhttp","http://schemas.xmlsoap.org/soap/http/"),
WSDL("wsdl","http://schemas.xmlsoap.org/wsdl/");
private String prefix;
private String nameSpaceURI;
NameSpacesEnum(String prefix,String nameSpaceURI){
this.prefix=prefix;
this.nameSpaceURI=nameSpaceURI;
}
/**
* @return the nameSpace
*/ public String getNameSpaceURI()
{
return nameSpaceURI;
}
/**
* @return the prefix
*/ public String getNameSpacePrefix()
{
return prefix;
}
}
|
Make sort param request listener accept non-array configuration
|
<?php
namespace Alchemy\RestBundle\EventListener;
use Alchemy\RestBundle\Rest\Request\SortOptionsFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class SortParamRequestListener implements EventSubscriberInterface
{
/**
* @var SortOptionsFactory
*/
private $factory;
/**
* @param SortOptionsFactory $factory
*/
public function __construct(SortOptionsFactory $factory)
{
$this->factory = $factory;
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$attributes = $request->attributes;
if (($config = $attributes->get('_sort', false)) === false) {
return;
}
if (! is_array($config)) {
$config = array();
}
$request->attributes->set('sort', $this->factory->create($request->query->all(), $config));
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array('onKernelRequest', -2048)
);
}
}
|
<?php
namespace Alchemy\RestBundle\EventListener;
use Alchemy\RestBundle\Rest\Request\SortOptionsFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class SortParamRequestListener implements EventSubscriberInterface
{
/**
* @var SortOptionsFactory
*/
private $factory;
/**
* @param SortOptionsFactory $factory
*/
public function __construct(SortOptionsFactory $factory)
{
$this->factory = $factory;
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$attributes = $request->attributes;
if (($config = $attributes->get('_sort', false)) === false) {
return;
}
if (! is_array($config)) {
return;
}
$request->attributes->set('sort', $this->factory->create($request->query->all(), $config));
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array('onKernelRequest', -2048)
);
}
}
|
Fix logic for finding the user
|
const Verifier = require('feathers-authentication-local').Verifier;
const errors = require('feathers-errors');
module.exports = function createVerifier (options = {}, app) {
if (!options.userService) {
throw new Error('You must provide a `userService` in the options for the challenge-request strategy verifier');
}
return class ChallengeRequestVerifier extends Verifier {
verify (req, email, signature, done) {
// Make sure request was signed. This will be caught implicitly by
// Passport, but making sure it's checked explicitly here is preferable.
if (!signature) {
done(new errors.NotAuthenticated('invalid login'), null);
}
app.service(options.userService).find({query: {email}})
.then(users => {
users = users.data || users;
let user = users[0];
// Pass the user to the after hooks.
if (user) {
done(null, user);
// Or there was no user.
} else {
done(new errors.NotAuthenticated('invalid login'), null);
}
})
.catch(error => {
console.log(error);
debugger;
done(new errors.NotAuthenticated(error), null);
});
}
};
};
|
const Verifier = require('feathers-authentication-local').Verifier;
const errors = require('feathers-errors');
module.exports = function createVerifier (options = {}, app) {
if (!options.userService) {
throw new Error('You must provide a `userService` in the options for the challenge-request strategy verifier');
}
return class ChallengeRequestVerifier extends Verifier {
verify (req, email, signature, done) {
// Make sure request was signed. This will be caught implicitly by
// Passport, but making sure it's checked explicitly here is preferable.
if (!signature) {
done(new errors.NotAuthenticated('invalid login'), null);
}
app.service(options.userService).find({email})
.then(users => {
users = users.data || users;
let user = users[0];
// Pass the user to the after hooks.
if (user) {
done(null, user);
// Or there was no user.
} else {
done(new errors.NotAuthenticated('invalid login'), null);
}
})
.catch(error => {
console.log(error);
debugger;
done(new errors.NotAuthenticated(error), null);
});
}
};
};
|
Include handlebars module in build process
|
define(["handlebars-compiler"], function (Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension);
// Use node.js file system module to load the template.
// Sorry, no Rhino support.
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
parentRequire(["handlebars"], function () {
onload();
});
},
// http://requirejs.org/docs/plugins.html#apiwrite
write: function (pluginName, name, write) {
var compiled = Handlebars.precompile(buildMap[name]);
// Write out precompiled version of the template function as AMD
// definition.
write(
"define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" +
"return Handlebars.template(" + compiled.toString() + ");\n" +
"});\n"
);
}
};
});
|
define(["handlebars-compiler"], function (Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension);
// Use node.js file system module to load the template.
// Sorry, no Rhino support.
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
onload();
},
// http://requirejs.org/docs/plugins.html#apiwrite
write: function (pluginName, name, write) {
var compiled = Handlebars.precompile(buildMap[name]);
// Write out precompiled version of the template function as AMD
// definition.
write(
"define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" +
"return Handlebars.template(" + compiled.toString() + ");\n" +
"});\n"
);
}
};
});
|
Use inputTrees for sass dir
|
var CachingWriter = require('broccoli-caching-writer');
var Compass = require('compass-compile');
CompassCompiler.prototype = Object.create(CachingWriter.prototype);
CompassCompiler.prototype.constructor = CompassCompiler;
function CompassCompiler(inputTrees, options) {
if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTrees, options); }
if (!Array.isArray(inputTrees)) { throw new Error('Expected array for first argument - did you mean [tree] instead of tree?'); }
CachingWriter.call(this, inputTrees, {
annotation: options.annotation
});
this.defaultOptions = {
getSassDir: function(inputTrees) {
return inputTrees[0];
},
getCssDir: function(outputPath) {
return outputPath;
}
};
this.inputTrees = inputTrees;
this.options = options || {};
this.compass = new Compass();
}
CompassCompiler.prototype.getOptions = function() {
var compassOptions = Object.assign({}, this.defaultOptions, this.options);
compassOptions.sassDir = compassOptions.getSassDir(this.inputTrees, this.inputPaths);
compassOptions.cssDir = compassOptions.getCssDir(this.outputPath);
delete compassOptions.getSassDir;
delete compassOptions.getCssDir;
return compassOptions;
};
CompassCompiler.prototype.build = function() {
var compassOptions = this.getOptions();
return this.compass.compile(compassOptions);
};
module.exports = CompassCompiler;
|
var CachingWriter = require('broccoli-caching-writer');
var Compass = require('compass-compile');
CompassCompiler.prototype = Object.create(CachingWriter.prototype);
CompassCompiler.prototype.constructor = CompassCompiler;
function CompassCompiler(inputTrees, options) {
if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTrees, options); }
if (!Array.isArray(inputTrees)) { throw new Error('Expected array for first argument - did you mean [tree] instead of tree?'); }
CachingWriter.call(this, inputTrees, {
annotation: options.annotation
});
this.defaultOptions = {
getSassDir: function(inputPaths) {
return inputPaths[0];
},
getCssDir: function(outputPath) {
return outputPath;
}
};
this.options = options || {};
this.compass = new Compass();
}
CompassCompiler.prototype.getOptions = function() {
var compassOptions = Object.assign({}, this.defaultOptions, this.options);
compassOptions.sassDir = compassOptions.getSassDir(this.inputPaths);
compassOptions.cssDir = compassOptions.getCssDir(this.outputPath);
delete compassOptions.getSassDir;
delete compassOptions.getCssDir;
return compassOptions;
};
CompassCompiler.prototype.build = function() {
var compassOptions = this.getOptions();
return this.compass.compile(compassOptions);
};
module.exports = CompassCompiler;
|
Remove the 'end' type from format()
|
var util = require('util');
var mochaFormatter = {
suite: "describe('%s', function () {",
test: "it('%s');",
end: '});'
};
function format(line, type) {
return util.format(mochaFormatter[type], line.trim());
}
function getIndentLength(line) {
return (line.match(/ {2}/g) || []).length;
}
module.exports = function (input) {
var newline = '\n';
var inputLines = input.split(newline);
var outputLines = [];
inputLines.forEach(function (line, index) {
var indentLength = getIndentLength(line);
var nextLine = inputLines[index + 1];
var nextIndentLength = nextLine === undefined ? 0 : getIndentLength(nextLine);
if (line.length === 0) {
outputLines.push('');
} else if (nextLine === undefined || indentLength >= nextIndentLength) {
outputLines.push(format(line, 'test'));
if (indentLength > nextIndentLength) {
for (var i = 0; i < indentLength - nextIndentLength; i++) {
outputLines.push(mochaFormatter.end);
}
}
} else {
outputLines.push(format(line, 'suite'));
}
});
return outputLines.join(newline);
};
|
var util = require('util');
var mochaFormatter = {
suite: "describe('%s', function () {",
test: "it('%s');",
end: '});'
};
function format(line, type) {
if (type === 'end') {
return mochaFormatter.end;
} else {
return util.format(mochaFormatter[type], line.trim());
}
}
function getIndentLength(line) {
return (line.match(/ {2}/g) || []).length;
}
module.exports = function (input) {
var newline = '\n';
var inputLines = input.split(newline);
var outputLines = [];
inputLines.forEach(function (line, index) {
var indentLength = getIndentLength(line);
var nextLine = inputLines[index + 1];
var nextIndentLength = nextLine === undefined ? 0 : getIndentLength(nextLine);
if (line.length === 0) {
outputLines.push('');
} else if (nextLine === undefined || indentLength >= nextIndentLength) {
outputLines.push(format(line, 'test'));
if (indentLength > nextIndentLength) {
for (var i = 0; i < indentLength - nextIndentLength; i++) {
outputLines.push(format(line, 'end'));
}
}
} else {
outputLines.push(format(line, 'suite'));
}
});
return outputLines.join(newline);
};
|
Fix name of font size map
|
/* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*********************************************************************************************** */
/**
* Font size normalizer
*/
qx.Class.define("unify.bom.Font", {
statics : {
BaseFontSize : 16,
FontSizeMap : {
"xx-small" : 9,
"x-small" : 10,
"small" : 13,
"medium" : 16,
"large" : 18,
"x-large" : 24,
"xx-large" : 32
},
/**
* Resolve font size of relative name
*
* @param fontSizeName {String} Name of relative font size
* @return {Integer} Pixel value as string
*/
resolveRelativeSize : function(fontSizeName) {
var self = unify.bom.Font;
var fontSize = null;
if (fontSizeName.indexOf("%") > -1) {
fontSize = Math.round(self.BaseFontSize * (parseInt(fontSizeName.split("%")[0], 10) / 100));
} else {
fontSize = self.FontSizeMap[fontSizeName];
}
return fontSize || self.BaseFontSize;
}
}
});
|
/* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2011, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*********************************************************************************************** */
/**
* Font size normalizer
*/
qx.Class.define("unify.bom.Font", {
statics : {
BaseFontSize : 16,
FontSizeMap : {
"xx-small" : 9,
"x-small" : 10,
"small" : 13,
"medium" : 16,
"large" : 18,
"x-large" : 24,
"xx-large" : 32
},
/**
* Resolve font size of relative name
*
* @param fontSizeName {String} Name of relative font size
* @return {Integer} Pixel value as string
*/
resolveRelativeSize : function(fontSizeName) {
var self = unify.bom.Font;
var fontSize = null;
if (fontSizeName.indexOf("%") > -1) {
fontSize = Math.round(self.BaseFontSize * (parseInt(fontSizeName.split("%")[0], 10) / 100));
} else {
fontSize = self.fontSizeMap[fontSizeName];
}
return fontSize || self.BaseFontSize;
}
}
});
|
Add a test for the 'cf quota $QUOTA_NAME' command
|
package quotas_test
import(
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/pivotal-cf-experimental/cf-test-helpers/cf"
)
var _ = Describe("CF Quota commands", func() {
It("can Create, Read, Update, and Delete quotas", func() {
AsUser(context.AdminUserContext(), func() {
Eventually(Cf("create-quota",
"quota-name-goes-here",
"-m", "512M",
), 5.0).Should(Exit(0))
Eventually(Cf("quota", "quota-name-goes-here"), 5.0).Should(Say("512M"))
quotaOutput := Cf("quotas")
Eventually(quotaOutput, 5).Should(Say("quota-name-goes-here"))
Eventually(Cf("update-quota",
"quota-name-goes-here",
"-m", "513M",
), 5).Should(Exit(0))
Eventually(Cf("quotas")).Should(Say("513M"))
Eventually(Cf("delete-quota",
"quota-name-goes-here",
"-f,",
)).Should(Exit(0))
Eventually(Cf("quotas")).ShouldNot(Say("quota-name-goes-here"))
})
})
})
|
package quotas_test
import(
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
. "github.com/onsi/gomega/gexec"
. "github.com/pivotal-cf-experimental/cf-test-helpers/cf"
)
var _ = Describe("CF Quota commands", func() {
It("can Create, Read, Update, and Delete quotas", func() {
AsUser(context.AdminUserContext(), func() {
Eventually(Cf("create-quota",
"quota-name-goes-here",
"-m", "512M",
), 5.0).Should(Exit(0))
quotaOutput := Cf("quotas")
Eventually(quotaOutput, 5).Should(Say("quota-name-goes-here"))
Eventually(Cf("update-quota",
"quota-name-goes-here",
"-m", "513M",
), 5).Should(Exit(0))
Eventually(Cf("quotas")).Should(Say("513M"))
Eventually(Cf("delete-quota",
"quota-name-goes-here",
"-f,",
)).Should(Exit(0))
Eventually(Cf("quotas")).ShouldNot(Say("quota-name-goes-here"))
})
})
})
|
Put module.exports and function on same line
|
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
module.exports = function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
|
module.exports = reviewersEditionCompare
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
|
Use the enum constant as the default value
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.configuration;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public abstract class AbstractPersistentStateCondition implements Condition {
private static final PersistentStateConfig DEFAULT_VALUE = PersistentStateConfig.REDIS;
private final PersistentStateConfig persistentStateConfig;
protected AbstractPersistentStateCondition(final PersistentStateConfig persistentStateConfig) {
this.persistentStateConfig = persistentStateConfig;
}
@Override
public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
return getProperty(context) == persistentStateConfig;
}
private PersistentStateConfig getProperty(final ConditionContext context) {
return PersistentStateConfig.valueOf(context.getEnvironment().getProperty("hp.find.persistentState", DEFAULT_VALUE.name()));
}
}
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.configuration;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public abstract class AbstractPersistentStateCondition implements Condition {
private static final String DEFAULT_VALUE = "REDIS";
private final PersistentStateConfig persistentStateConfig;
protected AbstractPersistentStateCondition(final PersistentStateConfig persistentStateConfig) {
this.persistentStateConfig = persistentStateConfig;
}
@Override
public boolean matches(final ConditionContext context, final AnnotatedTypeMetadata metadata) {
return getProperty(context) == persistentStateConfig;
}
private PersistentStateConfig getProperty(final ConditionContext context) {
return PersistentStateConfig.valueOf(context.getEnvironment().getProperty("hp.find.persistentState", DEFAULT_VALUE));
}
}
|
MAke Eventer.removeListener work if no cbs bound for event, yet.
|
;(function(exports) {
function Eventer() {
var callbacks = {};
this.addListener = function(obj, event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push({
obj: obj,
callback: callback
});
return this;
};
this.addListener
this.on = this.addListener;
this.removeListener = function(obj, event) {
if (callbacks[event] !== undefined) {
for(var i = 0; i < callbacks[event].length; i++) {
if(callbacks[event][i].obj === obj) {
callbacks[event].splice(i, 1);
break;
}
}
}
};
this.emit = function(event, data) {
var eventCallbacks = callbacks[event];
if(eventCallbacks !== undefined) {
for(var i = 0; i < eventCallbacks.length; i++) {
var callbackObj = eventCallbacks[i];
callbackObj.callback.call(callbackObj.obj, data);
}
}
return this;
};
}
exports.Eventer = Eventer;
})(typeof exports === 'undefined' ? this : exports)
|
;(function(exports) {
function Eventer() {
var callbacks = {};
this.addListener = function(obj, event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push({
obj: obj,
callback: callback
});
return this;
};
this.addListener
this.on = this.addListener;
this.removeListener = function(obj, event) {
for(var i = 0; i < callbacks[event].length; i++) {
if(callbacks[event][i].obj === obj) {
callbacks[event].splice(i, 1);
break;
}
}
};
this.emit = function(event, data) {
var eventCallbacks = callbacks[event];
if(eventCallbacks !== undefined) {
for(var i = 0; i < eventCallbacks.length; i++) {
var callbackObj = eventCallbacks[i];
callbackObj.callback.call(callbackObj.obj, data);
}
}
return this;
};
}
exports.Eventer = Eventer;
})(typeof exports === 'undefined' ? this : exports)
|
Add a dependency on Scrapy
|
#!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='Bug importers for the OpenHatch project',
install_requires=[
'gdata',
'lxml',
'pyopenssl',
'unicodecsv',
'feedparser',
'twisted',
'python-dateutil',
'decorator',
'scrapy',
],
)
if __name__ == '__main__':
from setuptools import setup
setup(**setup_params)
|
#!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='Bug importers for the OpenHatch project',
install_requires=[
'gdata',
'lxml',
'pyopenssl',
'unicodecsv',
'feedparser',
'twisted',
'python-dateutil',
'decorator',
],
)
if __name__ == '__main__':
from setuptools import setup
setup(**setup_params)
|
Fix a bug where MappedBytes.writeUtf8 crashed the JVM if passed a null
|
package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.io.File;
import java.io.RandomAccessFile;
import static org.junit.Assert.*;
public class MappedBytesTest {
@Test
public void shouldNotBeReadOnly() throws Exception {
MappedBytes bytes = MappedBytes.mappedBytes(File.createTempFile("mapped", "bytes"), 64 << 10);
assertFalse(bytes.isBackingFileReadOnly());
bytes.writeUtf8(null); // used to blow up.
assertNull(bytes.readUtf8());
bytes.release();
}
@Test
public void shouldBeReadOnly() throws Exception {
final File tempFile = File.createTempFile("mapped", "bytes");
final RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
raf.setLength(4096);
assertTrue(tempFile.setWritable(false));
final MappedBytes mappedBytes = MappedBytes.readOnly(tempFile);
assertTrue(mappedBytes.
isBackingFileReadOnly());
mappedBytes.release();
}
}
|
package net.openhft.chronicle.bytes;
import org.junit.Test;
import java.io.File;
import java.io.RandomAccessFile;
import static org.junit.Assert.*;
public class MappedBytesTest {
@Test
public void shouldNotBeReadOnly() throws Exception {
MappedBytes bytes = MappedBytes.mappedBytes(File.createTempFile("mapped", "bytes"), 1024);
assertFalse(bytes.isBackingFileReadOnly());
bytes.writeUtf8(null); // used to blow up.
assertNull(bytes.readUtf8());
bytes.release();
}
@Test
public void shouldBeReadOnly() throws Exception {
final File tempFile = File.createTempFile("mapped", "bytes");
final RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
raf.setLength(4096);
assertTrue(tempFile.setWritable(false));
final MappedBytes mappedBytes = MappedBytes.readOnly(tempFile);
assertTrue(mappedBytes.
isBackingFileReadOnly());
mappedBytes.release();
}
}
|
Set required in files related
|
<?php
class RelatedFileForm extends BaseForm
{
public function configure()
{
$this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
$this->widgetSchema['filenames']->setLabel("Add File") ;
$this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
$this->validatorSchema['filenames'] = new sfValidatorFile(
array(
'required' => true,
//'mime_type_guessers' => array('guessFromFileinfo'),
'validated_file_class' => 'myValidatedFile'
));
$this->validatorSchema['filenames']->setOption('mime_type_guessers', array(
array($this->validatorSchema['filenames'], 'guessFromFileinfo'),
array($this->validatorSchema['filenames'], 'guessFromFileBinary'),
array($this->validatorSchema['filenames'], 'guessFromMimeContentType')
));
}
}
|
<?php
class RelatedFileForm extends BaseForm
{
public function configure()
{
$this->widgetSchema['filenames'] = new sfWidgetFormInputFile();
$this->widgetSchema['filenames']->setLabel("Add File") ;
$this->widgetSchema['filenames']->setAttributes(array('class' => 'Add_related_file'));
$this->validatorSchema['filenames'] = new sfValidatorFile(
array(
'required' => false,
//'mime_type_guessers' => array('guessFromFileinfo'),
'validated_file_class' => 'myValidatedFile'
));
$this->validatorSchema['filenames']->setOption('mime_type_guessers', array(
array($this->validatorSchema['filenames'], 'guessFromFileinfo'),
array($this->validatorSchema['filenames'], 'guessFromFileBinary'),
array($this->validatorSchema['filenames'], 'guessFromMimeContentType')
));
}
}
|
Remove self (not in class scope)
|
#!/usr/bin/env php
<?php
/*
* This file is part of the Certificationy CLI application.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/vendor/autoload.php';
use Certificationy\Cli\Command\StartCommand;
use KevinGH\Amend\Command;
use KevinGH\Amend\Helper;
use Symfony\Component\Console\Application;
use Symfony\Component\Yaml\Yaml;
const VERSION = 1.4;
const APPLICATION_NAME = 'Certificationy';
$application = new Application(APPLICATION_NAME, VERSION);
$config = Yaml::parse(file_get_contents('config.yml'));
$updateCommand = new Command('self-update');
$updateCommand->setManifestUri($config['manifest_uri']);
$application->add($updateCommand);
$application->getHelperSet()->set(new Helper());
$startCommand = new StartCommand();
$application->add($startCommand);
$application->setDefaultCommand($startCommand->getName());
$application->run();
|
#!/usr/bin/env php
<?php
/*
* This file is part of the Certificationy CLI application.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/vendor/autoload.php';
use Certificationy\Cli\Command\StartCommand;
use KevinGH\Amend\Command;
use KevinGH\Amend\Helper;
use Symfony\Component\Console\Application;
use Symfony\Component\Yaml\Yaml;
const VERSION = 1.4;
const APPLICATION_NAME = 'Certificationy';
$application = new Application(self::APPLICATION_NAME, self::VERSION);
$config = Yaml::parse(file_get_contents('config.yml'));
$updateCommand = new Command('self-update');
$updateCommand->setManifestUri($config['manifest_uri']);
$application->add($updateCommand);
$application->getHelperSet()->set(new Helper());
$startCommand = new StartCommand();
$application->add($startCommand);
$application->setDefaultCommand($startCommand->getName());
$application->run();
|
Update expert card tests to use enzyme.
|
/* Copyright (C) 2018 Canonical Ltd. */
'use strict';
const React = require('react');
const enzyme = require('enzyme');
const ExpertCard = require('../expert-card/expert-card');
const EXPERTS = require('../expert-card/experts');
describe('ExpertCard', function() {
const renderComponent = (options = {}) => enzyme.shallow(
<ExpertCard
expert={options.expert || EXPERTS['spicule']}
staticURL="/media">
<span>Content</span>
</ExpertCard>
);
it('can render', () => {
const wrapper = renderComponent();
const expected = (
<div className="expert-card">
<div className="expert-card__top-title">
Juju expert partners
</div>
<div className="expert-card__logo">
<img alt="spicule.png"
className="expert-card__logo-image"
src={
'/media/static/gui/build/app/assets/images/' +
'non-sprites/experts/spicule.png'} />
</div>
<span>Content</span>
</div>);
assert.compareJSX(wrapper, expected);
});
});
|
/* Copyright (C) 2018 Canonical Ltd. */
'use strict';
const React = require('react');
const ExpertCard = require('../expert-card/expert-card');
const EXPERTS = require('../expert-card/experts');
const jsTestUtils = require('../../utils/component-test-utils');
describe('ExpertCard', function() {
function renderComponent(options={}) {
return jsTestUtils.shallowRender(
<ExpertCard
expert={options.expert || EXPERTS['spicule']}
staticURL="/media">
<span>Content</span>
</ExpertCard>, true);
}
it('can render', () => {
const renderer = renderComponent();
const output = renderer.getRenderOutput();
const expected = (
<div className="expert-card">
<div className="expert-card__top-title">
Juju expert partners
</div>
<div className="expert-card__logo">
<img alt="spicule.png"
className="expert-card__logo-image"
src={
'/media/static/gui/build/app/assets/images/' +
'non-sprites/experts/spicule.png'} />
</div>
<span>Content</span>
</div>);
expect(output).toEqualJSX(expected);
});
});
|
Fix issue with default values — just implement in getters
|
const Sequelize = require('sequelize');
module.exports = {
JSONType: (fieldName, {defaultValue = {}} = {}) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) { return defaultValue }
return JSON.parse(val);
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
JSONARRAYType: (fieldName, {defaultValue = []} = {}) => ({
type: Sequelize.TEXT,
get: function get() {
const val = this.getDataValue(fieldName);
if (!val) { return defaultValue }
return JSON.parse(val);
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
}
|
const Sequelize = require('sequelize');
module.exports = {
JSONType: (fieldName, {defaultValue = '{}'} = {}) => ({
type: Sequelize.TEXT,
defaultValue,
get: function get() {
return JSON.parse(this.getDataValue(fieldName))
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
JSONARRAYType: (fieldName, {defaultValue = '[]'} = {}) => ({
type: Sequelize.TEXT,
defaultValue,
get: function get() {
return JSON.parse(this.getDataValue(fieldName))
},
set: function set(val) {
this.setDataValue(fieldName, JSON.stringify(val));
},
}),
}
|
Fix pending test for PUT collection
|
var expect = require('expect.js');
var request = require('request');
var fixtures = require('./fixtures');
describe('PUT plural', function () {
it('should replace entire collection with given new collection... maybe'); /*, function (done) {
return done(); // TODO unimplemented
var poke = { name: 'Poke' };
var collards = { name: 'Collard Greens' };
var mustard = { name: 'Mustard' };
var options = {
url: 'http://localhost:8012/api/v1/vegetables',
json: [ poke, collards, mustard ]
};
request.put(options, function (error, response, body) {
if (error) return done(error);
expect(response).to.have.property('statusCode', 200);
expect(body).to.have.property('length', 3); // TODO more...
done();
});
}); */
});
|
var expect = require('expect.js');
var request = require('request');
var fixtures = require('./fixtures');
describe('PUT plural', function () {
before(fixtures.vegetable.init);
beforeEach(fixtures.vegetable.create);
after(fixtures.vegetable.deinit);
it('should replace entire collection with given new collection'); /*, function (done) {
return done(); // TODO unimplemented
var poke = { name: 'Poke' };
var collards = { name: 'Collard Greens' };
var mustard = { name: 'Mustard' };
var options = {
url: 'http://localhost:8012/api/v1/vegetables',
json: [ poke, collards, mustard ]
};
request.put(options, function (error, response, body) {
if (error) return done(error);
expect(response).to.have.property('statusCode', 200);
expect(body).to.have.property('length', 3); // TODO more...
done();
});
}); */
});
|
Add protection for empty GitHub url.
|
'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callback('GitHub repo not valid.');
return;
}
githubapi.repos.getContent({
user: user,
repo: repo,
path: 'package.json'
}, function(error, result) {
if (error) {
callback(error.message || error.defaultMessage || error);
return;
}
var jsonString = new Buffer(result.content, result.encoding).toString();
var json = JSON.parse(jsonString);
callback(null, json);
});
};
exports.getUserFromUrl = function(url) {
if (!url) {
return url;
}
var user = url.substr('https://github.com/'.length);
return user && user.substr(0, user.indexOf('/'));
};
exports.getRepoFromUrl = function(url) {
if (!url) {
return url;
}
var repo = url.substr(url.lastIndexOf('/')+1);
return repo && repo.substr(0, repo.indexOf('.'));
}
|
'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callback('GitHub repo not valid.');
return;
}
githubapi.repos.getContent({
user: user,
repo: repo,
path: 'package.json'
}, function(error, result) {
if (error) {
callback(error.message || error.defaultMessage || error);
return;
}
var jsonString = new Buffer(result.content, result.encoding).toString();
var json = JSON.parse(jsonString);
callback(null, json);
});
};
exports.getUserFromUrl = function(url) {
var user = url.substr('https://github.com/'.length);
user = user.substr(0, user.indexOf('/'));
return user;
};
exports.getRepoFromUrl = function(url) {
var repo = url.substr(url.lastIndexOf('/')+1);
repo = repo.substr(0, repo.indexOf('.'));
return repo;
}
|
Allow for comments in the sql file that do not start the line.
|
import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **options):
# Ensure we have the clone_schema() function
clone_schema_file = os.path.join(os.path.abspath(__file__ + '/../../../'), 'sql', 'clone_schema.sql')
clone_schema_function = " ".join([x.strip() for x in open(clone_schema_file).readlines() if not x.strip().startswith('--')])
clone_schema_function = clone_schema_function.replace("'%'", "'%%'")
cursor = connection.cursor()
cursor.execute(clone_schema_function)
# Ensure we have a __template__ schema.
template_schema.create_schema()
# Set the search path, so we find created models correctly
cursor = connection.cursor()
cursor.execute("SET search_path TO public,__template__;")
super(Command, self).handle_noargs(**options)
# Ensure all existing schemata exist (in case we imported them using loaddata or something)
for schema in Schema.objects.all():
schema.create_schema()
|
import os.path
from django.core.management.commands import syncdb
from django.db import models, connection, transaction
try:
from south.management.commands import syncdb
except ImportError:
pass
from ...models import Schema, template_schema
class Command(syncdb.Command):
def handle_noargs(self, **options):
# Ensure we have the clone_schema() function
clone_schema_file = os.path.join(os.path.abspath(__file__ + '/../../../'), 'sql', 'clone_schema.sql')
clone_schema_function = " ".join([x.strip() for x in open(clone_schema_file).readlines() if not x.startswith('--')])
clone_schema_function = clone_schema_function.replace("'%'", "'%%'")
cursor = connection.cursor()
cursor.execute(clone_schema_function)
# Ensure we have a __template__ schema.
template_schema.create_schema()
# Set the search path, so we find created models correctly
cursor = connection.cursor()
cursor.execute("SET search_path TO public,__template__;")
super(Command, self).handle_noargs(**options)
# Ensure all existing schemata exist (in case we imported them using loaddata or something)
for schema in Schema.objects.all():
schema.create_schema()
|
Fix date error in books model
Fix typos and the auto addition of date to the date_added field.
|
from django.db import models
from datetime import datetime
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
year = models.DateTimeField('year published',
help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
pages = models.IntegerField(default=0)
isbn_10 = models.IntegerField(default=0)
isbn_13 = models.IntegerField(default=0)
description = models.TextField()
cover_image = models.ImageField('cover Image',
upload_to='cover_pics/%Y-%m-%d/',
null=True,
blank=True)
date_added = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.title + " by " + self.author
def was_added_recently(self):
return self.date_added >= timezone.now() - datetime.timedelta(days=30)
|
from django.db import models
from datetime import date
from django.utils import timezone
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
year = models.DateTimeField('year published',
help_text="Please use the following format: <em>YYYY-MM-DD</em>.")
pages = models.IntegerField(default=0)
isbn_10 = models.IntegerField(default=0)
isbn_13 = models.IntegerField(default=0)
description = models.TextField()
cover_image = models.ImageField('Cover Image',
upload_to='cover_pics/%Y-%m-%d/',
null=True,
blank=True)
add_date = models.DateTimeField('date added', default=datetime.now)
def __str__(self):
return self.title + " by " + self.author
def was_added_recently(self):
return self.add_date >= timezone.now() - datetime.timedelta(days=30)
|
Update toJSON to return a string
Instead of returning the metadata object, it should return that object
encoded as a JSON string
|
'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
return output;
}
Object.defineProperty(ModelRenderer.prototype, 'metadata', {
get: function () {
return R.mapObj(R.identity, this);
},
enumerable: true
});
ModelRenderer.prototype.toJSON = function toJSON() {
return JSON.stringify(this.metadata);
};
ModelRenderer.prototype.toString = function toString() {
var output = this.modelName;
if (!isEmptyObj(this.attrs)) {
output += ':\n';
output += R.join('\n', R.map(R.apply(attrToString), R.toPairs(this.attrs)));
}
return output;
};
module.exports = ModelRenderer;
|
'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
return output;
}
Object.defineProperty(ModelRenderer.prototype, 'metadata', {
get: function () {
return R.mapObj(R.identity, this);
},
enumerable: true
});
ModelRenderer.prototype.toJSON = function toJSON() {
return R.mapObj(R.identity, this);
};
ModelRenderer.prototype.toString = function toString() {
var output = this.modelName;
if (!isEmptyObj(this.attrs)) {
output += ':\n';
output += R.join('\n', R.map(R.apply(attrToString), R.toPairs(this.attrs)));
}
return output;
};
module.exports = ModelRenderer;
|
Drop use of namespaced oslo.i18n
Related-blueprint: drop-namespace-packages
Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0
|
# Copyright 2014 Mirantis Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
|
# Copyright 2014 Mirantis Inc.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo import i18n
_translators = i18n.TranslatorFactory(domain='oslo.concurrency')
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
|
Throw interrupted exceptions from stop().
Make the arquillian container use the SwarmExector/SwarmProcess bits.
|
/**
* Copyright 2015 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.plugin.maven;
import java.util.concurrent.TimeUnit;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.wildfly.swarm.tools.exec.SwarmProcess;
/**
* @author Thomas Meyer
*/
@Mojo(name = "stop")
public class StopMojo extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
SwarmProcess process = (SwarmProcess) getPluginContext().get("swarm-process");
if(process != null) {
try {
process.stop( 10, TimeUnit.SECONDS );
} catch (InterruptedException e) {
throw new MojoFailureException( "unable to stop process", e);
}
}
}
}
|
/**
* Copyright 2015 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.plugin.maven;
import java.util.concurrent.TimeUnit;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.wildfly.swarm.tools.exec.SwarmProcess;
/**
* @author Thomas Meyer
*/
@Mojo(name = "stop")
public class StopMojo extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
SwarmProcess process = (SwarmProcess) getPluginContext().get("swarm-process");
if(process != null) {
process.stop( 10, TimeUnit.SECONDS );
}
}
}
|
Generalize the printing of APA102 encoded buffers
|
// Copyright 2016 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// playing is a small app to play with the pins, nothing more. You are not
// expected to use it as-is.
package main
import (
"fmt"
"os"
"reflect"
"github.com/maruel/dlibox-go/anim1d"
"github.com/maruel/dlibox-go/apa102"
)
func printFrame(p anim1d.Pattern, l int) {
// Generate a frame.
pixels := make(anim1d.Frame, l)
p.NextFrame(pixels, 0)
// Convert to apa102 protocol.
var d []byte
apa102.Raster(pixels, &d)
// Print it.
const cols = 16
fmt.Printf("uint8_t %s[] = {", reflect.TypeOf(p).Elem().Name())
for i, b := range d {
if i%cols == 0 {
fmt.Printf("\n ")
}
fmt.Printf("0x%02x,", b)
if i%cols != cols-1 && i != len(d)-1 {
fmt.Printf(" ")
}
}
fmt.Printf("\n};\n")
}
func mainImpl() error {
printFrame(&anim1d.Rainbow{}, 144)
printFrame(&anim1d.Color{0x7f, 0x7f, 0x7f}, 144)
return nil
}
func main() {
if err := mainImpl(); err != nil {
fmt.Fprintf(os.Stderr, "playing\n: %s.\n", err)
os.Exit(1)
}
}
|
// Copyright 2016 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// playing is a small app to play with the pins, nothing more. You are not
// expected to use it as-is.
package main
import (
"fmt"
"os"
"github.com/kr/pretty"
"github.com/maruel/dlibox-go/anim1d"
"github.com/maruel/dlibox-go/apa102"
)
func mainImpl() error {
pixels := make(anim1d.Frame, 150)
var p anim1d.Rainbow
p.NextFrame(pixels, 0)
var d []byte
apa102.Raster(pixels, &d)
pretty.Print(d)
return nil
}
func main() {
if err := mainImpl(); err != nil {
fmt.Fprintf(os.Stderr, "playing\n: %s.\n", err)
os.Exit(1)
}
}
|
Remove reference to web browsers in bazel documentation.
--
MOS_MIGRATED_REVID=115912069
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.test;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import java.util.Map;
/**
* This provider can be implemented by rules which need special environments to run in (especially
* tests).
*/
@Immutable
public final class ExecutionInfoProvider implements TransitiveInfoProvider {
private final ImmutableMap<String, String> executionInfo;
public ExecutionInfoProvider(Map<String, String> requirements) {
this.executionInfo = ImmutableMap.copyOf(requirements);
}
/**
* Returns a map to indicate special execution requirements, such as hardware
* platforms, etc. Rule tags, such as "requires-XXX", may also be added
* as keys to the map.
*/
public ImmutableMap<String, String> getExecutionInfo() {
return executionInfo;
}
}
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.test;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import java.util.Map;
/**
* This provider can be implemented by rules which need special environments to run in (especially
* tests).
*/
@Immutable
public final class ExecutionInfoProvider implements TransitiveInfoProvider {
private final ImmutableMap<String, String> executionInfo;
public ExecutionInfoProvider(Map<String, String> requirements) {
this.executionInfo = ImmutableMap.copyOf(requirements);
}
/**
* Returns a map to indicate special execution requirements, such as hardware
* platforms, web browsers, etc. Rule tags, such as "requires-XXX", may also be added
* as keys to the map.
*/
public ImmutableMap<String, String> getExecutionInfo() {
return executionInfo;
}
}
|
Update replaceCount to handle multiple instances
The previous implementation assumed that the word being replaced was
only on a line once. This updates it to count the number of times the
old string was present.
|
package far
import (
"bufio"
"os"
"strings"
)
func FileExists(path string) bool {
_, err := os.Stat(path)
if err != nil {
return false
} else {
return true
}
}
func FindAndReplace(path, current, update string) (int, error) {
file, _ := os.Open(path)
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
write_file, err := os.Create(path)
if err != nil {
panic(err)
}
defer write_file.Close()
writer := bufio.NewWriter(file)
replaceCount := 0
for _, line := range lines {
if strings.Contains(line, current) {
replaceCount += strings.Count(line, current)
line = strings.Replace(line, current, update, -1)
}
write_file.WriteString(line + "\n")
}
writer.Flush()
return replaceCount, nil
}
|
package far
import (
"bufio"
"os"
"strings"
)
func FileExists(path string) bool {
_, err := os.Stat(path)
if err != nil {
return false
} else {
return true
}
}
func FindAndReplace(path, current, update string) (int, error) {
file, _ := os.Open(path)
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
write_file, err := os.Create(path)
if err != nil {
panic(err)
}
defer write_file.Close()
writer := bufio.NewWriter(file)
replaceCount := 0
for _, line := range lines {
if strings.Contains(line, current) {
line = strings.Replace(line, current, update, -1)
replaceCount++
}
write_file.WriteString(line + "\n")
}
writer.Flush()
return replaceCount, nil
}
|
Add new validator that applies data_api_client.email_is_valid_for_admin_user to field
|
from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
from .. import data_api_client
class AdminEmailAddressValidator(object):
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
if not data_api_client.email_is_valid_for_admin_user(field.data):
raise validators.StopValidation(self.message)
class EmailAddressForm(Form):
email_address = StripWhitespaceStringField('Email address', validators=[
validators.DataRequired(message="Email can not be empty"),
validators.Email(message="Please enter a valid email address")
])
class MoveUserForm(Form):
user_to_move_email_address = StripWhitespaceStringField('Move an existing user to this supplier', validators=[
validators.DataRequired(message="Email can not be empty"),
validators.Email(message="Please enter a valid email address")
])
class EmailDomainForm(Form):
new_buyer_domain = StripWhitespaceStringField('Add a buyer email domain', validators=[
validators.DataRequired(message="The domain field can not be empty.")
])
|
from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
class EmailAddressForm(Form):
email_address = StripWhitespaceStringField('Email address', validators=[
validators.DataRequired(message="Email can not be empty"),
validators.Email(message="Please enter a valid email address")
])
class MoveUserForm(Form):
user_to_move_email_address = StripWhitespaceStringField('Move an existing user to this supplier', validators=[
validators.DataRequired(message="Email can not be empty"),
validators.Email(message="Please enter a valid email address")
])
class EmailDomainForm(Form):
new_buyer_domain = StripWhitespaceStringField('Add a buyer email domain', validators=[
validators.DataRequired(message="The domain field can not be empty.")
])
|
Fix Gulp config due to latest evolutions
|
/* === PLUGINS === */
const gulp = require('gulp'),
rimraf = require('gulp-rimraf'),
webpack = require('webpack-stream'),
sequence = require('run-sequence');
/* === CONFIG === */
const config = {
src: 'src/main/**/*',
target: 'dist/',
cfg: {
webpack: './webpack.config.js',
jshint: '.jshintrc'
}
};
/* === TASKS === */
gulp.task('clean', function () {
return gulp.src(config.target, {read: false}).pipe(rimraf());
});
gulp.task('webpack:build', function () {
return gulp.src(config.src)
.pipe(webpack(require(config.cfg.webpack)))
.pipe(gulp.dest(config.target));
});
gulp.task('webpack:watch', function () {
return gulp.watch(config.src, ['webpack:build']);
});
// Shortcut tasks
gulp.task('build', function (callback) {
sequence('clean', 'webpack:build', callback);
});
gulp.task('watch', ['webpack:watch']);
gulp.task('default', ['build']);
|
/* === PLUGINS === */
const gulp = require('gulp'),
rimraf = require('gulp-rimraf'),
webpack = require('webpack-stream'),
sequence = require('run-sequence');
/* === CONFIG === */
const config = {
src: {
js: 'src/main/js/**/*',
},
target: 'dist/',
cfg: {
webpack: './webpack.config.js',
jshint: '.jshintrc'
}
};
/* === TASKS === */
gulp.task('clean', function () {
return gulp.src(config.target, {read: false}).pipe(rimraf());
});
gulp.task('webpack:build', function () {
return gulp.src(config.src.js)
.pipe(webpack(require(config.cfg.webpack)))
.pipe(gulp.dest(config.target));
});
gulp.task('webpack:watch', function () {
return gulp.watch(config.src.js, ['webpack:build']);
});
// Shortcut tasks
gulp.task('build', function (callback) {
sequence('clean', 'webpack:build', callback);
});
gulp.task('watch', ['webpack:watch']);
gulp.task('default', ['build']);
|
Add Model in operation type
|
package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
// Class is the metadata of the node
type Class struct {
gorm.Model
Name string //The name of NodeType
Base string //Base type name
Operations []Operation //Operation of type
}
// Operation is action of type
type Operation struct {
gorm.Model
ClassID int `gorm:"index"` //Foreign key of the Class
Implementor string //Function implement the operation
}
func (p *Class) Invoke(name string, node *Node) (NodeStatus, error) {
return NodeStatusRed, fmt.Errorf("TBD")
}
func init() {
Models["Class"] = classDesc()
Models["Operation"] = operationDesc()
}
func operationDesc() *ModelDescriptor {
return &ModelDescriptor{
Type: &Operation{},
New: func() interface{} {
return &Operation{}
},
NewSlice:func() interface{} {
return &[]Operation{}
},
}
}
func classDesc() *ModelDescriptor {
return &ModelDescriptor{
Type: &Class{},
New: func() interface{} {
return &Class{}
},
NewSlice:func() interface{} {
return &[]Class{}
},
}
}
|
package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
// Class is the metadata of the node
type Class struct {
gorm.Model
Name string //The name of NodeType
Base string //Base type name
Operations []Operation //Operation of type
}
// Operation is action of type
type Operation struct {
ClassID int `gorm:"index"` //Foreign key of the Class
Implementor string //Function implement the operation
}
func (p *Class) Invoke(name string, node *Node) (NodeStatus, error) {
return NodeStatusRed, fmt.Errorf("TBD")
}
func init() {
Models["Class"] = classDesc()
Models["Operation"] = operationDesc()
}
func operationDesc() *ModelDescriptor {
return &ModelDescriptor{
Type: &Operation{},
New: func() interface{} {
return &Operation{}
},
NewSlice:func() interface{} {
return &[]Operation{}
},
}
}
func classDesc() *ModelDescriptor {
return &ModelDescriptor{
Type: &Class{},
New: func() interface{} {
return &Class{}
},
NewSlice:func() interface{} {
return &[]Class{}
},
}
}
|
Make sure port is an int
|
import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
try:
host = os.environ['STATSD_HOST']
port = int(os.environ['STATSD_PORT'])
prefix = os.environ.get('STATSD_PREFIX')
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, KeyError):
statsd = None
|
import socket
import os
try:
from django.conf import settings
except ImportError:
settings = None
from client import StatsClient
__all__ = ['StatsClient', 'statsd']
VERSION = (0, 4, 0)
__version__ = '.'.join(map(str, VERSION))
if settings:
try:
host = getattr(settings, 'STATSD_HOST', 'localhost')
port = getattr(settings, 'STATSD_PORT', 8125)
prefix = getattr(settings, 'STATSD_PREFIX', None)
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, ImportError):
try:
host = os.environ['STATSD_HOST']
port = os.environ['STATSD_PORT']
prefix = os.environ.get('STATSD_PREFIX')
statsd = StatsClient(host, port, prefix)
except (socket.error, socket.gaierror, KeyError):
statsd = None
|
Fix build break related to TUSCANY-1102
git-svn-id: d03bf258fa706134e13af30ae75b879a77d8986d@508535 13f79535-47bb-0310-9956-ffa450edef68
|
package org.apache.tuscany.sdo.test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AllTests extends TestCase {
public static TestSuite suite() {
TestSuite suite = new TestSuite();
// suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class);
suite.addTestSuite(ChangeSummaryGenTestCase.class);
suite.addTestSuite(GenPatternsTestCase.class);
//suite.addTestSuite(org.apache.tuscany.sdo.test.StaticSequenceNoEmfTestCase.class);
return suite;
}
/**
* Runs the test suite using the textual runner.
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
|
package org.apache.tuscany.sdo.test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AllTests extends TestCase {
public static TestSuite suite() {
TestSuite suite = new TestSuite();
// suite.addTestSuite(ChangeSummaryOnDataObjectTestCase.class);
suite.addTestSuite(ChangeSummaryGenTestCase.class);
suite.addTestSuite(GenPatternsTestCase.class);
suite.addTestSuite(org.apache.tuscany.sdo.test.StaticSequenceNoEmfTestCase.class);
return suite;
}
/**
* Runs the test suite using the textual runner.
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
|
Add a test for mapPropsOnChange
|
import test from 'ava'
import React from 'react'
import { mapPropsOnChange, withState, flattenProp, compose } from '../'
import { mount } from 'enzyme'
import sinon from 'sinon'
test('mapPropsOnChange maps subset of owner props to child props', t => {
const mapSpy = sinon.spy()
const StringConcat = compose(
withState('strings', 'updateStrings', { a: 'a', b: 'b', c: 'c' }),
flattenProp('strings'),
mapPropsOnChange(
['a', 'b'],
({ a, b, ...props }) => {
mapSpy()
return {
...props,
foobar: a + b
}
}
)
)('div')
t.is(StringConcat.displayName, 'withState(flattenProp(mapPropsOnChange(div)))')
const div = mount(<StringConcat />).find('div')
const { updateStrings } = div.props()
t.is(div.prop('foobar'), 'ab')
t.is(mapSpy.callCount, 1)
// Does not re-map for non-dependent prop updates
updateStrings(strings => ({ ...strings, c: 'baz' }))
t.is(div.prop('foobar'), 'ab')
t.is(div.prop('c'), 'baz')
t.is(mapSpy.callCount, 1)
updateStrings(strings => ({ ...strings, a: 'foo', 'b': 'bar' }))
t.is(div.prop('foobar'), 'foobar')
t.is(mapSpy.callCount, 2)
})
|
import test from 'ava'
import React from 'react'
import { mapPropsOnChange, withState, flattenProp, compose } from '../'
import { mount } from 'enzyme'
import sinon from 'sinon'
test('mapPropsOnChange maps subset of owner props to child props', t => {
const mapSpy = sinon.spy()
const StringConcat = compose(
withState('strings', 'updateStrings', { a: 'a', b: 'b', c: 'c' }),
flattenProp('strings'),
mapPropsOnChange(
['a', 'b'],
({ a, b, ...props }) => {
mapSpy()
return {
...props,
foobar: a + b
}
}
)
)('div')
t.is(StringConcat.displayName, 'withState(flattenProp(mapPropsOnChange(div)))')
const div = mount(<StringConcat />).find('div')
const { updateStrings } = div.props()
t.is(div.prop('foobar'), 'ab')
t.is(mapSpy.callCount, 1)
// Does not re-map for non-dependent prop updates
updateStrings(strings => ({ ...strings, c: 'baz' }))
t.is(div.prop('foobar'), 'ab')
t.is(mapSpy.callCount, 1)
updateStrings(strings => ({ ...strings, a: 'foo', 'b': 'bar' }))
t.is(div.prop('foobar'), 'foobar')
t.is(mapSpy.callCount, 2)
})
|
Add unit test to check if the environment returns a correct type
|
# coding=utf-8
'''
Test case for utils/__init__.py
'''
from __future__ import unicode_literals, print_function, absolute_import
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pytest = None
import salt.utils
@skipIf(pytest is None, 'PyTest is missing')
class UtilsTestCase(TestCase):
'''
Test case for utils/__init__.py
'''
def test_get_module_environment_empty(self):
'''
Test for salt.utils.get_module_environment
Test if empty globals returns to an empty environment
with the correct type.
:return:
'''
out = salt.utils.get_module_environment({})
assert out == {}
assert isinstance(out, dict)
|
# coding=utf-8
'''
Test case for utils/__init__.py
'''
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pytest = None
import salt.utils
@skipIf(pytest is None, 'PyTest is missing')
class UtilsTestCase(TestCase):
'''
Test case for utils/__init__.py
'''
def test_get_module_environment(self):
'''
Test for salt.utils.get_module_environment
:return:
'''
_globals = {}
salt.utils.get_module_environment(_globals)
|
Replace Entry's created's auto_now_add=True with default=datetime.now
|
from datetime import datetime
from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(default=datetime.now)
active = models.BooleanField(default=True)
class Meta:
ordering = ['-created']
verbose_name_plural = "entries"
def get_language(self):
return utils.get_language(self.language)
def get_mimetype(self):
return utils.get_mimetype(self.language)
def get_filename(self):
return '%s.%s' % (self.id, self.get_extension())
def get_extension(self):
return utils.get_extension(self.language)
def __unicode__(self):
return '<Entry: id=%s lang=%s>' % (self.id, self.language)
class EditToken(models.Model):
entry = models.ForeignKey(Entry, unique=True)
token = models.CharField(max_length=8)
expires = models.DateTimeField()
def __unicode__(self):
return '<EditToken: entry=%s token=%s>' % (self.entry_id, self.token)
|
from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ['-created']
verbose_name_plural = "entries"
def get_language(self):
return utils.get_language(self.language)
def get_mimetype(self):
return utils.get_mimetype(self.language)
def get_filename(self):
return '%s.%s' % (self.id, self.get_extension())
def get_extension(self):
return utils.get_extension(self.language)
def __unicode__(self):
return '<Entry: id=%s lang=%s>' % (self.id, self.language)
class EditToken(models.Model):
entry = models.ForeignKey(Entry, unique=True)
token = models.CharField(max_length=8)
expires = models.DateTimeField()
def __unicode__(self):
return '<EditToken: entry=%s token=%s>' % (self.entry_id, self.token)
|
Add comment about python2.7 specific code.
|
# coding: utf-8
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
'date': lambda r:
r['Buchungstag'][3:5] + '/' + r['Buchungstag'][:2] + '/' +
r['Buchungstag'][-4:],
# locale.atof does not actually know how to deal with German separators.
# So we do it the crude way
'amount': lambda r: r['Betrag'].replace('.', '').replace(',', '.'),
'desc': itemgetter('Buchungstext'),
# Unicode marker required for python2.7
'payee': itemgetter(u'Auftraggeber/Empfänger'),
}
|
# coding: utf-8
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'has_header': True,
'currency': 'EUR',
'delimiter': ';',
'bank': 'GLS Bank',
'account': itemgetter('Kontonummer'),
# Chop up the dotted German date format and put it in ridiculous M/D/Y order
'date': lambda r:
r['Buchungstag'][3:5] + '/' + r['Buchungstag'][:2] + '/' +
r['Buchungstag'][-4:],
# locale.atof does not actually know how to deal with German separators.
# So we do it the crude way
'amount': lambda r: r['Betrag'].replace('.', '').replace(',', '.'),
'desc': itemgetter('Buchungstext'),
'payee': itemgetter(u'Auftraggeber/Empfänger'),
}
|
Add create and remove file for setUp and tearDown
|
import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket, test_dir, test_file
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
test_file = 'bucketeer_test_file'
def setUp(self):
# Create a bucket to test on existing bucket
connection = boto.connect_s3()
bucket = connection.create_bucket(existing_bucket)
# Create directory to house test files
os.makedirs(test_dir)
# Create test file
open(test_dir + '/' + test_file, 'w').close()
return
def tearDown(self):
# Remove bucket created to test on existing bucket
connection = boto.connect_s3()
bucket = connection.delete_bucket(existing_bucket)
# Remove test file
os.remove(test_dir + '/' + test_file)
# Remove directory created to house test files
os.rmdir(test_dir)
return
def testMain(self):
self.assertTrue(commit)
if __name__ == '__main__':
unittest.main()
|
import unittest, boto, os
from bucketeer import commit
class BuckeeterTest(unittest.TestCase):
global existing_bucket, test_dir
existing_bucket = 'bucket.exists'
test_dir = 'bucketeer_test_dir'
def setUp(self):
# Create a bucket to test on existing bucket
connection = boto.connect_s3()
bucket = connection.create_bucket(existing_bucket)
# Create directory to house test files
os.makedirs(test_dir)
return
def tearDown(self):
# Remove bucket created to test on existing bucket
connection = boto.connect_s3()
bucket = connection.delete_bucket(existing_bucket)
# Remove directory created to house test files
os.rmdir(test_dir)
return
def testMain(self):
self.assertTrue(commit)
if __name__ == '__main__':
unittest.main()
|
Make all changes to app/ run on all trybot platforms, not just the big three.
Anyone who's changing a header here may break the chromeos build.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2838027
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@51000 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogenerated window resources files are off limits
r'.*resource.h$',
)
def CheckChangeOnUpload(input_api, output_api):
results = []
black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
sources = lambda x: input_api.FilterSourceFile(
x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
results.extend(input_api.canned_checks.CheckChangeLintsClean(
input_api, output_api, sources))
return results
def GetPreferredTrySlaves():
return ['win', 'linux', 'linux_view', 'linux_chromeos', 'mac']
|
#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Makes sure that the app/ code is cpplint clean."""
INCLUDE_CPP_FILES_ONLY = (
r'.*\.cc$', r'.*\.h$'
)
EXCLUDE = (
# Autogenerated window resources files are off limits
r'.*resource.h$',
)
def CheckChangeOnUpload(input_api, output_api):
results = []
black_list = input_api.DEFAULT_BLACK_LIST + EXCLUDE
sources = lambda x: input_api.FilterSourceFile(
x, white_list=INCLUDE_CPP_FILES_ONLY, black_list=black_list)
results.extend(input_api.canned_checks.CheckChangeLintsClean(
input_api, output_api, sources))
return results
|
Remove save call in build storage
|
import Dispatcher from '../dispatcher';
import Store from './store';
import {BUILDS_RECEIVE} from '../constants';
import {sortByAttributeComparator, Storage} from '../utils';
var storage = new Storage();
class BuildStore extends Store {
constructor() {
super();
this._loading = false;
this.key = 'builds';
}
getAll() {
return this.data.sort(sortByAttributeComparator('-id'));
}
getBuild(owner, project, buildNumber) {
return this.getItem(owner + project + buildNumber.toString());
}
isLoading() {
return this._loading;
}
}
var store = new BuildStore();
store.dispatcherToken = Dispatcher.register(payload => {
var actions = {};
actions[BUILDS_RECEIVE] = payload => {
var builds = storage.getItem('builds') || {};
payload.action.builds.forEach(build => {
var key = build.project.owner + build.project.name + build.build_number.toString();
build.key = key;
store.setItem(key, build);
});
store._loading = false;
store.emitChange();
};
if (actions.hasOwnProperty(payload.action.type)) {
actions[payload.action.type](payload);
}
});
export default store;
|
import Dispatcher from '../dispatcher';
import Store from './store';
import {BUILDS_RECEIVE} from '../constants';
import {sortByAttributeComparator, Storage} from '../utils';
var storage = new Storage();
class BuildStore extends Store {
constructor() {
super();
this._loading = false;
this.key = 'builds';
}
getAll() {
return this.data.sort(sortByAttributeComparator('-id'));
}
getBuild(owner, project, buildNumber) {
return this.getItem(owner + project + buildNumber.toString());
}
isLoading() {
return this._loading;
}
}
var store = new BuildStore();
store.dispatcherToken = Dispatcher.register(payload => {
var actions = {};
actions[BUILDS_RECEIVE] = payload => {
var builds = storage.getItem('builds') || {};
payload.action.builds.forEach(build => {
var key = build.project.owner + build.project.name + build.build_number.toString();
build.key = key;
store.setItem(key, build);
});
store.save();
store._loading = false;
store.emitChange();
};
if (actions.hasOwnProperty(payload.action.type)) {
actions[payload.action.type](payload);
}
});
export default store;
|
Split the start_date for better data entry (and Javascript date pickers).
|
import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
Make PowerSet method more compact
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package recursion
// PowerSet returns a power set of s.
// The length of s must be less then size of int.
// If the size is equal or bigger, then nil interface and false is returned.
func PowerSet(s []interface{}) (ps []interface{}, ok bool) {
if len(s) >= intSize {
return ps, false
}
for i := 0; i < (1 << uint(len(s))); i++ {
var ss []interface{}
// x == 0 indicates sub-set end.
// x &= (x - 1) ensures that the iteration count will be the same as number of bits set to 1 in x.
for x := i; x > 0; x &= (x - 1) {
lsb, i := x&-x, 0 // x&-x is same as x&^(x - 1).
for p := 1; lsb&p == 0; p = p << 1 { // lsb must always be greater then 0, which is always true 'cause x > 0.
i++ // Compute the index of x's least significant bit.
}
ss = append(ss, s[i])
}
ps = append(ps, ss)
}
return ps, true
}
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package recursion
// PowerSet returns a power set of s.
// The length of s must be less then size of int.
// If the size is equal or bigger, then nil interface and false is returned.
func PowerSet(s []interface{}) (ps []interface{}, ok bool) {
if len(s) >= intSize {
return ps, false
}
for i := 0; i < (1 << uint(len(s))); i++ {
x := i
var ss []interface{}
for x > 0 {
lsb := x & -x // x & -x is same as x & ^(x - 1).
// Compute the index of x's least significant bit.
i := 0
p := 1
for lsb&p == 0 { // lsb must always be greater then 0, which is always true 'cause x > 0.
p <<= 1
i++
}
ss = append(ss, s[i])
x &= (x - 1) // This ensures that the iteration count will be the same as number of 1 bits in x.
// x == 0 indicates sub-set end.
}
ps = append(ps, ss)
}
return ps, true
}
|
Remove old JS code in the normalization report
This fixes a JS `Uncaught TypeError` error in the normalization report
caused by code that was used to setup dialogs for displaying job
information but which were removed a few years ago.
|
/*
This file is part of Archivematica.
Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
Archivematica is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Archivematica is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Archivematica. If not, see <http://www.gnu.org/licenses/>.
*/
$(function() {
// add popovers
$($.find('a.file-location'))
.popover({
trigger: 'hover',
content: function()
{
return $(this).attr('data-location').replace(/%.*%/gi, '');
}
})
.click(function(event) {
event.preventDefault();
});
});
|
/*
This file is part of Archivematica.
Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
Archivematica is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Archivematica is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Archivematica. If not, see <http://www.gnu.org/licenses/>.
*/
$(function() {
// add job viewer to generate dialogs with
var job = new Job();
job.set({'type': 'Approve Normalization'});
job.sip = new Sip();
job.sip.set({'directory': '{{ sipname }}'});
var jobView = new BaseJobView({model: job});
// add popovers
$($.find('a.file-location'))
.popover({
trigger: 'hover',
content: function()
{
return $(this).attr('data-location').replace(/%.*%/gi, '');
}
})
.click(function(event) {
event.preventDefault();
});
});
|
Support for actions in profile
|
import React, { Component } from 'react'
import { DrawerLabel } from '..'
import Avatar from 'material-ui/Avatar'
import RaisedButton from 'material-ui/RaisedButton'
import styles from './Profile.css'
const avatarStyles = {
width: 200,
height: 200,
marginLeft: 88,
marginTop: 32,
marginRight: 88,
marginBottom: 6
}
class Profile extends Component {
render () {
const { avatar, details, actions } = this.props
return (
<div style={{ overflowY: 'auto', height: '100%' }}>
{ avatar ? <Avatar src={avatar} style={avatarStyles} /> : null}
{
details.map((e, i) => (
<DrawerLabel key={i} name={e.name} value={e.value} />
))
}
{
actions ? actions.map((a, i) => (
<RaisedButton key={i} {...a} style={{ marginTop: 26 }} fullWidth={true} />
)) : null
}
</div>
)
}
}
export default Profile
|
import React, { Component } from 'react'
import { DrawerLabel } from '..'
import Avatar from 'material-ui/Avatar'
import styles from './Profile.css'
const avatarStyles = {
width: 200,
height: 200,
marginLeft: 88,
marginTop: 32,
marginRight: 88,
marginBottom: 6
}
class Profile extends Component {
render () {
const { avatar, details } = this.props
return (
<div style={{ overflowY: 'auto', height: '100%' }}>
{ avatar ? <Avatar src={avatar} style={avatarStyles} /> : null}
{
details.map((e, i) => (
<DrawerLabel key={i} name={e.name} value={e.value} />
))
}
</div>
)
}
}
export default Profile
|
Section: Set end_paragraph to True by default
|
# -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
#: A section should normally start in its own paragraph
end_paragraph = True
def __init__(self, title, numbering=True, *args, **kwargs):
""".
Args
----
title: str
The section title.
numbering: bool
Add a number before the section title.
"""
self.title = title
self.numbering = numbering
super().__init__(*args, **kwargs)
def dumps(self):
"""Represent the section as a string in LaTeX syntax.
Returns
-------
str
"""
if not self.numbering:
num = '*'
else:
num = ''
string = Command(self.latex_name + num, self.title).dumps()
string += self.dumps_content()
return string
|
# -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
def __init__(self, title, numbering=True, *args, **kwargs):
""".
Args
----
title: str
The section title.
numbering: bool
Add a number before the section title.
"""
self.title = title
self.numbering = numbering
super().__init__(*args, **kwargs)
def dumps(self):
"""Represent the section as a string in LaTeX syntax.
Returns
-------
str
"""
if not self.numbering:
num = '*'
else:
num = ''
string = Command(self.latex_name + num, self.title).dumps()
string += self.dumps_content()
return string
|
Update sim hooks for 2018
|
from hal_impl.sim_hooks import SimHooks
class PyFrcFakeHooks(SimHooks):
'''
Defines hal hooks that use the fake time object
'''
def __init__(self, fake_time):
self.fake_time = fake_time
super().__init__()
#
# Time related hooks
#
def getTime(self):
return self.fake_time.get()
def delayMillis(self, ms):
self.fake_time.increment_time_by(.001 * ms)
def delaySeconds(self, s):
self.fake_time.increment_time_by(s)
#
# DriverStation related hooks
#
@property
def ds_cond(self):
return self.fake_time.ds_cond
@ds_cond.setter
def ds_cond(self, value):
pass # ignored
|
from hal_impl.data import hal_data
class PyFrcFakeHooks:
'''
Defines hal hooks that use the fake time object
'''
def __init__(self, fake_time):
self.fake_time = fake_time
#
# Hook functions
#
def getTime(self):
return self.fake_time.get()
def getFPGATime(self):
return int((self.fake_time.get() - hal_data['time']['program_start']) * 1000000)
def delayMillis(self, ms):
self.fake_time.increment_time_by(.001 * ms)
def delaySeconds(self, s):
self.fake_time.increment_time_by(s)
def initializeDriverStation(self):
pass
@property
def ds_cond(self):
return self.fake_time.ds_cond
@ds_cond.setter
def ds_cond(self, value):
pass # ignored
|
Deploy Travis CI build 377 to GitHub
|
#!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
import os
if os.path.exists('README.rst'):
README = open('README.rst').read()
else:
README = "" # a placeholder, readme is generated on release
CHANGES = open('CHANGES.md').read()
setuptools.setup(
name=__project__,
version=__version__,
description="PythonTemplateDemo is a Python 3 package template.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='jacebrowning@gmail.com',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=(README + '\n' + CHANGES),
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.3',
],
install_requires=open('requirements.txt').readlines(),
)
|
#!/usr/bin/env python
"""
Setup script for PythonTemplateDemo.
"""
import setuptools
from demo import __project__, __version__
import os
if os.path.exists('README.rst'):
README = open('README.rst').read()
else:
README = "" # a placeholder, readme is generated on release
CHANGES = open('CHANGES.md').read()
setuptools.setup(
name=__project__,
version=__version__,
description="PythonTemplateDemo is a Python 3 package template.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='jacebrowning@gmail.com',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=(README + '\n' + CHANGES),
license='MIT',
classifiers=[
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.3',
],
install_requires=open('requirements.txt').readlines(),
)
|
Change MVC construct for User Fields.
|
<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_forum-stat_include.php
| Author: Digitanium
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }
if ($profile_method == "input") {
//Nothing here
$user_fields = '';
if (defined('ADMIN_PANEL')) { // To show in admin panel only.
$user_fields = "<div class='well m-t-5 text-center'>".$locale['uf_forum-stat']."</div>";
}
} elseif ($profile_method == "display") {
$user_fields = array('title'=>$locale['uf_forum-stat'], 'value'=>$user_data['user_posts']);
} elseif ($profile_method == "validate_insert") {
//Nothing here
} elseif ($profile_method == "validate_update") {
//Nothing here
}
?>
|
<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_forum-stat_include.php
| Author: Digitanium
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }
if ($profile_method == "input") {
//Nothing here
} elseif ($profile_method == "display") {
echo "<tr>\n";
echo "<td class='tbl1'>".$locale['uf_forum-stat']."</td>\n";
echo "<td align='right' class='tbl1'>".number_format($user_data['user_posts'])."</td>\n";
echo "</tr>\n";
} elseif ($profile_method == "validate_insert") {
//Nothing here
} elseif ($profile_method == "validate_update") {
//Nothing here
}
?>
|
Fix problem with {property}-changed event
In polymer 2 the following change was made:
Property change notifications (property-changed events) aren't fired when
the value changes as a result of a binding from the host
(see https://polymer-library.polymer-project.org/2.0/docs/about_20).
The polymer team suggested to use observer instead of {property}-changed
event.
Bug: Issue 11316
Change-Id: I12d1860d3ee836724c111605725d806687ec2141
|
/**
* @license
* Copyright (C) 2017 The Android Open Source Project
*
* 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.
*/
(function() {
'use strict';
Polymer({
is: 'gr-endpoint-param',
_legacyUndefinedCheck: true,
properties: {
name: String,
value: {
type: Object,
notify: true,
observer: '_valueChanged',
},
},
_valueChanged(newValue, oldValue) {
/* In polymer 2 the following change was made:
"Property change notifications (property-changed events) aren't fired when
the value changes as a result of a binding from the host"
(see https://polymer-library.polymer-project.org/2.0/docs/about_20).
To workaround this problem, we fire the event from the observer.
In some cases this fire the event twice, but our code is
ready for it.
*/
const detail = {
value: newValue,
};
this.dispatchEvent(new CustomEvent('value-changed', {detail}));
},
});
})();
|
/**
* @license
* Copyright (C) 2017 The Android Open Source Project
*
* 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.
*/
(function() {
'use strict';
Polymer({
is: 'gr-endpoint-param',
_legacyUndefinedCheck: true,
properties: {
name: String,
value: {
type: Object,
notify: true,
},
},
});
})();
|
Add version and initialize AppHelper
|
define([
'jquery',
'underscore',
'backbone',
'router',
'helpers/app',
'helpers/conf',
'helpers/usertag',
'views/sidebar',
'views/user',
'views/search',
'text!templates/body.html',
'bootstrap'
], function ($, _, Backbone, Router, AppHelper, ConfHelper, UserTagHelper,
SidebarView, UserView, SearchView, BodyTemplate) {
return {
version: '0.1.0',
initialize: function (tests) {
ConfHelper.loadConf ();
ConfHelper.switchTheme ();
ConfHelper.switchFont ();
AppHelper.initialize (this.version);
UserTagHelper.loadUserTags();
$('body').html (_.template (BodyTemplate));
AppHelper.sidebarView = new SidebarView ();
AppHelper.searchView = new SearchView();
AppHelper.userView = new UserView ();
if (!tests) {
AppHelper.sidebarView.render ();
Router.initialize ();
}
}
}
});
|
define([
'jquery',
'underscore',
'backbone',
'router',
'helpers/app',
'helpers/conf',
'helpers/usertag',
'views/sidebar',
'views/user',
'views/search',
'text!templates/body.html',
'bootstrap'
], function ($, _, Backbone, Router, AppHelper, ConfHelper, UserTagHelper,
SidebarView, UserView, SearchView, BodyTemplate) {
return {
initialize: function (tests) {
ConfHelper.loadConf ();
ConfHelper.switchTheme ();
ConfHelper.switchFont ();
UserTagHelper.loadUserTags();
$('body').html (_.template (BodyTemplate));
AppHelper.sidebarView = new SidebarView ();
AppHelper.searchView = new SearchView();
AppHelper.userView = new UserView ();
if (!tests) {
AppHelper.sidebarView.render ();
Router.initialize ();
}
}
}
});
|
Comment out the Shove object, as we are not using it yet
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
#from myfedora.streams import DataStreamer
#self.datastreamer = DataStreamer()
#FEED_CACHE = "/tmp/moksha-feeds"
#from shove import Shove
#from feedcache.cache import Cache
#self.feed_storage = Shove('file://' + FEED_CACHE)
#self.feed_cache = Cache(self.feed_storage)
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
#from myfedora.streams import DataStreamer
#self.datastreamer = DataStreamer()
FEED_CACHE = "/tmp/moksha-feeds"
from shove import Shove
from feedcache.cache import Cache
self.feed_storage = Shove('file://' + FEED_CACHE)
self.feed_cache = Cache(self.feed_storage)
|
Add unique id for each wav file
|
import os
import logging
import gevent
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
import string
import random
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
def rand_id(size=8):
return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(size))
@app.route('/', methods=['GET', 'POST'])
def main():
return redirect(url_for('static', filename='index.html'))
@sockets.route('/submit')
def submit(ws):
user_id = rand_id()
while not ws.closed:
gevent.sleep()
data = ws.receive()
if data and data != "start":
file_name = "_".join(["file", user_id, rand_id()])
wave_file = io.open(file_name, "wb")
wave_file.write(data)
wave_file.close()
# process_file(file_name)
|
import os
import logging
import gevent
from flask import Flask, render_template, url_for, redirect
from flask_sockets import Sockets
import io
app = Flask(__name__)
path = os.getcwd()
app.config['DEBUG'] = True
sockets = Sockets(app)
@app.route('/', methods=['GET', 'POST'])
def main():
return redirect(url_for('static', filename='index.html'))
@sockets.route('/submit')
def submit(ws):
while not ws.closed:
gevent.sleep()
data = ws.receive()
if data:
ws.send("ayy lmao")
wave_file = io.open("test.wav", "wb")
wave_file.write(data)
wave_file.close()
|
Use PingFactory for more testable code
|
<?php
namespace Loct\Pinger\Provider;
use \Loct\Pinger\Command\PingCommand;
use \Loct\Pinger\PingFactory;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;
/**
* Service provider for command related classes and parameters.
*
* @author herloct <herloct@gmail.com>
*/
class CommandProvider implements ServiceProviderInterface
{
/**
* Registers services on the given container.
*
* This method should only be used to configure services and parameters.
* It should not get services.
*
* @param Container $pimple An Container instance
*/
public function register(Container $pimple)
{
$pimple['ping_command'] = function ($pimple)
{
$config = $pimple['config'];
$factory = new PingFactory();
$notifier = $pimple['notifier'];
$hosts = $config->get('pinger.hosts');
return new PingCommand($factory, $notifier, $hosts);
};
}
}
|
<?php
namespace Loct\Pinger\Provider;
use \Loct\Pinger\Command\PingCommand;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;
/**
* Service provider for command related classes and parameters.
*
* @author herloct <herloct@gmail.com>
*/
class CommandProvider implements ServiceProviderInterface
{
/**
* Registers services on the given container.
*
* This method should only be used to configure services and parameters.
* It should not get services.
*
* @param Container $pimple An Container instance
*/
public function register(Container $pimple)
{
$pimple['ping_command'] = function ($pimple)
{
$config = $pimple['config'];
$hosts = $config->get('pinger.hosts');
$notifier = $pimple['notifier'];
return new PingCommand($hosts, $notifier);
};
}
}
|
Include radix in parseInt call
The default is not guaranteed to be 10.
|
(function () {
"use strict";
$(document).ready(function() {
if ($('select').is('#active_filter')){
var page_size = parseInt($('select').attr("value"), 10);
var table = $('table').dataTable(
{ "pageLength" : page_size,
"search": {
"caseInsensitive": false
},
"ordering": false
});
$('.dataTables_filter').hide();
$('#active_filter').prop('selectedIndex',0);
$('#active_filter').on('change', function() {
if (this.value !== "All") {
table.fnFilter( $(this).val());
}
else {
table.fnFilter("");
}
});
}
});
})();
|
(function () {
"use strict";
$(document).ready(function() {
if ($('select').is('#active_filter')){
var page_size = parseInt($('select').attr("value"));
var table = $('table').dataTable(
{ "pageLength" : page_size,
"search": {
"caseInsensitive": false
},
"ordering": false
});
$('.dataTables_filter').hide();
$('#active_filter').prop('selectedIndex',0);
$('#active_filter').on('change', function() {
if (this.value !== "All") {
table.fnFilter( $(this).val());
}
else {
table.fnFilter("");
}
});
}
});
})();
|
Add example of logging setting for Manila
This change demonstrates how we can define logging setting specific to
manila-ui, so that operators can easily understand how to customize
logging level and so on.
Change-Id: Ia8505d988ed75e0358452b5b3c2889b364680f22
|
# Copyright 2016 Red Hat 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
#
# 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.
# Sample
# settings.LOGGING['loggers'].update({
# 'manilaclient': {
# 'handlers': ['console'],
# 'level': 'DEBUG',
# 'propagate': False,
# }
# })
# The OPENSTACK_MANILA_FEATURES settings can be used to enable or disable
# the UI for the various services provided by Manila.
OPENSTACK_MANILA_FEATURES = {
'enable_share_groups': True,
'enable_replication': True,
'enable_migration': True,
'enable_public_share_type_creation': True,
'enable_public_share_group_type_creation': True,
'enable_public_shares': True,
'enabled_share_protocols': ['NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS',
'MapRFS'],
}
|
# Copyright 2016 Red Hat 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
#
# 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.
# The OPENSTACK_MANILA_FEATURES settings can be used to enable or disable
# the UI for the various services provided by Manila.
OPENSTACK_MANILA_FEATURES = {
'enable_share_groups': True,
'enable_replication': True,
'enable_migration': True,
'enable_public_share_type_creation': True,
'enable_public_share_group_type_creation': True,
'enable_public_shares': True,
'enabled_share_protocols': ['NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS',
'MapRFS'],
}
|
Support event on root element
|
// Events are in the Backbone form of
// {
// '[type] [selector]':'[function]'
// '[type]' :'[function]'
// }
// where selector may have a space, e.g. 'foo > bar'
function DOMViewMixin(view) {
var _this = this;
var events = view.events || {};
for (var key in events) {
if (events.hasOwnProperty(key)) {
var firstSpaceIndex = key.indexOf(' ');
// Event on root element
var type;
var selector;
if (firstSpaceIndex === -1) {
type = key;
} else {
type = key.substr(0, firstSpaceIndex);
selector = key.substr(firstSpaceIndex + 1);
}
var fn = events[key];
(function(fn) {
var elem = (selector === undefined) ? view.$el : view.$el.find(selector);
if (!elem.length) {
console.warn('no selector "' + selector + '" on view');
}
elem[type](function(event) {
if (_this[fn] === undefined) {
throw new Error('mixin target has no function: ' + fn);
}
_this[fn](event);
});
})(fn);
}
}
}
module.exports = DOMViewMixin;
|
// Events are in the Backbone form of
// {
// '[type] [selector]':'[function]'
// }
// where selector may have a space, e.g. 'foo > bar'
function DOMViewMixin(view) {
var _this = this;
var events = view.events || {};
for (var key in events) {
if (events.hasOwnProperty(key)) {
var firstSpaceIndex = key.indexOf(' ');
var type = key.substr(0, firstSpaceIndex);
var selector = key.substr(firstSpaceIndex + 1);
var fn = events[key];
(function(fn) {
view.$el.find(selector)[type](function(event) {
if (_this[fn] === undefined) {
throw new Error('mixin target has no function: ' + fn);
}
_this[fn](event);
});
})(fn);
}
}
}
module.exports = DOMViewMixin;
|
Remove unused import to fix flake8
|
import os
import vcr
from django.test import TestCase
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
|
import os
import vcr
from django.test import TestCase, override_settings
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
|
Fix wrong wording and spelling
|
export default {
today: 'I dag',
now: 'Nu',
backToToday: 'Gå til i dag',
ok: 'Ok',
clear: 'Annuller',
month: 'Måned',
year: 'År',
timeSelect: 'Vælg tidspunkt',
dateSelect: 'Vælg dato',
monthSelect: 'Vælg måned',
yearSelect: 'Vælg år',
decadeSelect: 'Vælg årti',
yearFormat: 'YYYY',
dateFormat: 'D/M/YYYY',
dayFormat: 'D',
dateTimeFormat: 'D/M/YYYY HH:mm:ss',
monthFormat: 'MMMM',
monthBeforeYear: true,
previousMonth: 'Forrige måned(PageUp)',
nextMonth: 'Næste måned (PageDown)',
previousYear: 'Forrige år (Control + left)',
nextYear: 'Næste r (Control + right)',
previousDecade: 'Forrige årti',
nextDecade: 'Næste årti',
previousCentury: 'Forrige århundrede',
nextCentury: 'Næste århundrede',
};
|
export default {
today: 'I dag',
now: 'Nu',
backToToday: 'Tilbage til i dag',
ok: 'Ok',
clear: 'Annuler',
month: 'Måned',
year: 'År',
timeSelect: 'Vælg tidspunkt',
dateSelect: 'Vælg dato',
monthSelect: 'Vælg måned',
yearSelect: 'Vælg år',
decadeSelect: 'Vælg årti',
yearFormat: 'YYYY',
dateFormat: 'D/M/YYYY',
dayFormat: 'D',
dateTimeFormat: 'D/M/YYYY HH:mm:ss',
monthFormat: 'MMMM',
monthBeforeYear: true,
previousMonth: 'Forrige måned(PageUp)',
nextMonth: 'Næste måned (PageDown)',
previousYear: 'Forrige år (Control + left)',
nextYear: 'Næste r (Control + right)',
previousDecade: 'Forrige årti',
nextDecade: 'Næste årti',
previousCentury: 'Forrige århundrede',
nextCentury: 'Næste århundrede',
};
|
Remove if branch to test django > 1.7
|
import os
import sys
import dj_database_url
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
from django.test.runner import DiscoverRunner
BASEDIR = os.path.dirname(os.path.dirname(__file__))
settings.configure(
DATABASES={
'default': dj_database_url.config(
default='sqlite://{}/user_deletion.db'.format(BASEDIR),
),
},
INSTALLED_APPS=('user_deletion',),
MIDDLEWARE_CLASSES=(),
)
django.setup()
class TestRunner(ColourRunnerMixin, DiscoverRunner):
"""Enable colorised output."""
test_runner = TestRunner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
import os
import sys
import dj_database_url
import django
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
from django.test.runner import DiscoverRunner
BASEDIR = os.path.dirname(os.path.dirname(__file__))
settings.configure(
DATABASES={
'default': dj_database_url.config(
default='sqlite://{}/user_deletion.db'.format(BASEDIR),
),
},
INSTALLED_APPS=('user_deletion',),
MIDDLEWARE_CLASSES=(),
)
if django.VERSION >= (1, 7):
django.setup()
class TestRunner(ColourRunnerMixin, DiscoverRunner):
"""Enable colorised output."""
test_runner = TestRunner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
[CallResponder] Add calls to list of answered calls.
Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>
|
package org.duckdns.raven.ttscallresponder.tts;
import org.duckdns.raven.ttscallresponder.domain.call.Call;
import org.duckdns.raven.ttscallresponder.domain.call.PersistentCallList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
public class StartAnsweringServiceReceiver extends BroadcastReceiver {
private static final String TAG = "StartAnsweringServiceReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.i(TAG, "Phone state changed: " + state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Log.i(TAG, "Ringing - preparing service");
Intent startResponderService = new Intent(context, TtsAnsweringService.class);
context.startService(startResponderService);
Log.i(TAG, "Service started");
Log.i(TAG, "Adding to answered calls: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
PersistentCallList callList = new PersistentCallList(context.getFilesDir());
callList.add(new Call(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)));
callList.savePersistentList();
}
}
}
|
package org.duckdns.raven.ttscallresponder.tts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
public class StartAnsweringServiceReceiver extends BroadcastReceiver {
private static final String TAG = "StartAnsweringServiceReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.i(TAG, "Phone state changed: " + state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Log.i(TAG, "Ringing - preparing service");
Intent startResponderService = new Intent(context, TtsAnsweringService.class);
context.startService(startResponderService);
Log.i(TAG, "Service started");
}
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.i(TAG, "InCall - answering");
}
}
}
|
Add slow down carousel speed
|
$(document).ready(function () {
$(".carousel-inner-download").cycle({
fx:'scrollVert',
pager: '.pager',
timeout: 4000,
speed: 1000,
// pause: 1,
});
$(".c1-right").on("click", function(e) {
var activeImage = $(".c1-image-shown");
var nextImage = activeImage.next();
if(nextImage.length == 0) {
nextImage = $(".slider-inner img").first();
};
activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index",-10);;
nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index",20);
$(".slider-inner img").not([activeImage, nextImage]).css("z-index",1);
});
$(".c1-left").on("click", function(e){
var activeImage = $(".c1-image-shown");
var nextImage = activeImage.prev();
if(nextImage.length == 0) {
nextImage = $('.slider-inner img').last();
}
activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index", -10);
nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index", 20);
$('.slider-inner img').not([activeImage, nextImage]).css("z-index", 1);
})
});
|
$(document).ready(function () {
$(".carousel-inner-download").cycle({
fx:'scrollVert',
pager: '.pager',
timeout: 4000,
speed: 500,
// pause: 1,
});
$(".c1-right").on("click", function(e) {
var activeImage = $(".c1-image-shown");
var nextImage = activeImage.next();
if(nextImage.length == 0) {
nextImage = $(".slider-inner img").first();
};
activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index",-10);;
nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index",20);
$(".slider-inner img").not([activeImage, nextImage]).css("z-index",1);
});
$(".c1-left").on("click", function(e){
var activeImage = $(".c1-image-shown");
var nextImage = activeImage.prev();
if(nextImage.length == 0) {
nextImage = $('.slider-inner img').last();
}
activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index", -10);
nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index", 20);
$('.slider-inner img').not([activeImage, nextImage]).css("z-index", 1);
})
});
|
Stop PE server only if it was running
|
package protocolsupport;
import java.util.logging.Level;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;
public class ProtocolSupport extends Plugin {
private PEProxyServer peserver;
@Override
public void onLoad() {
try {
getProxy().getPluginManager().registerCommand(this, new CommandHandler());
BungeeNettyChannelInjector.inject();
} catch (Throwable t) {
t.printStackTrace();
ProxyServer.getInstance().stop();
}
}
@Override
public void onEnable() {
if (Utils.getJavaPropertyValue("enablepe", false, Boolean::parseBoolean)) {
getLogger().log(Level.INFO, "Enabling MCPE support");
(peserver = new PEProxyServer()).start();
}
}
@Override
public void onDisable() {
if (peserver != null) {
peserver.stop();
}
}
}
|
package protocolsupport;
import java.util.logging.Level;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;
public class ProtocolSupport extends Plugin {
private PEProxyServer peserver;
@Override
public void onLoad() {
try {
getProxy().getPluginManager().registerCommand(this, new CommandHandler());
BungeeNettyChannelInjector.inject();
} catch (Throwable t) {
t.printStackTrace();
ProxyServer.getInstance().stop();
}
}
@Override
public void onEnable() {
if (Utils.getJavaPropertyValue("enablepe", false, Boolean::parseBoolean)) {
getLogger().log(Level.INFO, "Enabling MCPE support");
(peserver = new PEProxyServer()).start();
}
}
@Override
public void onDisable() {
peserver.stop();
}
}
|
Update for React changes in API.
|
/**
*/
var React = require('react');
var ReactDOM = require('react-dom');
exports.ResultModal = React.createClass({
/**
* Invoked immediately after updating occurs. This method is not called for the initial render.
*/
componentDidUpdate: function (prevProps, prevState) {
// Show only if truthy.
if (this.props.dieString) {
// Trigger Bootstrap's modal functionality.
$(ReactDOM.findDOMNode(this)).modal();
}
},
render: function () {
/*jshint ignore:start*/
return (
<div id="ResultModal" className="modal fade"
tabIndex="-1" role="dialog" aria-labelledby="ResultModal" aria-hidden="true">
<div className="modal-dialog modal-sm">
<div className="modal-content">
<p className="text-center">{this.props.timeStamp}</p>
<h1 className="text-center">{this.props.dieResult}</h1>
<p className="text-center">{this.props.dieString}</p>
</div>
</div>
</div>
);
/*jshint ignore:end*/
}
});
|
/**
* @jsx React.DOM
*/
var React = require('react');
exports.ResultModal = React.createClass({
/**
* Invoked immediately after updating occurs. This method is not called for the initial render.
*/
componentDidUpdate: function (prevProps, prevState) {
// Show only if truthy.
if (this.props.dieString) {
// Trigger Bootstrap's modal functionality.
$(this.getDOMNode()).modal();
}
},
render: function () {
/*jshint ignore:start*/
return (
<div id="ResultModal" className="modal fade"
tabIndex="-1" role="dialog" aria-labelledby="ResultModal" aria-hidden="true">
<div className="modal-dialog modal-sm">
<div className="modal-content">
<p className="text-center">{this.props.timeStamp}</p>
<h1 className="text-center">{this.props.dieResult}</h1>
<p className="text-center">{this.props.dieString}</p>
</div>
</div>
</div>
);
/*jshint ignore:end*/
}
});
|
Add Tag List Panel Handle to Main Gui Handle
|
package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
import seedu.todo.TestApp;
/**
* Provides a handle for the main GUI.
*/
public class MainGuiHandle extends GuiHandle {
public MainGuiHandle(GuiRobot guiRobot, Stage primaryStage) {
super(guiRobot, primaryStage, TestApp.APP_TITLE);
}
public TaskListPanelHandle getTaskListPanel() {
return new TaskListPanelHandle(guiRobot, primaryStage);
}
public ResultDisplayHandle getResultDisplay() {
return new ResultDisplayHandle(guiRobot, primaryStage);
}
public CommandBoxHandle getCommandBox() {
return new CommandBoxHandle(guiRobot, primaryStage, TestApp.APP_TITLE);
}
public MainMenuHandle getMainMenu() {
return new MainMenuHandle(guiRobot, primaryStage);
}
//@@author A0142421X
public TagListPanelHandle getTagListPanel() {
return new TagListPanelHandle(guiRobot, primaryStage);
}
}
|
package guitests.guihandles;
import guitests.GuiRobot;
import javafx.stage.Stage;
import seedu.todo.TestApp;
/**
* Provides a handle for the main GUI.
*/
public class MainGuiHandle extends GuiHandle {
public MainGuiHandle(GuiRobot guiRobot, Stage primaryStage) {
super(guiRobot, primaryStage, TestApp.APP_TITLE);
}
public TaskListPanelHandle getTaskListPanel() {
return new TaskListPanelHandle(guiRobot, primaryStage);
}
public ResultDisplayHandle getResultDisplay() {
return new ResultDisplayHandle(guiRobot, primaryStage);
}
public CommandBoxHandle getCommandBox() {
return new CommandBoxHandle(guiRobot, primaryStage, TestApp.APP_TITLE);
}
public MainMenuHandle getMainMenu() {
return new MainMenuHandle(guiRobot, primaryStage);
}
}
|
Fix possible memory leak in feed.
I've observed a memory leak (on API 17) apparently stemming from the new
functionality to fill in the bookmark icon when the featured article is
detected to be part of a reading list.
This seems to be caused by us passing an anonymous instance of a
CallbackTask.Callback object from FeaturedArticleView, which contains
references to $this, which contains a reference to the activity context.
This patch solves the leak by modifying the CallbackTask to no longer hold
on to a reference of Callback, and instead null it out immediately after
it's called.
Change-Id: I768e24dab7f39652ec741a5d6f9821db7de4f2bd
|
package org.wikipedia.concurrency;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class CallbackTask<T> extends SaneAsyncTask<T> {
public interface Callback<T> {
void success(T row);
}
public interface Task<T> {
T execute();
}
@NonNull private final Task<T> task;
@Nullable private Callback<T> callback;
public static <T> void execute(@NonNull Task<T> task) {
execute(task, null);
}
public static <T> void execute(@NonNull Task<T> task, @Nullable Callback<T> callback) {
new CallbackTask<>(task, callback).execute();
}
CallbackTask(@NonNull Task<T> task, @Nullable Callback<T> callback) {
this.task = task;
this.callback = callback;
}
@Override public T performTask() throws Throwable {
return task.execute();
}
@Override public void onFinish(T result) {
super.onFinish(result);
if (callback != null) {
callback.success(result);
callback = null;
}
}
}
|
package org.wikipedia.concurrency;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class CallbackTask<T> extends SaneAsyncTask<T> {
public interface Callback<T> {
void success(T row);
}
public interface Task<T> {
T execute();
}
@NonNull private final Task<T> task;
@Nullable private final Callback<T> callback;
public static <T> void execute(@NonNull Task<T> task) {
execute(task, null);
}
public static <T> void execute(@NonNull Task<T> task, @Nullable Callback<T> callback) {
new CallbackTask<>(task, callback).execute();
}
CallbackTask(@NonNull Task<T> task, @Nullable Callback<T> callback) {
this.task = task;
this.callback = callback;
}
@Override public T performTask() throws Throwable {
return task.execute();
}
@Override public void onFinish(T result) {
super.onFinish(result);
if (callback != null) {
callback.success(result);
}
}
}
|
Add test for metadata appearing on fastbootInfo
|
var expect = require('chai').expect;
var path = require('path');
var alchemistRequire = require('broccoli-module-alchemist/require');
var FastBootInfo = alchemistRequire('fastboot-info.js');
var FastBootResponse = alchemistRequire('fastboot-response.js');
var FastBootRequest = alchemistRequire('fastboot-request.js');
describe("FastBootInfo", function() {
var response;
var request;
var fastbootInfo;
var metadata = { foo: 'bar' };
beforeEach(function () {
response = {};
request = {
cookie: "",
protocol: "http",
headers: {
},
get: function() {
return this.cookie;
}
};
fastbootInfo = new FastBootInfo(request, response, { metadata });
});
it("has a FastBootRequest", function() {
expect(fastbootInfo.request).to.be.an.instanceOf(FastBootRequest);
});
it("has a FastBootResponse", function() {
expect(fastbootInfo.response).to.be.an.instanceOf(FastBootResponse);
});
it("has metadata", function() {
expect(fastbootInfo.metadata).to.deep.equal(metadata);
});
});
|
var expect = require('chai').expect;
var path = require('path');
var alchemistRequire = require('broccoli-module-alchemist/require');
var FastBootInfo = alchemistRequire('fastboot-info.js');
var FastBootResponse = alchemistRequire('fastboot-response.js');
var FastBootRequest = alchemistRequire('fastboot-request.js');
describe("FastBootInfo", function() {
var response;
var request;
var fastbootInfo;
beforeEach(function () {
response = {};
request = {
cookie: "",
protocol: "http",
headers: {
},
get: function() {
return this.cookie;
}
};
fastbootInfo = new FastBootInfo(request, response);
});
it("has a FastBootRequest", function() {
expect(fastbootInfo.request).to.be.an.instanceOf(FastBootRequest);
});
it("has a FastBootResponse", function() {
expect(fastbootInfo.response).to.be.an.instanceOf(FastBootResponse);
});
});
|
Use info growl for game rating growl.
It fits better with the component.
|
angular.module( 'App.Game.RatingGrowl' ).service( 'Game_RatingGrowl', function( App, Api, Growls )
{
this.show = function( game )
{
// Don't show when not logged in.
if ( !App.user ) {
return;
}
// Don't show if ratings are disabled for the game.
if ( !game.ratings_enabled ) {
return;
}
// Don't show when this is the developer of the game.
if ( App.user.id == game.developer.id ) {
return;
}
Api.sendRequest( '/web/discover/games/ratings/get-user-rating/' + game.id, null, { detach: true } )
.then( function( payload )
{
// If there is a rating for this user already, don't show the growl.
if ( payload.rating ) {
return;
}
Growls.info( {
sticky: true,
templateUrl: '/app/components/game/rating-growl/rating-growl.html',
controller: 'Game_RatingGrowlCtrl',
resolve: {
game: function()
{
return game;
}
}
} );
} );
};
} );
|
angular.module( 'App.Game.RatingGrowl' ).service( 'Game_RatingGrowl', function( App, Api, Growls )
{
this.show = function( game )
{
// Don't show when not logged in.
if ( !App.user ) {
return;
}
// Don't show if ratings are disabled for the game.
if ( !game.ratings_enabled ) {
return;
}
// Don't show when this is the developer of the game.
if ( App.user.id == game.developer.id ) {
return;
}
Api.sendRequest( '/web/discover/games/ratings/get-user-rating/' + game.id, null, { detach: true } )
.then( function( payload )
{
// If there is a rating for this user already, don't show the growl.
if ( payload.rating ) {
return;
}
Growls.success( {
sticky: true,
templateUrl: '/app/components/game/rating-growl/rating-growl.html',
controller: 'Game_RatingGrowlCtrl',
resolve: {
game: function()
{
return game;
}
}
} );
} );
};
} );
|
Send exception message with 500 error response
|
<?php
// load Tonic
require_once '../src/Tonic/Autoloader.php';
$config = array(
'load' => array('../*.php', '../src/Tyrell/*.php'), // load example resources
#'mount' => array('Tyrell' => '/nexus'), // mount in example resources at URL /nexus
#'cache' => new Tonic\MetadataCacheFile('/tmp/tonic.cache') // use the metadata cache
#'cache' => new Tonic\MetadataCacheAPC // use the metadata cache
);
$app = new Tonic\Application($config);
#echo $app;
$request = new Tonic\Request();
#echo $request;
try {
$resource = $app->getResource($request);
#echo $resource;
$response = $resource->exec();
} catch (Tonic\NotFoundException $e) {
$response = new Tonic\Response(404);
} catch (Tonic\UnauthorizedException $e) {
$response = new Tonic\Response(401);
$response->wwwAuthenticate = 'Basic realm="My Realm"';
} catch (Tonic\Exception $e) {
$response = new Tonic\Response(500, $e->getMessage());
}
#echo $response;
$response->output();
|
<?php
// load Tonic
require_once '../src/Tonic/Autoloader.php';
$config = array(
'load' => array('../*.php', '../src/Tyrell/*.php'), // load example resources
#'mount' => array('Tyrell' => '/nexus'), // mount in example resources at URL /nexus
#'cache' => new Tonic\MetadataCacheFile('/tmp/tonic.cache') // use the metadata cache
#'cache' => new Tonic\MetadataCacheAPC // use the metadata cache
);
$app = new Tonic\Application($config);
#echo $app;
$request = new Tonic\Request();
#echo $request;
try {
$resource = $app->getResource($request);
#echo $resource;
$response = $resource->exec();
} catch (Tonic\NotFoundException $e) {
$response = new Tonic\Response(404);
} catch (Tonic\UnauthorizedException $e) {
$response = new Tonic\Response(401);
$response->wwwAuthenticate = 'Basic realm="My Realm"';
} catch (Tonic\Exception $e) {
$response = new Tonic\Response(500);
}
#echo $response;
$response->output();
|
Add missing `>` to top comment
:smile:
|
/**
* amputee.js
*
* Copyright © 2015 | Johnie Hjelm <johnie@hjelm.im>
*/
// Get all amputee elements
const amputee = document.getElementsByTagName('amputee');
/**
* Ajax function
*
* @return {string}
* @throws Will throw an error if the file does not exist.
*/
const httpGet = url => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);
if (xhr.status === 200) {
return xhr.responseText;
} else {
throw `amputee: Could not fetch file: ${url}`;
}
};
/**
* Main amputee function
*
* @return {mixed}
*/
;(() => {
for ( var i = 0; i < amputee.length; ) {
var src = '';
if ( amputee[i].hasAttribute('src') ) {
// Append the data to src
src += httpGet(amputee[i].getAttribute('src'));
// Create a div for each amputee
var htmlNode = document.createElement('span');
// Put src inside of htmlNode
htmlNode.innerHTML = src;
// Replace htmlNode with amputee response
amputee[i].parentNode.replaceChild(htmlNode, amputee[i]);
} else {
throw `amputee: ${amputee[i]} has no src location.`;
}
}
})();
|
/**
* amputee.js
*
* Copyright © 2015 | Johnie Hjelm <johnie@hjelm.im
*/
// Get all amputee elements
const amputee = document.getElementsByTagName('amputee');
/**
* Ajax function
*
* @return {string}
* @throws Will throw an error if the file does not exist.
*/
const httpGet = url => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send(null);
if (xhr.status === 200) {
return xhr.responseText;
} else {
throw `amputee: Could not fetch file: ${url}`;
}
};
/**
* Main amputee function
*
* @return {mixed}
*/
;(() => {
for ( var i = 0; i < amputee.length; ) {
var src = '';
if ( amputee[i].hasAttribute('src') ) {
// Append the data to src
src += httpGet(amputee[i].getAttribute('src'));
// Create a div for each amputee
var htmlNode = document.createElement('span');
// Put src inside of htmlNode
htmlNode.innerHTML = src;
// Replace htmlNode with amputee response
amputee[i].parentNode.replaceChild(htmlNode, amputee[i]);
} else {
throw `amputee: ${amputee[i]} has no src location.`;
}
}
})();
|
Fix migration to modify multiple documents
|
Migrations.add({
version: 1,
name: "Extract items to a separate collection from the nested field",
up: function () {
Flights.find({items: {$exists: true}}).forEach(function (flight) {
flight.items.forEach(function (item) {
var itemId = Items.insert(_.extend(item, {createdAt: new Date(), flightId: flight._id}));
Flights.update({_id: flight._id}, {$addToSet: {itemIds: itemId}});
});
});
},
down: function () {
}
});
Migrations.add({
version: 2,
name: "Drop items field",
up: function () {
Flights.update({items: {$exists: true}}, {$unset: {items: ''}}, {multi: true});
},
down: function () {
}
});
Migrations.migrateTo('latest');
|
Migrations.add({
version: 1,
name: "Extract items to a separate collection from the nested field",
up: function () {
Flights.find({items: {$exists: true}}).forEach(function (flight) {
flight.items.forEach(function (item) {
var itemId = Items.insert(_.extend(item, {createdAt: new Date(), flightId: flight._id}));
Flights.update({_id: flight._id}, {$addToSet: {itemIds: itemId}});
});
});
},
down: function () {
}
});
Migrations.add({
version: 2,
name: "Drop items field",
up: function () {
Flights.update({items: {$exists: true}}, {$unset: {items: ''}});
},
down: function () {
}
});
Migrations.migrateTo('latest');
|
Fix of library declaration used in documentation generation
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
foam.LIB({
name: 'foam.java.Util',
methods:[
{
/** Splits strings when they are too long, used to split documentation in multiple lines */
name: 'limitSplit',
code: function(str, maxWords){
res = [];
var arr = str.split(' ', 150);
for( i = 0 ; i < arr.length ; i++){
line = arr[i] + ' ';
if( i % maxWords == 0 && i > 0 ){
line += '\n';
}
res.push(line);
}
return res;
}
}
]
});
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
foam.LIB({
name: 'foam.java.Util',
methods:[
{
/** Splits strings when they are too long, used to split documentation in multiple lines */
name: 'limitSplit',
code: function(o, str, maxWords){
var res = '';
var arr = str.split(' ', 150);
o.indent();
for( i = 0 ; i < arr.length ; i++){
res += arr[i] + ' ';
if( i % maxWords == 0 && i > 0 ){
res += '\n';
o.indent();
}
}
return res;
}
}
]
});
|
Make browserAction link to /messages
|
let username = ""
const init = () => {
console.log("Starting...");
chrome.alarms.create("checkmessages", {
periodInMinutes: 1
})
console.log("Alarm created!");
chrome.storage.sync.get(["username"], (v) => { username = v["username"] });
console.log("Username fetched!");
}
init()
chrome.alarms.onAlarm.addListener(a => {
console.log("Alarm recieved.");
if (a.name === "checkmessages") {
console.log("Check recieved.");
if (username !== "") {
console.log("Checking messages...");
fetch(`https://api.scratch.mit.edu/proxy/users/${username}/activity/count`).then(r => r.json()).then(({msg_count}) => {
if (msg_count > 0) {
chrome.browserAction.setBadgeText({text: msg_count + ""})
}else{
chrome.browserAction.setBadgeText({text: ""})
}
})
}
}
})
chrome.storage.onChanged.addListener((c, n) => {
if (n === "sync") {
username = c.username.newValue
}
})
chrome.browserAction.onClicked.addListener(() => {
chrome.tabs.create({
url: "https://scratch.mit.edu/messages"
})
})
|
let username = ""
const init = () => {
console.log("Starting...");
chrome.alarms.create("checkmessages", {
periodInMinutes: 1
})
console.log("Alarm created!");
chrome.storage.sync.get(["username"], (v) => { username = v["username"] });
console.log("Username fetched!");
}
init()
chrome.alarms.onAlarm.addListener(a => {
console.log("Alarm recieved.");
if (a.name === "checkmessages") {
console.log("Check recieved.");
if (username !== "") {
console.log("Checking messages...");
fetch(`https://api.scratch.mit.edu/proxy/users/${username}/activity/count`).then(r => r.json()).then(({msg_count}) => {
if (msg_count > 0) {
chrome.browserAction.setBadgeText({text: msg_count + ""})
}else{
chrome.browserAction.setBadgeText({text: ""})
}
})
}
}
})
chrome.storage.onChanged.addListener((c, n) => {
if (n === "sync") {
username = c.username.newValue
}
})
|
Update dsub version to 0.3.7
PiperOrigin-RevId: 292945859
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.7'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.7.dev0'
|
Load configuration from a custom location
|
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Mike van Riel <mike.vanriel@naenius.com>
* @copyright 2010-2018 Mike van Riel / Naenius (http://www.naenius.com)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link http://phpdoc.org
*/
namespace phpDocumentor\Application\Stage;
use phpDocumentor\Application\Configuration\CommandlineOptionsMiddleware;
use phpDocumentor\Application\Configuration\ConfigurationFactory;
use phpDocumentor\DomainModel\Uri;
final class Configure
{
/**
* @var ConfigurationFactory
*/
private $configFactory;
/**
* Configure constructor.
*/
public function __construct(ConfigurationFactory $configFactory)
{
$this->configFactory = $configFactory;
}
/**
* @return string[]
*/
public function __invoke(array $options): array
{
$this->configFactory->addMiddleware(
new CommandlineOptionsMiddleware($options)
);
if ($options['config'] ?? null) {
return $this->configFactory->fromUri(new Uri(realpath($options['config'])))->getArrayCopy();
}
return $this->configFactory->fromDefaultLocations()->getArrayCopy();
}
}
|
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Mike van Riel <mike.vanriel@naenius.com>
* @copyright 2010-2018 Mike van Riel / Naenius (http://www.naenius.com)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link http://phpdoc.org
*/
namespace phpDocumentor\Application\Stage;
use phpDocumentor\Application\Configuration\CommandlineOptionsMiddleware;
use phpDocumentor\Application\Configuration\ConfigurationFactory;
final class Configure
{
/**
* @var ConfigurationFactory
*/
private $configFactory;
/**
* Configure constructor.
*/
public function __construct(ConfigurationFactory $configFactory)
{
$this->configFactory = $configFactory;
}
/**
* @return string[]
*/
public function __invoke(array $options): array
{
$this->configFactory->addMiddleware(
new CommandlineOptionsMiddleware($options)
);
return $this->configFactory->fromDefaultLocations()->getArrayCopy();
}
}
|
Fix regex matching coverage output
The coverage library now returns the file extensions.
|
import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 5 38%'
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
stderr=os.path.join('lib', 'mod1.py').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
stderr='TOTAL ' + STATS)
|
import os.path
from nose2.tests._common import FunctionalTestCase
class TestCoverage(FunctionalTestCase):
def test_run(self):
proc = self.runIn(
'scenario/test_with_module',
'-v',
'--with-coverage',
'--coverage=lib/'
)
STATS = ' 8 5 38%'
stdout, stderr = proc.communicate()
self.assertTestRunOutputMatches(
proc,
stderr=os.path.join('lib', 'mod1').replace('\\', r'\\') + STATS)
self.assertTestRunOutputMatches(
proc,
stderr='TOTAL ' + STATS)
|
Update the PyPI version to 7.0.10.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.10',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.9',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.