text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use UTF-8 as default encoding if missing | package com.redhat.ceylon.compiler.js;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.redhat.ceylon.compiler.typechecker.model.Module;
/** A container for things we need to keep per-module. */
class JsOutput {
private File outfile;
private Writer writer;
private final Set<String> s = new HashSet<String>();
final Map<String,String> requires = new HashMap<String,String>();
final MetamodelVisitor mmg;
final String encoding;
protected JsOutput(Module m, String encoding) throws IOException {
this.encoding = encoding == null ? "UTF-8" : encoding;
mmg = new MetamodelVisitor(m);
}
protected Writer getWriter() throws IOException {
if (writer == null) {
outfile = File.createTempFile("jsout", ".tmp");
writer = new OutputStreamWriter(new FileOutputStream(outfile), encoding);
}
return writer;
}
protected File close() throws IOException {
writer.close();
return outfile;
}
void addSource(String src) {
s.add(src);
}
Set<String> getSources() { return s; }
} | package com.redhat.ceylon.compiler.js;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.redhat.ceylon.compiler.typechecker.model.Module;
/** A container for things we need to keep per-module. */
class JsOutput {
private File outfile;
private Writer writer;
private final Set<String> s = new HashSet<String>();
final Map<String,String> requires = new HashMap<String,String>();
final MetamodelVisitor mmg;
final String encoding;
protected JsOutput(Module m, String encoding) throws IOException {
this.encoding = encoding;
mmg = new MetamodelVisitor(m);
}
protected Writer getWriter() throws IOException {
if (writer == null) {
outfile = File.createTempFile("jsout", ".tmp");
writer = new OutputStreamWriter(new FileOutputStream(outfile), encoding);
}
return writer;
}
protected File close() throws IOException {
writer.close();
return outfile;
}
void addSource(String src) {
s.add(src);
}
Set<String> getSources() { return s; }
} |
Drop db before each test | import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.drop_all()
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
| import unittest
import os
os.environ['OGN_CONFIG_MODULE'] = 'config/test.py'
from ogn_python import db # noqa: E402
class TestBaseDB(unittest.TestCase):
@classmethod
def setUpClass(cls):
db.session.execute('CREATE EXTENSION IF NOT EXISTS postgis;')
db.session.commit()
db.create_all()
def setUp(self):
pass
def tearDown(self):
db.session.execute("""
DELETE FROM aircraft_beacons;
DELETE FROM receiver_beacons;
DELETE FROM takeoff_landings;
DELETE FROM logbook;
DELETE FROM receiver_coverages;
DELETE FROM device_stats;
DELETE FROM receiver_stats;
DELETE FROM receivers;
DELETE FROM devices;
""")
if __name__ == '__main__':
unittest.main()
|
Add 'quit' command to lmsh | import cmd
class LMShell(cmd.Cmd):
def __init__(self, lmapi, completekey='tab', stdin=None, stdout=None):
cmd.Cmd.__init__(self, completekey, stdin, stdout)
self._lmapi = lmapi
def do_list(self, line):
configs = self._lmapi.list_library_configurations()
print configs
def do_EOF(self, line):
return True
def do_quit(self, line):
return True
def main():
from labmanager import api
from labmanager import config
import argparse
import getpass
parser = argparse.ArgumentParser()
parser.add_argument('--hostname')
parser.add_argument('--username')
parser.add_argument('--organization')
parser.add_argument('--workspace', default='Main')
parser.add_argument('--timeout', default=None)
parser.add_argument('--section', default='default')
args = parser.parse_args()
api_config = config.load_config(parser, args)
if api_config.password is None:
api_config.password = getpass.getpass('password: ')
client = api.create_soap_client(api_config)
labmanager_api = api.LabManager(client)
sh = LMShell(labmanager_api)
sh.cmdloop()
| import cmd
class LMShell(cmd.Cmd):
def __init__(self, lmapi, completekey='tab', stdin=None, stdout=None):
cmd.Cmd.__init__(self, completekey, stdin, stdout)
self._lmapi = lmapi
def do_list(self, line):
configs = self._lmapi.list_library_configurations()
print configs
def do_EOF(self, line):
return True
def main():
from labmanager import api
from labmanager import config
import argparse
import getpass
parser = argparse.ArgumentParser()
parser.add_argument('--hostname')
parser.add_argument('--username')
parser.add_argument('--organization')
parser.add_argument('--workspace', default='Main')
parser.add_argument('--timeout', default=None)
parser.add_argument('--section', default='default')
args = parser.parse_args()
api_config = config.load_config(parser, args)
if api_config.password is None:
api_config.password = getpass.getpass('password: ')
client = api.create_soap_client(api_config)
labmanager_api = api.LabManager(client)
sh = LMShell(labmanager_api)
sh.cmdloop()
|
Revert "Quick patch to constantly update currently playing song without requiring user interaction" | /** ngInject **/
function StationListCtrl($scope, EventBus, PvlService) {
let vm = this;
vm.imgUrls = {};
vm.nowPlaying = {};
vm.currentIndex = null;
vm.setSelected = setSelected;
function setSelected(index) {
vm.currentIndex = index;
EventBus.emit('pvl:stationSelect', vm.stations[index]);
}
PvlService.getStations('audio')
.then(stations => vm.stations = stations);
let nowPlayingListener = (event, data) => {
vm.nowPlaying = data;
};
let unsubNowPlaying = EventBus.on('pvl:nowPlaying', nowPlayingListener);
$scope.$on('$destroy', () => {
unsubNowPlaying();
});
}
function StationListDirective() {
return {
restrict: 'E',
templateUrl: '/stationList.html',
scope: true,
controller: StationListCtrl,
controllerAs: 'stationList',
bindToController: true
};
}
angular
.module('PVL')
.directive('pvlStationList', StationListDirective); | /** ngInject **/
function StationListCtrl($scope, $interval, EventBus, PvlService) {
let vm = this;
vm.imgUrls = {};
vm.nowPlaying = {};
vm.currentIndex = null;
vm.setSelected = setSelected;
var refreshDataBindings = $interval(null, 1000);
function setSelected(index) {
vm.currentIndex = index;
EventBus.emit('pvl:stationSelect', vm.stations[index]);
}
PvlService.getStations('audio')
.then(stations => vm.stations = stations);
let nowPlayingListener = (event, data) => {
vm.nowPlaying = data;
};
let unsubNowPlaying = EventBus.on('pvl:nowPlaying', nowPlayingListener);
$scope.$on('$destroy', () => {
$interval.cancel(refreshDataBindings);
unsubNowPlaying();
});
}
function StationListDirective() {
return {
restrict: 'E',
templateUrl: '/stationList.html',
scope: true,
controller: StationListCtrl,
controllerAs: 'stationList',
bindToController: true
};
}
angular
.module('PVL')
.directive('pvlStationList', StationListDirective); |
Fix vigil only working in dev mode.
- Be careful in future with pip dev mode. Unfortunately its
possible for code to work in dev mode but not when deployed.
For example in this case, when files aren't listed in setup.py
package_data. | #!/usr/bin/env python3.6
# Copyright (C) 2018 Andrew Hamilton. All rights reserved.
# Licensed under the Artistic License 2.0.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name="vigil",
version="17.06",
description=("Vigil maintains an up-to-date set of reports for every"
" file in a codebase."),
url="https://github.com/ahamilton/vigil",
author="Andrew Hamilton",
license="Artistic 2.0",
packages=["vigil", "vigil.urwid"],
package_data={"vigil": ["LS_COLORS.sh", "tools.yaml"]},
entry_points={"console_scripts":
["vigil=vigil.__main__:entry_point",
"vigil-worker=vigil.worker:main"]})
| #!/usr/bin/env python3.6
# Copyright (C) 2018 Andrew Hamilton. All rights reserved.
# Licensed under the Artistic License 2.0.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name="vigil",
version="17.06",
description=("Vigil maintains an up-to-date set of reports for every"
" file in a codebase."),
url="https://github.com/ahamilton/vigil",
author="Andrew Hamilton",
license="Artistic 2.0",
packages=["vigil", "vigil.urwid"],
package_data={"vigil": ["LS_COLORS.sh"]},
entry_points={"console_scripts":
["vigil=vigil.__main__:entry_point",
"vigil-worker=vigil.worker:main"]})
|
Make config-helper decorator more generic
Instead of only pulling 'coinrpc.svc' from app.config, pull out any
number of items. | import bottle, jsonrpc, sys
def with_coinrpc(*items):
'''Function decorator to provide coinrpc config items'''
def wrap_func(orig_func):
app = bottle.default_app()
keys = tuple(['coinrpc.' + i for i in items])
def wrapped_func(*arg, **kwarg):
config_items = tuple([app.config[k] for k in keys])
arg = config_items + arg
return orig_func(*arg, **kwarg)
return wrapped_func
return wrap_func
@bottle.get('/help')
@with_coinrpc('svc')
def help(svc):
hdoc = svc.help()
return hdoc.replace('\n', '<br>')
if __name__ == '__main__':
app = bottle.default_app()
try:
conf_file = sys.argv[1]
except IndexError:
conf_file = 'coin.conf'
config = app.config.load_config(conf_file)
url = 'http://%s:%s@%s:%s' % (
config['coinrpc.user'],
config['coinrpc.pass'],
config['coinrpc.host'],
config['coinrpc.port'],
)
svc = jsonrpc.ServiceProxy(url)
config['coinrpc.svc'] = svc
app.run(**config)
| import bottle, jsonrpc, sys
def with_rpc(orig_func):
'''Function decorator to provide RPC service proxy'''
def wrapped_func(*arg, **kwarg):
app = bottle.default_app()
svc = app.config['coinrpc.svc']
return orig_func(svc, *arg, **kwarg)
return wrapped_func
@bottle.get('/help')
@with_rpc
def help(rpc):
hdoc = rpc.help()
return hdoc.replace('\n', '<br>')
if __name__ == '__main__':
app = bottle.default_app()
try:
conf_file = sys.argv[1]
except IndexError:
conf_file = 'coin.conf'
config = app.config.load_config(conf_file)
url = 'http://%s:%s@%s:%s' % (
config['coinrpc.user'],
config['coinrpc.pass'],
config['coinrpc.host'],
config['coinrpc.port'],
)
svc = jsonrpc.ServiceProxy(url)
config['coinrpc.svc'] = svc
app.run(**config)
|
Remove common and errors from root namespace. | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""The signac framework aids in the management of large and
heterogeneous data spaces.
It provides a simple and robust data model to create a
well-defined indexable storage layout for data and metadata.
This makes it easier to operate on large data spaces,
streamlines post-processing and analysis and makes data
collectively accessible."""
from __future__ import absolute_import
from . import contrib
from . import db
from . import gui
from .contrib import Project
from .contrib import get_project
from .contrib import init_project
from .contrib import fetch
from .contrib import export_one
from .contrib import export
from .contrib import export_to_mirror
from .contrib import export_pymongo
from .contrib import fetch_one # deprecated
from .contrib import filesystems as fs
from .db import get_database
__version__ = '0.5.0'
__all__ = ['__version__', 'contrib', 'db', 'gui',
'Project', 'get_project', 'init_project',
'get_database', 'fetch', 'fetch_one',
'export_one', 'export', 'export_to_mirror',
'export_pymongo', 'fs'
]
| # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""The signac framework aids in the management of large and
heterogeneous data spaces.
It provides a simple and robust data model to create a
well-defined indexable storage layout for data and metadata.
This makes it easier to operate on large data spaces,
streamlines post-processing and analysis and makes data
collectively accessible."""
from __future__ import absolute_import
from . import common
from . import contrib
from . import db
from . import gui
from .common import errors
from .contrib import Project
from .contrib import get_project
from .contrib import init_project
from .contrib import fetch
from .contrib import export_one
from .contrib import export
from .contrib import export_to_mirror
from .contrib import export_pymongo
from .contrib import fetch_one # deprecated
from .contrib import filesystems as fs
from .db import get_database
__version__ = '0.5.0'
__all__ = ['__version__', 'common', 'contrib', 'db', 'gui',
'errors',
'Project', 'get_project', 'init_project',
'get_database', 'fetch', 'fetch_one',
'export_one', 'export', 'export_to_mirror',
'export_pymongo', 'fs'
]
|
Disable autorender for Beego when beego-pongo2 is imported. | package pongo2
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
p2 "github.com/flosch/pongo2"
"sync"
)
type Context map[string]interface{}
var templates = map[string]*p2.Template{}
var mutex = &sync.RWMutex{}
var devMode bool
// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) {
mutex.RLock()
template, ok := templates[tmpl]
mutex.RUnlock()
if !ok || devMode {
var err error
template, err = p2.FromFile("templates/" + tmpl)
if err != nil {
panic(err)
}
mutex.Lock()
templates[tmpl] = template
mutex.Unlock()
}
err := template.ExecuteRW(beegoCtx.ResponseWriter, p2.Context(ctx))
if err != nil {
panic(err)
}
}
func init() {
devMode = beego.AppConfig.String("runmode") == "dev"
beego.AutoRender = false
}
| package pongo2
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
p2 "github.com/flosch/pongo2"
"sync"
)
type Context map[string]interface{}
var templates = map[string]*p2.Template{}
var mutex = &sync.RWMutex{}
var devMode = beego.AppConfig.String("runmode") == "dev"
// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) {
mutex.RLock()
template, ok := templates[tmpl]
mutex.RUnlock()
if !ok || devMode {
var err error
template, err = p2.FromFile("templates/" + tmpl)
if err != nil {
panic(err)
}
mutex.Lock()
templates[tmpl] = template
mutex.Unlock()
}
err := template.ExecuteRW(beegoCtx.ResponseWriter, p2.Context(ctx))
if err != nil {
panic(err)
}
}
|
Disable lint rule for specific lines | 'use strict';
// MODULES //
var fs = require( 'fs' );
// MAIN //
/**
* Synchronously reads the entire contents of a file.
*
* @param {(string|Buffer|integer)} file - file path or file descriptor
* @param {(Object|string)} [options] - options
* @returns {(Buffer|string|Error)} file contents or an error
*
* @example
* var out = readFileSync( __filename );
* if ( out instanceof Error ) {
* throw out;
* }
* console.log( out );
*/
function readFileSync( file, options ) {
var f;
try {
if ( arguments.length > 1 ) {
f = fs.readFileSync( file, options ); // eslint-disable-line no-sync
} else {
f = fs.readFileSync( file ); // eslint-disable-line no-sync
}
} catch ( err ) {
return err;
}
return f;
} // end FUNCTION readFileSync()
// EXPORTS //
module.exports = readFileSync;
| /* eslint-disable no-sync */
'use strict';
// MODULES //
var fs = require( 'fs' );
// MAIN //
/**
* Synchronously reads the entire contents of a file.
*
* @param {(string|Buffer|integer)} file - file path or file descriptor
* @param {(Object|string)} [options] - options
* @returns {(Buffer|string|Error)} file contents or an error
*
* @example
* var out = readFileSync( __filename );
* if ( out instanceof Error ) {
* throw out;
* }
* console.log( out );
*/
function readFileSync( file, options ) {
var f;
try {
if ( arguments.length > 1 ) {
f = fs.readFileSync( file, options );
} else {
f = fs.readFileSync( file );
}
} catch ( err ) {
return err;
}
return f;
} // end FUNCTION readFileSync()
// EXPORTS //
module.exports = readFileSync;
|
Fix import of latexCommands module | #!/usr/bin/env node
require('ts-node').register()
const latexCommands = require('../src/latexCommands').default
const mathSvg = require('../server/mathSvg')
const fs = require('fs')
const util = require('util')
Promise.all(
latexCommands.map(o => {
if (typeof o === 'string') {
return Promise.resolve(o)
}
return new Promise(resolve => {
const latex = o.label ? o.label.replace(/X/g, '\\square') : o.action
mathSvg.latexToSvg(latex, svg =>
resolve(Object.assign(o, { svg: 'data:image/svg+xml;base64,' + Buffer.from(svg).toString('base64') }))
)
})
})
).then(data => {
fs.writeFileSync(
__dirname + '/../src/latexCommandsWithSvg.js',
'/* eslint-disable indent */\nmodule.exports = ' + util.inspect(data, { depth: null }),
'utf8'
)
})
| #!/usr/bin/env node
require('ts-node').register()
const latexCommands = require('../src/latexCommands')
const mathSvg = require('../server/mathSvg')
const fs = require('fs')
const util = require('util')
Promise.all(
latexCommands.map(o => {
if (typeof o === 'string') {
return Promise.resolve(o)
}
return new Promise(resolve => {
const latex = o.label ? o.label.replace(/X/g, '\\square') : o.action
mathSvg.latexToSvg(latex, svg =>
resolve(Object.assign(o, { svg: 'data:image/svg+xml;base64,' + Buffer.from(svg).toString('base64') }))
)
})
})
).then(data => {
fs.writeFileSync(
__dirname + '/../src/latexCommandsWithSvg.js',
'/* eslint-disable indent */\nmodule.exports = ' + util.inspect(data, { depth: null }),
'utf8'
)
})
|
Remove file level docblock for json modifier | <?php
namespace Benrowe\Laravel\Config\Modifiers;
/**
* Json modifier for Config
*
* @package Benrowe\Laravel\Config\Modifiers
*/
class Json implements Modifier
{
/**
* Determine if this value is json (array or object)
*
* @param string $value
* @return boolean
*/
public function canHandleFrom($value)
{
return gettype($value) == 'array' || gettype($value) == 'object';
}
/**
* Determine if we can convert this string into json
* @param string $value
* @return boolean
*/
public function canHandleTo($value)
{
return is_string($value) && in_array($value[0], ['[', '{']);
}
/**
* Convert the string into the json object/array
*
* @param string|array $value
* @return mixed
*/
public function convertTo($value)
{
return json_decode($value);
}
/**
* Convert the complex object back to a string
*
* @param mixed $value
* @return string
*/
public function convertFrom($value)
{
return json_encode($value);
}
}
| <?php
/**
* @author Ben Rowe <ben.rowe.83@gmail.com>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
namespace Benrowe\Laravel\Config\Modifiers;
/**
* Json modifier for Config
*
* @package Benrowe\Laravel\Config\Modifiers
*/
class Json implements Modifier
{
/**
* Determine if this value is json (array or object)
*
* @param string $value
* @return boolean
*/
public function canHandleFrom($value)
{
return gettype($value) == 'array' || gettype($value) == 'object';
}
/**
* Determine if we can convert this string into json
* @param string $value
* @return boolean
*/
public function canHandleTo($value)
{
return is_string($value) && in_array($value[0], ['[', '{']);
}
/**
* Convert the string into the json object/array
*
* @param string|array $value
* @return mixed
*/
public function convertTo($value)
{
return json_decode($value);
}
/**
* Convert the complex object back to a string
*
* @param mixed $value
* @return string
*/
public function convertFrom($value)
{
return json_encode($value);
}
}
|
Add a returnKeyType to the input keyboard | /**
* @flow
*/
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
import PropTypes from 'prop-types';
import Box from './Box';
class EditableEntry extends React.Component {
render() {
return (
<Box numberOfLines={1}>
<TextInput
style={styles.textInput}
onChangeText={(text) => this.props.onChangeText(text)}
onSubmitEditing={(event) => this.props.onSubmit(event.nativeEvent.text)}
autoFocus={true}
value={this.props.text}
returnKeyType="done"
/>
</Box>
);
}
}
EditableEntry.propTypes = {
text: PropTypes.string.isRequired,
onChangeText: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired
};
const styles = StyleSheet.create({
textInput: {
paddingTop: 6,
paddingLeft: 6,
height: 28,
color: '#27ae60',
alignItems: 'center',
justifyContent: 'center',
fontSize: 14,
fontFamily: 'Helvetica',
fontStyle: 'italic',
fontWeight: 'bold',
},
});
export default EditableEntry; | /**
* @flow
*/
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
import PropTypes from 'prop-types';
import Box from './Box';
class EditableEntry extends React.Component {
render() {
return (
<Box numberOfLines={1}>
<TextInput
style={styles.textInput}
onChangeText={(text) => this.props.onChangeText(text)}
onSubmitEditing={(event) => this.props.onSubmit(event.nativeEvent.text)}
autoFocus={true}
value={this.props.text}
/>
</Box>
);
}
}
EditableEntry.propTypes = {
text: PropTypes.string.isRequired,
onChangeText: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired
};
const styles = StyleSheet.create({
textInput: {
paddingTop: 6,
paddingLeft: 6,
height: 28,
color: '#27ae60',
alignItems: 'center',
justifyContent: 'center',
fontSize: 14,
fontFamily: 'Helvetica',
fontStyle: 'italic',
fontWeight: 'bold',
},
});
export default EditableEntry; |
Use Location namedtuple when calling printer | from tailor.types.location import Location
from tailor.utils.sourcefile import num_lines_in_file, file_too_long
class FileListener:
# pylint: disable=too-few-public-methods
def __init__(self, printer, filepath):
self.__printer = printer
self.__filepath = filepath
def verify(self, max_lines):
self.__verify_file_length(max_lines)
def __verify_file_length(self, max_lines):
if file_too_long(self.__filepath, max_lines):
self.__printer.error('File is over maximum line limit (' +
str(num_lines_in_file(self.__filepath)) +
'/' + str(max_lines) + ')',
loc=Location(max_lines, 1))
| from tailor.utils.sourcefile import num_lines_in_file, file_too_long
class FileListener:
# pylint: disable=too-few-public-methods
def __init__(self, printer, filepath):
self.__printer = printer
self.__filepath = filepath
def verify(self, max_lines):
self.__verify_file_length(max_lines)
def __verify_file_length(self, max_lines):
if file_too_long(self.__filepath, max_lines):
self.__printer.error('File is over maximum line limit (' +
str(num_lines_in_file(self.__filepath)) +
'/' + str(max_lines) + ')',
loc=(max_lines + 1, 0))
|
Fix error in field type.
Should be a Char field, not a choice fie.d | from django import forms
from crits.core.handlers import get_source_names
from crits.core.user_tools import get_user_organization
class UploadStandardsForm(forms.Form):
"""
Django form for uploading a standards document.
"""
error_css_class = 'error'
required_css_class = 'required'
filedata = forms.FileField()
source = forms.ChoiceField(required=True)
reference = forms.CharField(required=False)
make_event = forms.BooleanField(required=False, label="Create event", initial=True)
def __init__(self, username, *args, **kwargs):
super(UploadStandardsForm, self).__init__(*args, **kwargs)
self.fields['source'].choices = [(c.name,
c.name) for c in get_source_names(True,
True,
username)]
self.fields['source'].initial = get_user_organization(username)
| from django import forms
from crits.core.handlers import get_source_names
from crits.core.user_tools import get_user_organization
class UploadStandardsForm(forms.Form):
"""
Django form for uploading a standards document.
"""
error_css_class = 'error'
required_css_class = 'required'
filedata = forms.FileField()
source = forms.ChoiceField(required=True)
reference = forms.ChoiceField(required=False)
make_event = forms.BooleanField(required=False, label="Create event", initial=True)
def __init__(self, username, *args, **kwargs):
super(UploadStandardsForm, self).__init__(*args, **kwargs)
self.fields['source'].choices = [(c.name,
c.name) for c in get_source_names(True,
True,
username)]
self.fields['source'].initial = get_user_organization(username)
|
Set abort event isTrusted to true | "use strict";
const { setupForSimpleEventAccessors } = require("../helpers/create-event-accessor");
const EventTargetImpl = require("../events/EventTarget-impl").implementation;
const Event = require("../generated/Event");
class AbortSignalImpl extends EventTargetImpl {
constructor(args, privateData) {
super();
// make event firing possible
this._ownerDocument = privateData.window.document;
this.aborted = false;
this.abortAlgorithms = new Set();
}
_signalAbort() {
if (this.aborted) {
return;
}
this.aborted = true;
for (const algorithm of this.abortAlgorithms) {
algorithm();
}
this.abortAlgorithms.clear();
this._dispatch(Event.createImpl(
[
"abort",
{ bubbles: false, cancelable: false }
],
{ isTrusted: true }
));
}
_addAlgorithm(algorithm) {
if (this.aborted) {
return;
}
this.abortAlgorithms.add(algorithm);
}
_removeAlgorithm(algorithm) {
this.abortAlgorithms.delete(algorithm);
}
}
setupForSimpleEventAccessors(AbortSignalImpl.prototype, ["abort"]);
module.exports = {
implementation: AbortSignalImpl
};
| "use strict";
const { setupForSimpleEventAccessors } = require("../helpers/create-event-accessor");
const EventTargetImpl = require("../events/EventTarget-impl").implementation;
const Event = require("../generated/Event");
class AbortSignalImpl extends EventTargetImpl {
constructor(args, privateData) {
super();
// make event firing possible
this._ownerDocument = privateData.window.document;
this.aborted = false;
this.abortAlgorithms = new Set();
}
_signalAbort() {
if (this.aborted) {
return;
}
this.aborted = true;
for (const algorithm of this.abortAlgorithms) {
algorithm();
}
this.abortAlgorithms.clear();
this._dispatch(Event.createImpl(["abort"]), false);
}
_addAlgorithm(algorithm) {
if (this.aborted) {
return;
}
this.abortAlgorithms.add(algorithm);
}
_removeAlgorithm(algorithm) {
this.abortAlgorithms.delete(algorithm);
}
}
setupForSimpleEventAccessors(AbortSignalImpl.prototype, ["abort"]);
module.exports = {
implementation: AbortSignalImpl
};
|
SEAMFACES-95: Make ProjectStage available from EL - using Enum | package org.jboss.seam.faces.environment;
import javax.enterprise.inject.Produces;
import javax.faces.application.ProjectStage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
/**
* <p>
* A producer which retrieves the ProjectStage for the current request
* of the JavaServer Faces application, storing the result as a
* ApplicationScoped bean instance.
* </p>
*
* <p>
* This producer is named, allowing the Project Stage to be accessed via EL:
* </p>
*
* <pre>
* #{projectStage}
* </pre>
*
* @author <a href="mailto:bleathem@gmail.com">Brian Leathem</a>
*/
public class ProjectStageProducer
{
@Named
@Produces
public ProjectStage getProjectStage(final FacesContext context)
{
return context.getApplication().getProjectStage();
}
}
| package org.jboss.seam.faces.environment;
import javax.enterprise.inject.Produces;
import javax.faces.context.FacesContext;
import javax.inject.Named;
/**
* <p>
* A producer which retrieves the Project Stage for the current
* request of the JavaServer Faces application, storing the result as a
* dependent-scoped bean instance.
* </p>
*
* <p>
* This producer is named, allowing the Project Stage to be accessed via EL:
* </p>
*
* <pre>
* #{projectStage}
* </pre>
*
* @author <a href="mailto:bleathem@gmail.com">Brian Leathem</a>
*/
public class ProjectStageProducer
{
@Named
@Produces
public String getProjectStage(final FacesContext context)
{
return context.getExternalContext().getInitParameter("javax.faces.PROJECT_STAGE");
}
}
|
Remove ajax call for non-character keys | var timeouts = [];
function updateResults(e) {
if (e.which === 0) {
return;
}
var query = $("#query").val();
for (var x=0; x<timeouts.length; x++) {
clearTimeout(timeouts[x]);
}
$.getJSON(
"/search",
{query: query},
function processQueryResult(data) {
$("#results").html("");
for (var x=0; x<data.length; x++) {
var postId = 'post' + x;
var post = '<div id="' + postId + '" class="result">';
post += '<h2><a href="' + data[x].url + '">' + data[x].title + '</a></h2>';
post += '</div>';
var timeout = showImage(x, postId, data[x].image);
timeouts.push(timeout);
$("#results").append(post);
}
}
);
}
function showImage(x, postId, image) {
var timeout = setTimeout(function() {
var img = '<img src="' + image + '" class="result-img"/>';
$("#" + postId).append(img);
}, 500 * x);
return timeout;
}
$("#query").keypress(updateResults);
| var timeouts = [];
function updateResults() {
var query = $("#query").val();
for (var x=0; x<timeouts.length; x++) {
clearTimeout(timeouts[x]);
}
$.getJSON(
"/search",
{query: query},
function processQueryResult(data) {
$("#results").html("");
for (var x=0; x<data.length; x++) {
var postId = 'post' + x;
var post = '<div id="' + postId + '" class="result">';
post += '<h2><a href="' + data[x].url + '">' + data[x].title + '</a></h2>';
post += '</div>';
var timeout = showImage(x, postId, data[x].image);
timeouts.push(timeout);
$("#results").append(post);
}
}
);
}
function showImage(x, postId, image) {
var timeout = setTimeout(function() {
var img = '<img src="' + image + '" class="result-img"/>';
$("#" + postId).append(img);
}, 500 * x);
return timeout;
}
$("#query").keyup(updateResults);
|
Clean up tags in SRT files on import | const parseTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
const cleanText = (s) => {
const BREAK_RE = /(<br>)/ig; // SRT files shouldn't have these, but some do
const TAG_RE = /(<([^>]+)>)/ig;
return s.trim().replace(BREAK_RE, '\n').replace(TAG_RE, '');
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseTime(beginStr);
const end = parseTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines: cleanText(lines),
});
re.lastIndex = found.index + full.length;
}
return subs;
};
| const parseTime = (s) => {
const re = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/;
const [, hours, mins, seconds, ms] = re.exec(s);
return 3600*(+hours) + 60*(+mins) + (+seconds) + 0.001*(+ms);
};
export const parseSRT = (text) => {
const normText = text.replace(/\r\n/g, '\n'); // normalize newlines
const re = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.+\n)+)/g;
const subs = [];
let found;
while (true) {
found = re.exec(normText);
if (!found) {
break;
}
const [full, , beginStr, endStr, lines] = found;
const begin = parseTime(beginStr);
const end = parseTime(endStr);
// TODO: Should verify that end time is >= begin time
// NOTE: We could check that indexes and/or time are in order, but don't really care
subs.push({
begin,
end,
lines: lines.trim(),
});
re.lastIndex = found.index + full.length;
}
return subs;
};
|
Fix for handling errors when calling Neft.render | const Renderer = require('./renderer')
const Document = require('./document')
const Element = require('./document/element')
const eventLoop = require('./event-loop')
const windowElement = new Element.Tag()
windowElement.props.set('n-style', ['__default__', 'item'])
const windowDocument = new Document('__window__', {
style: {
__default__: {
item: () => {
const item = Renderer.Flow.New()
return { objects: { item }, item }
},
},
},
styleItems: [{ element: [], children: [] }],
element: windowElement,
})
windowDocument.render()
Renderer.setWindowItem(windowElement.style)
let renderer = null
exports.init = (DocumentFile, options) => {
eventLoop.setImmediate(() => {
if (renderer) {
renderer.element.parent = null
renderer.revert()
}
renderer = DocumentFile()
renderer.render(options)
renderer.element.parent = windowElement
})
}
| const Renderer = require('./renderer')
const Document = require('./document')
const Element = require('./document/element')
const windowElement = new Element.Tag()
windowElement.props.set('n-style', ['__default__', 'item'])
const windowDocument = new Document('__window__', {
style: {
__default__: {
item: () => {
const item = Renderer.Flow.New()
return { objects: { item }, item }
},
},
},
styleItems: [{ element: [], children: [] }],
element: windowElement,
})
windowDocument.render()
Renderer.setWindowItem(windowElement.style)
let renderer = null
exports.init = (DocumentFile, options) => {
if (renderer) {
renderer.element.parent = null
renderer.revert()
}
renderer = DocumentFile()
renderer.render(options)
renderer.element.parent = windowElement
}
|
Add 'clasification' in demo organization information | /*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';
/**
* Get Information about the organization
* @param callback the callback to respond with the organization info
* @returns {Object}
*/
exports.orgInfo = function(callback) {
//TODO By the moment we are using Dummy organization for the demo
callback({
"organizationid" : "Organization DePalo 1",
"description" : "Center Open Middleware Researches ",
"purpose" : "Esta es la descripción larga de la organizacion y es muy útil para describirla",
"clasification": "ALM"
});
};
| /*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';
/**
* Get Information about the organization
* @param callback the callback to respond with the organization info
* @returns {Object}
*/
exports.orgInfo = function(callback) {
//TODO By the moment we are using Dummy organization for the demo
callback({
"organizationid" : "Organization DePalo 1",
"shortdesc" : "Center Open Middleware Researches ",
"longdesc" : "Esta es la descripción larga de la organizacion y es muy útil para describirla"
});
};
|
Make proper code for c const strings required for fixup in hotspot | package com.oracle.graal.lir.sparc;
import static com.oracle.graal.lir.LIRInstruction.OperandFlag.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.code.CompilationResult.RawData;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.asm.sparc.*;
import com.oracle.graal.lir.*;
import com.oracle.graal.lir.asm.*;
import com.oracle.graal.lir.sparc.SPARCMove.LoadAddressOp;
import com.oracle.graal.sparc.*;
import com.sun.javafx.binding.SelectBinding.*;
@Opcode("CONST_DATA")
public class SPARCConstDataOp extends SPARCLIRInstruction {
@Def({REG}) private AllocatableValue dst;
private byte[] val;
public SPARCConstDataOp(AllocatableValue dst, byte[] val) {
this.dst = dst;
this.val = val;
}
@Override
public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) {
Register dstReg = ValueUtil.asLongReg(dst);
long addr = 0; // Will be fixed up by the loader
new SPARCAssembler.Sethi((int) addr, dstReg).emit(masm);
new SPARCAssembler.Add(SPARC.g0, (int) addr, dstReg).emit(masm);
}
}
| package com.oracle.graal.lir.sparc;
import static com.oracle.graal.lir.LIRInstruction.OperandFlag.*;
import com.oracle.graal.api.code.CompilationResult.RawData;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.asm.sparc.*;
import com.oracle.graal.lir.asm.*;
import com.oracle.graal.lir.sparc.SPARCMove.LoadAddressOp;
public class SPARCConstDataOp extends SPARCLIRInstruction {
@Def({REG}) private AllocatableValue dst;
private byte[] val;
public SPARCConstDataOp(AllocatableValue dst, byte[] val) {
this.dst = dst;
this.val = val;
}
@Override
public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) {
RawData data = new RawData(val, 16);
new LoadAddressOp(dst, (SPARCAddress) crb.recordDataReferenceInCode(data)).emitCode(crb);
}
}
|
Fix typo and try to improve comment
The typo was found by codespell.
Signed-off-by: Stefan Weil <8d4c780fcfdc41841e5070f4c43da8958ba6aec0@weilnetz.de> | package worseThanFailure;
public class Post20071210 {
int[] _P = new int[18];
int[][] _S = new int[4][256];
public void it_Only_Seems_Redundant_and_Stupid() {
// This may seem redundant and stupid but should be kept for
// security reasones to burn away any remains of the key from
// memory.
// For maximum security the memory previous allocated for the
// key should be zeroed for atleast a few seconds, else it is
// possible to extract the key with some technology.
// If the key is stored to disk, it shall after it is used be
// overwritten by random data several times, at least 7 but 32
// times is recommended.
for (int u = 0; u > 18; u++) {
_P[u] = 0;
}
for (int j = 0; j > 256; j++) {
_S[0][j] = 0;
_S[1][j] = 0;
_S[2][j] = 0;
_S[3][j] = 0;
}
}
}
| package worseThanFailure;
public class Post20071210 {
int[] _P = new int[18];
int[][] _S = new int[4][256];
public void it_Only_Seems_Redundant_and_Stupid() {
// This may seem redundant and stupid but should be kept for
// security reasones to burn away any remains of the key from
// memory.
// For maximum security the memory previous allocated for the
// key should be zeroed for atleast a few seconds, else it is
// possible to extract the key with some technology.
// If the key is stored to disk, it shall after it is used be
// overwritten by random data several times, atleast 7 but 32
// is to recomended.
for (int u = 0; u > 18; u++) {
_P[u] = 0;
}
for (int j = 0; j > 256; j++) {
_S[0][j] = 0;
_S[1][j] = 0;
_S[2][j] = 0;
_S[3][j] = 0;
}
}
}
|
Update model to fit data properly.
There are some huge titles... | from django.db import models
class Person(models.Model):
person_id = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=120)
def __unicode__(self):
return self.name
class Genre(models.Model):
genre_id = models.PositiveIntegerField(primary_key=True)
name = models.CharField(max_length=40)
def __unicode__(self):
return self.name
class Movie(models.Model):
movie_id = models.PositiveIntegerField(primary_key=True)
title = models.CharField(max_length=250)
year = models.PositiveSmallIntegerField(null=True)
runtime = models.PositiveSmallIntegerField(null=True)
rating = models.CharField(max_length=24, null=True)
released = models.DateField(null=True)
plot = models.TextField(null=True)
fullplot = models.TextField(null=True)
poster = models.URLField(null=True)
director = models.ManyToManyField(Person, related_name="director")
writer = models.ManyToManyField(Person, related_name="writer")
cast = models.ManyToManyField(Person, related_name="cast")
genre = models.ManyToManyField(Genre)
def __unicode__(self):
return self.title
| from django.db import models
class Person(models.Model):
name = models.CharField(max_length=80)
def __unicode__(self):
return self.name
class Genre(models.Model):
name = models.CharField(max_length=40)
def __unicode__(self):
return self.name
class Movie(models.Model):
movie_id = models.CharField(max_length=7, primary_key=True)
title = models.CharField(max_length=60)
year = models.PositiveSmallIntegerField()
runtime = models.PositiveSmallIntegerField()
rating = models.CharField(max_length=12)
director = models.ManyToManyField(Person, related_name="director")
writer = models.ManyToManyField(Person, related_name="writer")
cast = models.ManyToManyField(Person, related_name="cast")
genre = models.ManyToManyField(Genre)
released = models.DateField()
plot = models.TextField()
fullplot = models.TextField()
poster = models.URLField()
def __unicode__(self):
return self.title
|
Add courseScores hashmap for course priority ranking | package com.google.sps.data;
import java.util.List;
import java.util.HashMap;
public class GenerateScheduleRequest {
List<Course> courses;
InputCriterion criterion;
BasicInfo basicInfo;
public GenerateScheduleRequest(){};
public List<Course> getCourses() {
return this.courses;
}
public List<TimeRange> getTimePreferences() {
return this.criterion.timePreferences;
}
public String getPreferredSubject() {
return this.criterion.preferredSubject;
}
public HashMap<String, Integer> getCourseScores() {
return this.criterion.courseScores;
}
public Invariants getCredits() {
return this.basicInfo.credits;
}
public String getTermStartDate() {
return this.basicInfo.termDates.startDate;
}
public String getTermEndDate() {
return this.basicInfo.termDates.endDate;
}
}
class InputCriterion {
List<TimeRange> timePreferences;
String preferredSubject;
HashMap<String, Integer> courseScores;
}
class BasicInfo {
Invariants credits;
TermDates termDates;
}
class TermDates {
String startDate;
String endDate;
}
| package com.google.sps.data;
import java.util.List;
public class GenerateScheduleRequest {
List<Course> courses;
InputCriterion criterion;
BasicInfo basicInfo;
public GenerateScheduleRequest(){};
public List<Course> getCourses() {
return this.courses;
}
public List<TimeRange> getTimePreferences() {
return this.criterion.timePreferences;
}
public String getPreferredSubject() {
return this.criterion.preferredSubject;
}
public Invariants getCredits() {
return this.basicInfo.credits;
}
public String getTermStartDate() {
return this.basicInfo.termDates.startDate;
}
public String getTermEndDate() {
return this.basicInfo.termDates.endDate;
}
}
class InputCriterion {
List<TimeRange> timePreferences;
String preferredSubject;
}
class BasicInfo {
Invariants credits;
TermDates termDates;
}
class TermDates {
String startDate;
String endDate;
}
|
Remove unary and binary restrictions. | 'use strict'
const fs = require('fs-extra')
const globby = require('globby')
const path = require('path')
const pify = require('pify')
/*----------------------------------------------------------------------------*/
const isFile = async (p) => (await stat(p)).isFile()
const read = pify(fs.readFile)
const remove = pify(fs.remove)
const stat = pify(fs.stat)
const write = pify(fs.outputFile)
const glob = async (patterns, opts) => {
patterns = Array.isArray(patterns) ? patterns : [patterns]
const nodir = !patterns.some((p) => !p.startsWith('!') && p.endsWith('/'))
try {
return await globby(patterns, Object.assign({
'nocase': true,
'nodir': nodir,
'noext': true,
'realpath': true,
'strict': true
}, opts))
} catch (e) {}
return []
}
const move = (() => {
const _move = pify(fs.move)
return async (source, dest, opts={}) => {
if (source !== dest && path.resolve(source) !== path.resolve(dest)) {
return _move(source, dest, opts)
}
}
})()
module.exports = {
glob,
isFile,
move,
read,
remove,
stat,
write
}
| 'use strict'
const fs = require('fs-extra')
const globby = require('globby')
const path = require('path')
const pify = require('pify')
/*----------------------------------------------------------------------------*/
const binary = (func) => (a, b) => func(a, b)
const unary = (func) => (a) => func(a)
const isFile = async (p) => (await stat(p)).isFile()
const read = binary(pify(fs.readFile))
const remove = unary(pify(fs.remove))
const stat = unary(pify(fs.stat))
const write = binary(pify(fs.outputFile))
const glob = async (patterns, opts) => {
patterns = Array.isArray(patterns) ? patterns : [patterns]
const nodir = !patterns.some((p) => !p.startsWith('!') && p.endsWith('/'))
try {
return await globby(patterns, Object.assign({
'nocase': true,
'nodir': nodir,
'noext': true,
'realpath': true,
'strict': true
}, opts))
} catch (e) {}
return []
}
const move = (() => {
const _move = pify(fs.move)
return async (source, dest, opts={}) => {
if (source !== dest && path.resolve(source) !== path.resolve(dest)) {
return _move(source, dest, opts)
}
}
})()
module.exports = {
glob,
isFile,
move,
read,
remove,
stat,
write
}
|
Add indexes to type and bucket columns | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddColumnsToCategorizePosts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->string('type')->index()->after('northstar_id')->default('photo')->comment('Describes the type of post submitted e.g. photo, call, voter-reg');
$table->string('action_bucket')->index()->after('type')->comment('Describes the bucket the action is tied to. A campaign could ask for multiple types of actions throught the life of the campaign.');
$table->text('details')->after('remote_addr')->comment('A JSON field to store extra details about a post.');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('type');
$table->dropColumn('action_bucket');
$table->dropColumn('details');
});
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddColumnsToCategorizePosts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->string('type')->after('northstar_id')->default('photo')->comment('Describes the type of post submitted e.g. photo, call, voter-reg');
$table->string('action_bucket')->after('type')->comment('Describes the bucket the action is tied to. A campaign could ask for multiple types of actions throught the life of the campaign.');
$table->text('details')->after('remote_addr')->comment('A JSON field to store extra details about a post.');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('type');
$table->dropColumn('action_bucket');
$table->dropColumn('details');
});
}
}
|
Add env variable for process id in forked processes | let Promise
try {
Promise = require('bluebird')
} catch (err) {
Promise = global.Promise
}
const child = require('child_process')
/**
* Shard cluster structure
* @prop {ChildProcess} worker The child process being handled
*/
class Cluster {
/**
* Creates a new Cluster instance
* @arg {String} file Path to file to run
* @arg {Number} id ID of the cluster
*/
constructor (file, id) {
this.worker = child.fork(file, { env: Object.assign(env, { PROCESS_ID: id })})
this.id = id
}
/**
* Awaits for a certain response
* @arg {String} message Message to send
* @returns {Promise<Object>}
*/
awaitResponse (message) {
return new Promise((resolve, reject) => {
const awaitListener = (msg) => {
if (!['resp', 'error'].includes(msg.op)) return
return resolve({ id: this.id, result: msg.d, code: msg.code })
}
this.worker.once('message', awaitListener)
this.worker.send(message)
setTimeout(() => {
this.worker.removeListener('message', awaitListener)
return reject('IPC request timed out after 5000ms')
}, 5000)
})
}
}
module.exports = Cluster
| let Promise
try {
Promise = require('bluebird')
} catch (err) {
Promise = global.Promise
}
const child = require('child_process')
/**
* Shard cluster structure
* @prop {ChildProcess} worker The child process being handled
*/
class Cluster {
/**
* Creates a new Cluster instance
* @arg {String} file Path to file to run
* @arg {Number} id ID of the cluster
*/
constructor (file, id) {
this.worker = child.fork(file)
this.id = id
}
/**
* Awaits for a certain response
* @arg {String} message Message to send
* @returns {Promise<Object>}
*/
awaitResponse (message) {
return new Promise((resolve, reject) => {
const awaitListener = (msg) => {
if (!['resp', 'error'].includes(msg.op)) return
return resolve({ id: this.id, result: msg.d, code: msg.code })
}
this.worker.once('message', awaitListener)
this.worker.send(message)
setTimeout(() => {
this.worker.removeListener('message', awaitListener)
return reject('IPC request timed out after 5000ms')
}, 5000)
})
}
}
module.exports = Cluster
|
Add support for NotoSans and Arimo. | """
Copyright 2014 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.
"""
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
elif fontname[0:8] == 'NotoSans':
family_dir = 'NotoSans/'
elif fontname[0:5] == 'Arimo':
family_dir = 'Arimo/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
| """
Copyright 2014 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.
"""
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
|
Use walk_preorder instead of manual visiting | import pprint
import sys
import clang.cindex
from clang.cindex import CursorKind
def handle_function_decl(fdecl_cursor):
children = list(fdecl_cursor.get_children())
# Only interested in functions that have a CUDAGLOBAL_ATTR attached.
if not any(c.kind == CursorKind.CUDAGLOBAL_ATTR for c in children):
return
print fdecl_cursor.displayname
# Look at param decls
for c in children:
if c.kind == CursorKind.PARM_DECL:
print '>>', c.spelling, c.type.spelling
index = clang.cindex.Index.create()
# Parse as CUDA
tu = index.parse(sys.argv[1], args=['-x', 'cuda'])
diagnostics = list(tu.diagnostics)
if len(diagnostics) > 0:
print 'There were parse errors'
pprint.pprint(diagnostics)
else:
for c in tu.cursor.walk_preorder():
if c.kind == CursorKind.FUNCTION_DECL:
handle_function_decl(c)
| import pprint
import sys
import clang.cindex
from clang.cindex import CursorKind
def handle_function_decl(fdecl_cursor):
children = list(fdecl_cursor.get_children())
# Only interested in functions that have a CUDAGLOBAL_ATTR attached.
if not any(c.kind == CursorKind.CUDAGLOBAL_ATTR for c in children):
return
print fdecl_cursor.displayname
# Look at param decls
for c in children:
if c.kind == CursorKind.PARM_DECL:
print '>>', c.spelling, c.type.spelling
def visitor(cursor):
if cursor.kind == CursorKind.FUNCTION_DECL:
handle_function_decl(cursor)
for child in cursor.get_children():
visitor(child)
index = clang.cindex.Index.create()
# Parse as CUDA
tu = index.parse(sys.argv[1], args=['-x', 'cuda'])
diagnostics = list(tu.diagnostics)
if len(diagnostics) > 0:
print 'There were parse errors'
pprint.pprint(diagnostics)
else:
visitor(tu.cursor)
|
[CHORE] Clean up gateway users controller from refactor to model | var User = require('../models/user'),
GatewayAccount = require('../models/gateway_account'),
utils = require('../../lib/utils'),
util = require('util');
module.exports = (function() {
function account(req, res) {
GatewayAccount.find({where: {
userId: req.params.userId
}}).complete(function(err, account){
if (err) { res.send({ success: false }) }
res.send({ success: true, gatewayAccount: account[0] })
})
}
function create(req, res) {
req.checkBody('name', 'Invalid name').notEmpty().isAlphanumeric()
req.checkBody('password', 'Invalid password').notEmpty().isAlphanumeric()
var errors = req.validationErrors();
if (errors) {
res.send({ error: util.inspect(errors) }, 400)
return;
}
var user = User.createEncrypted({ name: req.body.name, password: req.body.password }, function(err, user){
if (err) { res.send({ error: err }); return }
res.send({ success: true, user: user })
})
}
return {
account: account,
create: create
}
})();
| var User = require('../models/user'),
GatewayAccount = require('../models/gateway_account'),
utils = require('../../lib/utils'),
util = require('util');
module.exports = (function() {
function account(req, res) {
GatewayAccount.find({where: {
userId: req.params.userId
}}).complete(function(err, account){
if (err) { account = [] }
res.send(account)
})
}
function create(req, res) {
req.checkBody('name', 'Invalid name')
.notEmpty().isAlphanumeric();
req.checkBody('password', 'Invalid password')
.notEmpty().isAlphanumeric();
var errors = req.validationErrors();
if (errors) {
res.send({ error: util.inspect(errors) }, 400)
return;
}
var salt = utils.generateSalt()
var password = req.body.password
var passwordHash = utils.saltPassword(password, salt)
var user = User.createEncrypted(req.body.name, password, function(err, user){
if (err) { res.send({ error: err }); return }
res.send({ success: true, user: user })
})
}
return {
account: account,
create: create
}
})();
|
Add publish reference for config | <?php namespace Panlogic\Fonix;
/**
* Fonix helper package by Panlogic Ltd.
*
* NOTICE OF LICENSE
*
* Licensed under the terms from Panlogic Ltd.
*
* @package Fonix
* @version 1.0.0
* @author Panlogic Ltd
* @license GPL3
* @copyright (c) 2015, Panlogic Ltd
* @link http://www.panlogic.co.uk
*/
use Illuminate\Support\ServiceProvider;
class FonixServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/../../config/fonix.php' => config_path('fonix.php'),
]);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['fonix'] = $this->app->share(function($app)
{
return new Fonix;
});
$this->app->booting(function()
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Fonix', 'Panlogic\Fonix\Facades\Fonix');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('fonix');
}
} | <?php namespace Panlogic\Fonix;
/**
* Fonix helper package by Panlogic Ltd.
*
* NOTICE OF LICENSE
*
* Licensed under the terms from Panlogic Ltd.
*
* @package Fonix
* @version 1.0.0
* @author Panlogic Ltd
* @license GPL3
* @copyright (c) 2015, Panlogic Ltd
* @link http://www.panlogic.co.uk
*/
use Illuminate\Support\ServiceProvider;
class FonixServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['fonix'] = $this->app->share(function($app)
{
return new Fonix;
});
$this->app->booting(function()
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Fonix', 'Panlogic\Fonix\Facades\Fonix');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('fonix');
}
} |
Allow specifying test.py flags in 'inv test' | from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx, coverage=False, flags=""):
if "--verbose" not in flags.split():
flags += " --verbose"
runner = "python"
if coverage:
runner = "coverage run --source=paramiko"
ctx.run("{0} test.py {1}".format(runner, flags), pty=True)
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
# Build docs first. Use terribad workaround pending invoke #146
ctx.run("inv docs")
# Move the built docs into where Epydocs used to live
target = 'docs'
rmtree(target, ignore_errors=True)
# TODO: make it easier to yank out this config val from the docs coll
copytree('sites/docs/_build', target)
# Publish
publish(ctx)
# Remind
print("\n\nDon't forget to update RTD's versions page for new minor releases!")
ns = Collection(test, coverage, release, docs, www)
| from os import mkdir
from os.path import join
from shutil import rmtree, copytree
from invoke import Collection, ctask as task
from invocations.docs import docs, www
from invocations.packaging import publish
# Until we move to spec-based testing
@task
def test(ctx):
ctx.run("python test.py --verbose", pty=True)
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task
def release(ctx):
# Build docs first. Use terribad workaround pending invoke #146
ctx.run("inv docs")
# Move the built docs into where Epydocs used to live
target = 'docs'
rmtree(target, ignore_errors=True)
# TODO: make it easier to yank out this config val from the docs coll
copytree('sites/docs/_build', target)
# Publish
publish(ctx)
# Remind
print("\n\nDon't forget to update RTD's versions page for new minor releases!")
ns = Collection(test, coverage, release, docs, www)
|
Remove superfluous variable, improve documentation | // Adds toggle for custom theme to Page Action.
//
// This file *only* controls that toggle,
// the logic behind enabling/disabling the theme is found in
// core/js/customThemeHandler.js
var customThemeToggle = (function(){
var optionsLink = document.getElementById("options-link");
var enableTheme = document.getElementById("enable-theme");
chrome.storage.local.get("cmCustomThemeEnabled", function(response){
enableTheme.checked = !!response.cmCustomThemeEnabled;
setEventListeners();
});
function setEventListeners() {
// Need to manually add link functionality to the options page link.
// Alternatively, could just dynamically add the URL-- I'm not sure it matters much though.
optionsLink.addEventListener("click", function(e){
// needed to prevent the click from propagating to the checkbox
e.preventDefault();
//http://stackoverflow.com/a/16130739
var optionsUrl = chrome.extension.getURL('core/html/ces_options.html');
chrome.tabs.query({url: optionsUrl}, function(tabs) {
if (tabs.length) {
chrome.tabs.update(tabs[0].id, {active: true});
} else {
chrome.tabs.create({url: optionsUrl});
}
});
});
enableTheme.addEventListener("click", function(){
chrome.storage.local.set({"cmCustomThemeEnabled":enableTheme.checked}, function(){
sendToActiveTab({method:"enable-custom-theme", data:enableTheme.checked});
});
});
}
})();
| // Adds toggle for custom theme to Page Action.
//
// This file *only* controls that toggle,
// the logic behind enabling/disabling the theme is found in
// core/js/customThemeHandler.js
var customThemeToggle = (function(){
var optionsLink = document.getElementById("options-link");
var enableTheme = document.getElementById("enable-theme");
chrome.storage.local.get("cmCustomThemeEnabled", function(response){
var themeIsEnabled = !!response.cmCustomThemeEnabled;
enableTheme.checked = themeIsEnabled;
setEventListeners();
});
function setEventListeners() {
optionsLink.addEventListener("click", function(e){
// needed to prevent the click from propagating to the checkbox
e.preventDefault();
//http://stackoverflow.com/a/16130739
var optionsUrl = chrome.extension.getURL('core/html/ces_options.html');
chrome.tabs.query({url: optionsUrl}, function(tabs) {
if (tabs.length) {
chrome.tabs.update(tabs[0].id, {active: true});
} else {
chrome.tabs.create({url: optionsUrl});
}
});
});
enableTheme.addEventListener("click", function(){
chrome.storage.local.set({"cmCustomThemeEnabled":enableTheme.checked}, function(){
sendToActiveTab({method:"enable-custom-theme", data:enableTheme.checked});
});
});
}
})();
|
Throw out unnecessary dependencies in mFC | "use strict";
angular.module('arethusa.morph').directive('mirrorMorphForm', [
'morph',
function(morph) {
return {
restrict: 'A',
scope: {
form: '=mirrorMorphForm',
tokenId: '='
},
link: function(scope, element, attrs) {
var morphToken = morph.analyses[scope.tokenId];
var menuId = 'mfc' + scope.tokenId;
function newCustomForm() {
var form = angular.copy(scope.form);
// We might want to clean up even more here - such as the
// lexical inventory information. Revisit later.
delete form.origin;
return form;
}
element.bind('click', function() {
scope.$apply(function() {
morphToken.customForm = newCustomForm();
});
});
}
};
}
]);
| "use strict";
angular.module('arethusa.morph').directive('mirrorMorphForm', [
'morph',
'$location',
'$anchorScroll',
'$document',
'$timeout',
function(morph, $location, $anchorScroll, $document, $timeout) {
return {
restrict: 'A',
scope: {
form: '=mirrorMorphForm',
tokenId: '='
},
link: function(scope, element, attrs) {
var morphToken = morph.analyses[scope.tokenId];
var menuId = 'mfc' + scope.tokenId;
function newCustomForm() {
var form = angular.copy(scope.form);
// We might want to clean up even more here - such as the
// lexical inventory information. Revisit later.
delete form.origin;
return form;
}
element.bind('click', function() {
scope.$apply(function() {
morphToken.customForm = newCustomForm();
});
});
}
};
}
]);
|
Check actual node-supported encodings on startup | var Iconv = require('iconv-lite');
var NODE_ENCODING = [
'ascii',
'utf8',
'utf16le',
'ucs2',
'base64',
'latin1',
'binary',
'hex'
].reduce(function (map, item) {
map[item] = Buffer.isEncoding(item);
return map;
}, {});
exports.decode = function(buffer, encoding, options) {
if (NODE_ENCODING[encoding]) {
return buffer.toString(encoding);
}
var decoder = Iconv.getDecoder(encoding, options || {});
var res = decoder.write(buffer);
var trail = decoder.end();
return trail ? res + trail : res;
};
exports.encode = function(string, encoding, options) {
if (NODE_ENCODING[encoding]) {
return Buffer.from(string, encoding);
}
var encoder = Iconv.getEncoder(encoding, options || {});
var res = encoder.write(string);
var trail = encoder.end();
return trail && trail.length > 0 ? Buffer.concat([res, trail]) : res;
};
| var Iconv = require('iconv-lite');
var NODE_ENCODING = {
'ascii': true,
'utf8': true,
'utf16le': true,
'ucs2': true,
'base64': true,
'latin1': true,
'binary': true,
'hex': true
};
exports.decode = function(buffer, encoding, options) {
if (NODE_ENCODING[encoding]) {
return buffer.toString(encoding);
}
var decoder = Iconv.getDecoder(encoding, options || {});
var res = decoder.write(buffer);
var trail = decoder.end();
return trail ? res + trail : res;
};
exports.encode = function(string, encoding, options) {
if (NODE_ENCODING[encoding]) {
return Buffer.from(string, encoding);
}
var encoder = Iconv.getEncoder(encoding, options || {});
var res = encoder.write(string);
var trail = encoder.end();
return trail && trail.length > 0 ? Buffer.concat([res, trail]) : res;
};
|
MNT: Fix new lint found by flake8 | # Copyright (c) 2015,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for reading, calculating, and plotting with weather data."""
# What do we want to pull into the top-level namespace?
import os
import sys
import warnings
if sys.version_info < (3,):
raise ImportError(
"""You are running MetPy 0.12.0 or greater on Python 2.
MetPy 0.12.0 and above are no longer compatible with Python 2, but this version was
still installed. Sorry about that; it should not have happened. Make sure you have
pip >= 9.0 to avoid this kind of issue, as well as setuptools >= 24.2:
$ pip install pip setuptools --upgrade
Your choices:
- Upgrade to Python 3.
- Install an older version of MetPy:
$ pip install 'metpy=0.11.1'
""")
# Must occur before below imports
warnings.filterwarnings('ignore', 'numpy.dtype size changed')
os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'
from ._version import get_version # noqa: E402
from .xarray import * # noqa: F401, F403, E402
__version__ = get_version()
del get_version
| # Copyright (c) 2015,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for reading, calculating, and plotting with weather data."""
# What do we want to pull into the top-level namespace?
import os
import sys
import warnings
if sys.version_info < (3,):
raise ImportError(
"""You are running MetPy 0.12.0 or greater on Python 2.
MetPy 0.12.0 and above are no longer compatible with Python 2, but this version was
still installed. Sorry about that; it should not have happened. Make sure you have
pip >= 9.0 to avoid this kind of issue, as well as setuptools >= 24.2:
$ pip install pip setuptools --upgrade
Your choices:
- Upgrade to Python 3.
- Install an older version of MetPy:
$ pip install 'metpy=0.11.1'
""")
# Must occur before below imports
warnings.filterwarnings('ignore', 'numpy.dtype size changed')
os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'
from ._version import get_version # noqa: E402
from .xarray import * # noqa: F401, F403
__version__ = get_version()
del get_version
|
Fix for part category API | from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryDetailSerializer
| from rest_framework import generics
from .models import PartCategory, Part, PartParameter
from .serializers import PartSerializer
from .serializers import PartCategoryBriefSerializer, PartCategoryDetailSerializer
from .serializers import PartParameterSerializer
class PartDetail(generics.RetrieveAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartParameters(generics.ListAPIView):
def get_queryset(self):
part_id = self.kwargs['pk']
return PartParameter.objects.filter(part=part_id)
serializer_class = PartParameterSerializer
class PartList(generics.ListAPIView):
queryset = Part.objects.all()
serializer_class = PartSerializer
class PartCategoryDetail(generics.RetrieveAPIView):
""" Return information on a single PartCategory
"""
queryset = PartCategory.objects.all()
serializer_class = PartCategoryDetailSerializer
class PartCategoryList(generics.ListAPIView):
""" Return a list of all top-level part categories.
Categories are considered "top-level" if they do not have a parent
"""
queryset = PartCategory.objects.filter(parent=None)
serializer_class = PartCategoryBriefSerializer
|
Update form to new interface ... | <?php
namespace YouFood\ApiBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* OrderType
*
* @author Adrien Brault <adrien.brault@gmail.com>
*/
class OrderType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('collations', 'entity', array(
'class' => 'YouFoodMainBundle:Collation',
'multiple' => true,
));
$builder->add('menus', 'entity', array(
'class' => 'YouFoodMainBundle:Menu',
'multiple' => true,
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'order';
}
/**
* {@inheritdoc}
*/
public function getDefaultOptions()
{
return array(
'csrf_protection' => false,
);
}
}
| <?php
namespace YouFood\ApiBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
/**
* OrderType
*
* @author Adrien Brault <adrien.brault@gmail.com>
*/
class OrderType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('collations', 'entity', array(
'class' => 'YouFoodMainBundle:Collation',
'multiple' => true,
));
$builder->add('menus', 'entity', array(
'class' => 'YouFoodMainBundle:Menu',
'multiple' => true,
));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'order';
}
/**
* {@inheritdoc}
*/
public function getDefaultOptions()
{
return array(
'csrf_protection' => false,
);
}
}
|
Handle special characters by urlencode, like 'q=id:123' | try:
from urllib.parse import urlparse, urlencode, parse_qs
except ImportError:
from urlparse import urlparse, parse_qs
from urllib import urlencode
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
import requests
class AWSV4Sign(requests.auth.AuthBase):
"""
AWS V4 Request Signer for Requests.
"""
def __init__(self, credentials, region, service):
if not region:
raise ValueError("You must supply an AWS region")
self.credentials = credentials
self.region = region
self.service = service
def __call__(self, r):
url = urlparse(r.url)
path = url.path or '/'
querystring = ''
if url.query:
querystring = '?' + urlencode(parse_qs(url.query), doseq=True)
safe_url = url.scheme + '://' + url.netloc.split(':')[0] + path + querystring
request = AWSRequest(method=r.method.upper(), url=safe_url, data=r.body)
SigV4Auth(self.credentials, self.service, self.region).add_auth(request)
r.headers.update(dict(request.headers.items()))
return r
| try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
import requests
class AWSV4Sign(requests.auth.AuthBase):
"""
AWS V4 Request Signer for Requests.
"""
def __init__(self, credentials, region, service):
if not region:
raise ValueError("You must supply an AWS region")
self.credentials = credentials
self.region = region
self.service = service
def __call__(self, r):
url = urlparse(r.url)
path = url.path or '/'
if url.query:
querystring = '?' + url.query
else:
querystring = ''
safe_url = url.scheme + '://' + url.netloc.split(':')[0] + path + querystring
request = AWSRequest(method=r.method.upper(), url=safe_url, data=r.body)
SigV4Auth(self.credentials, self.service, self.region).add_auth(request)
r.headers.update(dict(request.headers.items()))
return r
|
Remove 'en' restriction when checking provenance for blackout | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dspace.doi;
import java.sql.SQLException;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.MetadataSchema;
/**
* Convenience methods involved in registering DOIs.
* @author dan
*/
public class DryadDOIRegistrationHelper {
public static final String REGISTER_PENDING_PUBLICATION_STEP = "registerPendingPublicationStep";
public static boolean isDataPackageInPublicationBlackout(Item dataPackage) throws SQLException {
// Publication blackout is indicated by provenance metadata
boolean isInBlackout = false;
DCValue provenance[] = dataPackage.getMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", Item.ANY);
for(DCValue dcValue : provenance) {
// only return true if the last recorded provenance indicates publication blackout
if(dcValue.value != null)
if(dcValue.value.contains("Entered publication blackout")) {
isInBlackout = true;
} else {
isInBlackout = false;
}
}
// now find something that would negate blackout
return isInBlackout;
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dspace.doi;
import java.sql.SQLException;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.MetadataSchema;
/**
* Convenience methods involved in registering DOIs.
* @author dan
*/
public class DryadDOIRegistrationHelper {
public static final String REGISTER_PENDING_PUBLICATION_STEP = "registerPendingPublicationStep";
public static boolean isDataPackageInPublicationBlackout(Item dataPackage) throws SQLException {
// Publication blackout is indicated by provenance metadata
boolean isInBlackout = false;
DCValue provenance[] = dataPackage.getMetadata(MetadataSchema.DC_SCHEMA, "description", "provenance", "en");
for(DCValue dcValue : provenance) {
// only return true if the last recorded provenance indicates publication blackout
if(dcValue.value != null)
if(dcValue.value.contains("Entered publication blackout")) {
isInBlackout = true;
} else {
isInBlackout = false;
}
}
// now find something that would negate blackout
return isInBlackout;
}
}
|
Add reference to source code | <!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>about cheeseb.us radio</title>
<link rel="stylesheet" href="/stylesheet.css">
</head>
<body>
<div id="content">
<h2>about cheeseb.us radio</h2>
<h6><a href="/radio/">cheeseb.us radio</a> cycles through a handpicked rotation of songs. the song database updates at least once a month.</h6>
<h6>albums prohibiting unauthorized copying and/or broadcasting are excluded from the rotation to the best extent possible.</h6>
<h6>on top of that, cheeseb.us radio operates on a NonCommercial basis.</h6>
<h6>the source code is available on <a href="https://github.com/pnaf/cheeseb.us/tree/master/radio">GitHub</a>.
<h6>other questions? <a href="mailto:admin@cheeseb.us">email</a></h6>
</div>
</body>
| <!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>about cheeseb.us radio</title>
<link rel="stylesheet" href="/stylesheet.css">
</head>
<body>
<div id="content">
<h2>about cheeseb.us radio</h2>
<h6><a href="/radio/">cheeseb.us radio</a> cycles through a handpicked rotation of songs. the song database updates at least once a month.</h6>
<h6>albums prohibiting unauthorized copying and/or broadcasting are excluded from the rotation to the best extent possible.</h6>
<h6>on top of that, cheeseb.us radio operates on a NonCommercial basis.</h6>
<h6>(source code and other juicy backend stuff will be out in the near future. ^^,)</h6>
<h6>other questions? <a href="mailto:admin@cheeseb.us">email</a></h6>
</div>
</body>
|
Include dev comment explaing filename |
#!/bin/python3
import math
import os
import random
import re
import sys
# Note the name of the file is based on this URL:
# https://www.hackerrank.com/challenges/torque-and-development/problem
# The problem name is "Roads and Libraries"
def roadsAndLibraries(n, c_lib, c_road, cities):
print("n {}, c_lib {}, c_road {}, cities {}".format(n, c_lib, c_road, cities))
return 0
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
num_queries = int(input())
for _query in range(num_queries):
n, m, c_lib, c_road = list(map(int, input().split()))
cities = []
for _city in range(m):
cities.append(list(map(int, input().rstrip().split())))
result = roadsAndLibraries(n, c_lib, c_road, cities)
fptr.write(str(result) + '\n')
fptr.close()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the roadsAndLibraries function below.
def roadsAndLibraries(n, c_lib, c_road, cities):
print("n {}, c_lib {}, c_road {}, cities {}".format(n, c_lib, c_road, cities))
return 0
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
num_queries = int(input())
for _query in range(num_queries):
n, m, c_lib, c_road = list(map(int, input().split()))
cities = []
for _city in range(m):
cities.append(list(map(int, input().rstrip().split())))
result = roadsAndLibraries(n, c_lib, c_road, cities)
fptr.write(str(result) + '\n')
fptr.close()
|
Rewrite SecureController and handle extra exception | <?php
namespace Koala\ContentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SecuredController extends Controller
{
protected function can_edit()
{
try {
// Check if user has right to edit
$editor_role = $this->container->getParameter('koala_content.editor_role');
return $this->get('security.context')->isGranted($editor_role);
} catch (\Exception $e) {
switch (get_class($e)) {
case 'Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException':
case 'Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException':
// Security is not enabled so everyone can edit
return true;
default:
throw $e;
}
}
}
}
| <?php
namespace Koala\ContentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
class SecuredController extends Controller
{
protected function can_edit()
{
try {
// Check if user has right to edit
$editor_role = $this->container->getParameter('koala_content.editor_role');
$can_edit = $this->get('security.context')->isGranted($editor_role);
} catch (AuthenticationCredentialsNotFoundException $e) {
// Security is not enabled so everyone can edit
$can_edit = true;
}
return $can_edit;
}
}
|
Refactor run_from_ipython() implementation to make it pass static code analysis test | # -*- coding: utf-8 -*-
import six
from formats import FormatBank, discover_json, discover_yaml
formats = FormatBank()
discover_json(formats, content_type='application/json')
discover_yaml(formats, content_type='application/x-yaml')
def run_from_ipython():
return getattr(__builtins__, "__IPYTHON__", False)
class Bunch(dict):
def __init__(self, kwargs=None):
if kwargs is None:
kwargs = {}
for key, value in six.iteritems(kwargs):
kwargs[key] = bunchify(value)
super().__init__(kwargs)
self.__dict__ = self
def bunchify(obj):
if isinstance(obj, (list, tuple)):
return [bunchify(item) for item in obj]
if isinstance(obj, dict):
return Bunch(obj)
return obj
| # -*- coding: utf-8 -*-
import six
from formats import FormatBank, discover_json, discover_yaml
formats = FormatBank()
discover_json(formats, content_type='application/json')
discover_yaml(formats, content_type='application/x-yaml')
def run_from_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
class Bunch(dict):
def __init__(self, kwargs=None):
if kwargs is None:
kwargs = {}
for key, value in six.iteritems(kwargs):
kwargs[key] = bunchify(value)
super().__init__(kwargs)
self.__dict__ = self
def bunchify(obj):
if isinstance(obj, (list, tuple)):
return [bunchify(item) for item in obj]
if isinstance(obj, dict):
return Bunch(obj)
return obj
|
Add click event to HUD glimpse logo to open the client | 'use strict';
// DEV TIME CODE
if (FAKE_SERVER) {
require('fake');
}
// DEV TIME CODE
require('./index.scss');
var $ = require('$jquery');
var util = require('lib/util');
var state = require('./state');
var repository = require('./repository');
var sections = require('./sections/section');
//var details = args.newData.hud;
var setup = state.current();
// only load things when we have the data ready to go
repository.getData(function(details) {
// generate the html needed for the sections
var html = sections.render(details, setup);
html = '<div class="glimpse"><div class="glimpse-icon"></div><div class="glimpse-hud">' + html + '</div></div>';
// insert the html into the dom
var holder = $(html).appendTo('body')
// force the correct state from previous load
state.setup(holder);
// setup events that we need to listen to
sections.postRender(holder);
// TODO: need to find a better place for this
$('.glimpse-icon').click(function() {
window.open(util.resolveClientUrl(), 'GlimpseClient');
});
}); | 'use strict';
// DEV TIME CODE
if (FAKE_SERVER) {
require('fake');
}
// DEV TIME CODE
require('./index.scss');
var $ = require('$jquery');
var state = require('./state');
var repository = require('./repository');
var sections = require('./sections/section');
//var details = args.newData.hud;
var setup = state.current();
// only load things when we have the data ready to go
repository.getData(function(details) {
// generate the html needed for the sections
var html = sections.render(details, setup);
html = '<div class="glimpse"><div class="glimpse-icon"></div><div class="glimpse-hud">' + html + '</div></div>';
// insert the html into the dom
var holder = $(html).appendTo('body')
// force the correct state from previous load
state.setup(holder);
// setup events that we need to listen to
sections.postRender(holder);
}); |
Add SciPy version to pytest header |
import numba
import numpy
import pkg_resources
import pytest
import scipy
# The first version of numpy that broke backwards compat and improved printing.
#
# We set the printing format to legacy to maintain our doctests' compatibility
# with both newer and older versions.
#
# See: https://docs.scipy.org/doc/numpy/release.html#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
#
NUMPY_PRINT_ALTERING_VERSION = pkg_resources.parse_version('1.14.0')
@pytest.fixture(autouse=True)
def add_preconfigured_np(doctest_namespace):
"""
Fixture executed for every doctest.
Injects pre-configured numpy into each test's namespace.
Note that even with this, doctests might fail due to the lack of full
compatibility when using ``numpy.set_printoptions(legacy='1.13')``.
Some of the whitespace issues can be fixed by ``NORMALIZE_WHITESPACE``
doctest option, which is currently set in ``pytest.ini``.
See: https://github.com/numpy/numpy/issues/10383
"""
current_version = pkg_resources.parse_version(numpy.__version__)
if current_version >= NUMPY_PRINT_ALTERING_VERSION:
numpy.set_printoptions(legacy='1.13')
doctest_namespace['np'] = numpy
def pytest_report_header(config):
return 'Testing fastats using: Numba {}, NumPy {}, SciPy {}'.format(
numba.__version__, numpy.__version__, scipy.__version__,
)
|
import numba
import numpy
import pkg_resources
import pytest
# The first version of numpy that broke backwards compat and improved printing.
#
# We set the printing format to legacy to maintain our doctests' compatibility
# with both newer and older versions.
#
# See: https://docs.scipy.org/doc/numpy/release.html#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
#
NUMPY_PRINT_ALTERING_VERSION = pkg_resources.parse_version('1.14.0')
@pytest.fixture(autouse=True)
def add_preconfigured_np(doctest_namespace):
"""
Fixture executed for every doctest.
Injects pre-configured numpy into each test's namespace.
Note that even with this, doctests might fail due to the lack of full
compatibility when using ``numpy.set_printoptions(legacy='1.13')``.
Some of the whitespace issues can be fixed by ``NORMALIZE_WHITESPACE``
doctest option, which is currently set in ``pytest.ini``.
See: https://github.com/numpy/numpy/issues/10383
"""
current_version = pkg_resources.parse_version(numpy.__version__)
if current_version >= NUMPY_PRINT_ALTERING_VERSION:
numpy.set_printoptions(legacy='1.13')
doctest_namespace['np'] = numpy
def pytest_report_header(config):
return 'Testing fastats using: NumPy {}, numba {}'.format(
numpy.__version__, numba.__version__
)
|
Clear storage before each test | import { API } from 'api';
import superagent from 'superagent';
describe('api interface', () => {
beforeEach(() => {
API.clearStorage();
});
it('should export api version', () => {
expect(API.version).toBe('0.0.1');
});
it('should get 0 captured requests', () => {
expect(API.capturedRequests).toBeDefined();
expect(API.capturedRequests.length).toBe(0);
});
it('should get a captured request', (done) => {
expect(API.capturedRequests.length).toBe(0);
superagent.get('http://fake.com')
.timeout(20)
.end(() => {
expect(API.capturedRequests.length).toBe(1);
let request = API.capturedRequests[0];
expect(request.method).toBe('GET');
expect(request.url).toBe('http://fake.com');
done();
});
});
});
| import { API } from 'api';
import superagent from 'superagent';
describe('api interface', () => {
it('should export api version', () => {
expect(API.version).toBe('0.0.1');
});
it('should get 0 captured requests', () => {
expect(API.capturedRequests).toBeDefined();
expect(API.capturedRequests.length).toBe(0);
});
it('should get a captured request', (done) => {
expect(API.capturedRequests.length).toBe(0);
superagent.get('http://fake.com')
.timeout(20)
.end(() => {
expect(API.capturedRequests.length).toBe(1);
let request = API.capturedRequests[0];
expect(request.method).toBe('GET');
expect(request.url).toBe('http://fake.com');
done();
});
});
});
|
Add unicode encoding to sted.navn | import pytest
import turbasen
@pytest.fixture
def configure_dev():
turbasen.configure(ENDPOINT_URL='http://dev.nasjonalturbase.no/')
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_get(configure_dev):
sted = turbasen.Sted.get('52407fb375049e561500004e')
assert sted.navn == u'Tjørnbrotbu'
assert sted.ssr_id == 382116
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_lookup(configure_dev):
results = turbasen.Sted.lookup(pages=2)
result_list = list(results)
assert len(result_list) == turbasen.settings.Settings.LIMIT * 2
assert result_list[0].object_id != ''
| import pytest
import turbasen
@pytest.fixture
def configure_dev():
turbasen.configure(ENDPOINT_URL='http://dev.nasjonalturbase.no/')
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_get(configure_dev):
sted = turbasen.Sted.get('52407fb375049e561500004e')
assert sted.navn == 'Tjørnbrotbu'
assert sted.ssr_id == 382116
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_lookup(configure_dev):
results = turbasen.Sted.lookup(pages=2)
result_list = list(results)
assert len(result_list) == turbasen.settings.Settings.LIMIT * 2
assert result_list[0].object_id != ''
|
Use core object type when checking instanceof | <?php
/**
* Skeleton subclass for representing a row from the 'vendor_catalog_item' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*ac
* @package plugins.reach
* @subpackage model
*/
class VendorAlignmentCatalogItem extends VendorCatalogItem
{
public function applyDefaultValues()
{
$this->setServiceFeature(VendorServiceFeature::ALIGNMENT);
}
public function getTaskVersion($entryId, $jobData = null)
{
$taskVersion = parent::getTaskVersion($entryId, $jobData);
if(!$jobData || !($jobData instanceof kAlignmentVendorTaskData))
return $taskVersion;
/* @var $jobData kAlignmentVendorTaskData */
$attachmentAsset = assetPeer::retrieveById($jobData->getTextTranscriptAssetId());
if(!$attachmentAsset)
return $taskVersion;
return $taskVersion * $attachmentAsset->getVersion();
}
} // VendorCaptionsCatalogItem
| <?php
/**
* Skeleton subclass for representing a row from the 'vendor_catalog_item' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*ac
* @package plugins.reach
* @subpackage model
*/
class VendorAlignmentCatalogItem extends VendorCatalogItem
{
public function applyDefaultValues()
{
$this->setServiceFeature(VendorServiceFeature::ALIGNMENT);
}
public function getTaskVersion($entryId, $jobData = null)
{
$taskVersion = parent::getTaskVersion($entryId, $jobData);
if(!$jobData || !($jobData instanceof KalturaVendorTaskData))
return $taskVersion;
/* @var $jobData kAlignmentVendorTaskData */
$attachmentAsset = assetPeer::retrieveById($jobData->getTextTranscriptAssetId());
if(!$attachmentAsset)
return $taskVersion;
return $taskVersion * $attachmentAsset->getVersion();
}
} // VendorCaptionsCatalogItem
|
Fix formatISODuration documentation (ci skip) | import requiredArgs from '../_lib/requiredArgs/index.js'
/**
* @name formatISODuration
* @category Common Helpers
* @summary Format a duration object according as ISO 8601 duration string
*
* @description
* Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm)
*
* @param {Duration} duration - the duration to format
*
* @returns {String} The ISO 8601 duration string
* @throws {TypeError} Requires 1 argument
* @throws {Error} Argument must be an object
*
* @example
* // Format the given duration as ISO 8601 string
* const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 })
* // => 'P39Y2M20DT0H0M0S'
*/
export default function formatISODuration(duration) {
requiredArgs(1, arguments)
if (typeof duration !== 'object')
throw new Error('Duration must be an object')
const {
years = 0,
months = 0,
days = 0,
hours = 0,
minutes = 0,
seconds = 0
} = duration
return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S`
}
| import requiredArgs from '../_lib/requiredArgs/index.js'
/**
* @name formatISODuration
* @category Common Helpers
* @summary Format a Duration Object according to ISO 8601 Duration standards (https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm)
*
* @param {Duration} duration
*
* @returns {String} The ISO 8601 Duration string
* @throws {TypeError} Requires 1 argument
* @throws {Error} Argument must be an object
*
* @example
* // Get the ISO 8601 Duration between January 15, 1929 and April 4, 1968.
* const result = formatISODuration({ years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 })
* // => 'P39Y2M20DT0H0M0S'
*/
export default function formatISODuration(duration) {
requiredArgs(1, arguments)
if (typeof duration !== 'object')
throw new Error('Duration must be an object')
const {
years = 0,
months = 0,
days = 0,
hours = 0,
minutes = 0,
seconds = 0
} = duration
return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S`
}
|
Include nt.db with package data. | from setuptools import setup
description = 'New testament greek app for django.'
long_desc = open('README.rst').read()
setup(
name='django-greekapp',
version='0.0.1',
url='https://github.com/honza/greekapp',
install_requires=['django', 'redis'],
description=description,
long_description=long_desc,
author='Honza Pokorny',
author_email='me@honza.ca',
maintainer='Honza Pokorny',
maintainer_email='me@honza.ca',
packages=['greekapp'],
package_data={
'greekapp': [
'templates/greekapp/index.html',
'static/greekapp.min.js',
'static/greekapp.css',
'managements/commands/nt.db'
]
}
)
| from setuptools import setup
description = 'New testament greek app for django.'
long_desc = open('README.rst').read()
setup(
name='django-greekapp',
version='0.0.1',
url='https://github.com/honza/greekapp',
install_requires=['django', 'redis'],
description=description,
long_description=long_desc,
author='Honza Pokorny',
author_email='me@honza.ca',
maintainer='Honza Pokorny',
maintainer_email='me@honza.ca',
packages=['greekapp'],
package_data={
'greekapp': [
'templates/greekapp/index.html',
'static/greekapp.min.js',
'static/greekapp.css'
]
}
)
|
Use a separate set of urlpatterns for each file in views. | from django.conf.urls import patterns, include, url
from myuw_mobile.views.page import index, myuw_login
from myuw_mobile.views.api import StudClasScheCurQuar, TextbookCurQuar, InstructorContact
urlpatterns = patterns('myuw_mobile.views.page',
url(r'login', 'myuw_login'),
url(r'support', 'support'),
url(r'^visual', 'index'),
url(r'^textbooks', 'index'),
url(r'^instructor', 'index'),
url(r'^links', 'index'),
url(r'^$', 'index'),
)
urlpatterns += patterns('myuw_mobile.views.api',
url(r'^api/v1/books/current/$', TextbookCurQuar().run),
url(r'^api/v1/schedule/current/$', StudClasScheCurQuar().run),
url(r'^api/v1/person/(?P<regid>.*)$', InstructorContact().run),
)
| from django.conf.urls import patterns, include, url
from myuw_mobile.views.page import index, myuw_login
from myuw_mobile.views.api import StudClasScheCurQuar, TextbookCurQuar, InstructorContact
urlpatterns = patterns('myuw_mobile.views.page',
url(r'login', 'myuw_login'),
url(r'support', 'support'),
url(r'^visual', 'index'),
url(r'^textbooks', 'index'),
url(r'^instructor', 'index'),
url(r'^links', 'index'),
url(r'^$', 'index'),
url(r'^api/v1/schedule/current/$', StudClasScheCurQuar().run),
url(r'^api/v1/books/current/$', TextbookCurQuar().run),
url(r'^api/v1/person/(?P<regid>.*)$', InstructorContact().run),
)
|
Make the Websocket's connection header value case-insensitive | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CONNECT request
# to the proxy before they initiate the websocket connection.
# To make WebSockets work in these cases, supply
# `--ignore :80$` as an additional parameter.
# (see http://mitmproxy.org/doc/features/passthrough.html)
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
value = flow.response.headers.get_first("Connection", None)
if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CONNECT request
# to the proxy before they initiate the websocket connection.
# To make WebSockets work in these cases, supply
# `--ignore :80$` as an additional parameter.
# (see http://mitmproxy.org/doc/features/passthrough.html)
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
if flow.response.headers.get_first("Connection", None) == "Upgrade":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) |
fix: Handle IE override of button input type. | import React, { PropTypes } from 'react';
const BUTTON_TYPES = {
PRIMARY: 'primary',
LINK: 'link',
SUBMIT: 'submit'
};
const BUTTON_SIZES = {
SMALL: 'small',
LARGE: 'large'
};
function Button(props) {
let classes = ['pe-btn'];
if (props.type) {
// Handle IE overriding element type
if (props.type === BUTTON_TYPES.SUBMIT) {
props.type = BUTTON_TYPES.PRIMARY;
}
classes = classes.concat([`pe-btn--${props.type}`]);
}
if (props.size) {
classes = classes.concat([`pe-btn--${props.size}`]);
}
return <button className={classes.join(' ')} {...props}>{props.children}</button>;
}
Button.BUTTON_TYPES = BUTTON_TYPES;
Button.BUTTON_SIZES = BUTTON_SIZES;
Button.propTypes = {
type: PropTypes.oneOf(Object.keys(BUTTON_TYPES).map(k => k.toLowerCase())),
size: PropTypes.oneOf(Object.keys(BUTTON_SIZES).map(k => k.toLowerCase()))
};
export default Button;
| import React, { PropTypes } from 'react';
const BUTTON_TYPES = {
PRIMARY: 'primary',
LINK: 'link'
};
const BUTTON_SIZES = {
SMALL: 'small',
LARGE: 'large'
};
function Button(props) {
let classes = ['pe-btn'];
if (props.type) {
classes = classes.concat([`pe-btn--${props.type}`]);
}
if (props.size) {
classes = classes.concat([`pe-btn--${props.size}`]);
}
return <button className={classes.join(' ')} {...props}>{props.children}</button>;
}
Button.BUTTON_TYPES = BUTTON_TYPES;
Button.BUTTON_SIZES = BUTTON_SIZES;
Button.propTypes = {
type: PropTypes.oneOf(Object.keys(BUTTON_TYPES).map(k => k.toLowerCase())),
size: PropTypes.oneOf(Object.keys(BUTTON_SIZES).map(k => k.toLowerCase()))
};
export default Button;
|
Kill fuzzers when we've found a crash or timed out | import redis
from celery import Celery
from .Fuzzer import Fuzzer
import os
import time
import driller.config as config
import logging
l = logging.getLogger("fuzzer.tasks")
backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT)
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@app.task
def drill(binary, input, fuzz_bitmap, exit_on_eof=False):
binary_path = os.path.join(config.BINARY_DIR, binary)
fuzzer = Fuzzer(binary_path, "tests", config.FUZZER_INSTANCES)
try:
fuzzer.start()
except Fuzzer.EarlyCrash
l.info("binary crashed on dummy testcase, moving on...")
return 0
# start the fuzzer and poll for a crash or timeout
fuzzer.start()
while not fuzzer.found_crash() and not fuzzer.timed_out():
time.sleep(config.CRASH_CHECK_INTERVAL)
# make sure to kill the fuzzers when we're done
fuzzer.kill()
return fuzzer.found_crash()
| import redis
from celery import Celery
from .Fuzzer import Fuzzer
import os
import time
import driller.config as config
import logging
l = logging.getLogger("fuzzer.tasks")
backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT)
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@app.task
def drill(binary, input, fuzz_bitmap, exit_on_eof=False):
binary_path = os.path.join(config.BINARY_DIR, binary)
fuzzer = Fuzzer(binary_path, "tests", config.FUZZER_INSTANCES)
try:
fuzzer.start()
except Fuzzer.EarlyCrash
l.info("binary crashed on dummy testcase, moving on...")
return 0
# start the fuzzer and poll for a crash or timeout
fuzzer.start()
while not fuzzer.found_crash() and not fuzzer.timed_out():
time.sleep(config.CRASH_CHECK_INTERVAL)
return fuzzer.found_crash()
|
Add double quotes for JSON formatting | package data;
import util.UserAuthUtil;
public class ResponseBuilder {
public static String toJson(boolean isLoggedIn, String redirectURL) {
// logged in: { "isLoggedIn":{"/_ah/logout?continue=%2FLogin"}, "isLoggedOut":{""}}
// logged out: { "isLoggedIn":{""}, "isLoggedOut":{"/_ah/login?continue=%2FLogin"}}
return "{ \"isLoggedIn\":{\"" + buildLogout(isLoggedIn, redirectURL) + "\"}, " +
"\"isLoggedOut\":{\"" + buildLogin(isLoggedIn, redirectURL) + "\"}}";
}
private static String buildLogin(boolean isLoggedIn, String redirectURL) {
return isLoggedIn ? "" : UserAuthUtil.getLoginURL(redirectURL);
}
private static String buildLogout(boolean isLoggedIn, String redirectURL) {
return isLoggedIn ? UserAuthUtil.getLogoutURL(redirectURL) : "";
}
}
| package data;
import util.UserAuthUtil;
public class ResponseBuilder {
public static String toJson(boolean isLoggedIn, String redirectURL) {
// sample output (logged in): { "isLoggedIn" : {"logoutURL"}, "isLoggedOut" : {}}
// sample output (logged out): { "isLoggedIn" : {}, "isLoggedOut" : { "loginURL" }}
return "{ \"isLoggedIn\":{" + buildLogout(isLoggedIn, redirectURL) + "}, \"isLoggedOut\":{"
+ buildLogin(isLoggedIn, redirectURL) + "}}";
}
private static String buildLogin(boolean isLoggedIn, String redirectURL) {
return isLoggedIn ? "" : UserAuthUtil.getLoginURL(redirectURL);
}
private static String buildLogout(boolean isLoggedIn, String redirectURL) {
return isLoggedIn ? UserAuthUtil.getLogoutURL(redirectURL) : "";
}
}
|
Check for used protocol for preview-url | <?php
class Kwf_Controller_Action_Component_PreviewController extends Kwf_Controller_Action
{
public function indexAction()
{
$this->view->config = array(
'responsive' => Kwf_Config::getValue('kwc.responsive')
);
$this->view->xtype = 'kwf.component.preview';
$this->view->initialUrl = null;
if (preg_match('#^https?://#', $this->view->initialUrl)) {
$this->view->initialUrl = $this->_getParam('url');
}
if (!$this->view->initialUrl) {
$https = Kwf_Util_Https::domainSupportsHttps($_SERVER['HTTP_HOST']);
$protocol = $https ? 'https://' : 'http://';
$this->view->initialUrl = $protocol.$_SERVER['HTTP_HOST'].Kwf_Setup::getBaseUrl().'/';
}
}
public function redirectAction()
{
Kwf_Util_Redirect::redirect($this->_getParam('url'));
}
}
| <?php
class Kwf_Controller_Action_Component_PreviewController extends Kwf_Controller_Action
{
public function indexAction()
{
$this->view->config = array(
'responsive' => Kwf_Config::getValue('kwc.responsive')
);
$this->view->xtype = 'kwf.component.preview';
$this->view->initialUrl = null;
if (preg_match('#^https?://#', $this->view->initialUrl)) {
$this->view->initialUrl = $this->_getParam('url');
}
if (!$this->view->initialUrl) {
$this->view->initialUrl = 'http://'.$_SERVER['HTTP_HOST'].Kwf_Setup::getBaseUrl().'/';
}
}
public function redirectAction()
{
Kwf_Util_Redirect::redirect($this->_getParam('url'));
}
}
|
Move server initializing into dedicated function | const express = require('express');
const bodyParser = require('body-parser');
const log = require('./logger')(__filename);
const DEFAULT_HOSTNAME = 'localhost';
const DEFAULT_PORT = 3000;
module.exports = class Core {
constructor(port = DEFAULT_PORT, hostname = DEFAULT_HOSTNAME) {
this._tgApiKey = null;
this._webhookUrl = null;
this._port = port;
this._hostname = hostname;
this._server = startHttpServer(port, hostname);
}
subscribeWebhook(url, callback) {
if (!this._webhookUrl) {
this._webhookUrl = url;
this._server.post(url, (req, res) => {
callback(req);
});
}
}
};
function startHttpServer(port, hostname) {
const server = express();
// Add required middlewares
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
// Start!
server.listen(port, hostname, () => {
log.info(`HTTP-server started at ${this._hostname}:${this._port}`);
});
return server;
}
| const express = require('express');
const bodyParser = require('body-parser');
const log = require('./logger')(__filename);
const DEFAULT_ADDRESS = 'localhost';
const DEFAULT_PORT = 3000;
module.exports = class Core {
constructor(port = DEFAULT_PORT, address = DEFAULT_ADDRESS) {
this._tgApiKey = null;
this._webhookUrl = null;
this._port = port;
this._address = address;
this._server = express();
this._server.use(bodyParser.urlencoded({ extended: false }));
this._server.use(bodyParser.json());
// # Start the server
this._server.listen(this._port, this._address, () => {
log.info(`Mankov started at ${this._address}:${this._port}`);
});
}
subscribeWebhook(url, callback) {
if (!this._webhookUrl) {
this._webhookUrl = url;
this._server.post(url, (req, res) => {
callback(req);
});
}
}
};
|
Remove KC banner from repo | var $ = require('jquery');
window.$ = window.jQuery = $;
var setupHomepage = require('./homepage');
var setupAllArticles = require('./all-articles');
var setupAdmonish = require('./admonish');
// kick things off
$(document).ready(function(){
// FAQs toggle content
$("div.faq h4").nextUntil("h4, h3, hr, .legal-container").hide();
$("div.faq h4").click(function() {
$(this).nextUntil("h4, h3, hr, .legal-container").slideToggle("fast");
$(this).toggleClass("active", 1000);
});
// Tags toggle
$("#list-tags").click(function() {
$(".tags-list").toggle();
});
// setup the homepage stuff
if (window.location.pathname.match(/how-to\/$/)) {
setupHomepage();
}
if (window.location.pathname.match(/-all-articles\/$/)) {
setupAllArticles();
}
setupAdmonish();
});
| var $ = require('jquery');
window.$ = window.jQuery = $;
var setupHomepage = require('./homepage');
var setupAllArticles = require('./all-articles');
var setupAdmonish = require('./admonish');
// kick things off
$(document).ready(function(){
// FAQs toggle content
$("div.faq h4").nextUntil("h4, h3, hr, .legal-container").hide();
$("div.faq h4").click(function() {
$(this).nextUntil("h4, h3, hr, .legal-container").slideToggle("fast");
$(this).toggleClass("active", 1000);
});
// Tags toggle
$("#list-tags").click(function() {
$(".tags-list").toggle();
});
// setup the homepage stuff
if (window.location.pathname.match(/how-to\/$/)) {
setupHomepage();
}
if (window.location.pathname.match(/-all-articles\/$/)) {
setupAllArticles();
}
setupAdmonish();
// remove redesign link from KC
$(".banner-redesign-link").remove();
});
|
Update to reflect not having trailing slashes | """Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
def make_map():
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = False
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be resolved
map.connect('error/:action/:id', controller='error')
# CUSTOM ROUTES HERE
map.resource('restsample', 'restsamples')
map.connect('/:controller/:action')
map.connect('/:controller/:action/:id')
return map
| """Routes configuration
The more specific and detailed routes should be defined first so they
may take precedent over the more generic routes. For more information
refer to the routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
def make_map():
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = False
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the top, ensuring it can always be resolved
map.connect('error/:action/:id', controller='error')
# CUSTOM ROUTES HERE
map.resource('restsample', 'restsamples')
map.connect('/:controller/index', action='index')
map.connect('/:controller/:action/')
map.connect('/:controller/:action/:id')
return map
|
Add logging of request to stdout | package main
import (
"fmt"
"log"
"net/http"
"path/filepath"
"github.com/docopt/docopt.go"
)
func main() {
arguments, _ := docopt.Parse(usage(), nil, true, "0.1", false)
port := arguments["--port"].(string)
path, _ := filepath.Abs(arguments["<directory>"].(string))
start(path, port)
}
func usage() string {
return `Static Web Server
This tool serves static files in the given directory through http on localhost over the given port number (e.g 5000 by default)
Usage:
staticws <directory> [--port=N]
staticws -h | --help
staticws --version
Options:
-h --help Show this screen.
--version Show version.
--port=N Web server port number [default: 5000].`
}
func start(path, port string) {
log.Println("Serving files from", path)
log.Println("Listening on port", port)
http.Handle("/", http.FileServer(http.Dir(path)))
panic(http.ListenAndServe(fmt.Sprintf(":%v", port), Log(http.DefaultServeMux)))
}
func Log(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
| package main
import (
"fmt"
"log"
"net/http"
"path/filepath"
"github.com/docopt/docopt.go"
)
func main() {
arguments, _ := docopt.Parse(usage(), nil, true, "0.1", false)
port := arguments["--port"].(string)
path, _ := filepath.Abs(arguments["<directory>"].(string))
start(path, port)
}
func usage() string {
return `Static Web Server
This tool serves static files in the given directory through http on localhost over the given port number (e.g 5000 by default)
Usage:
staticws <directory> [--port=N]
staticws -h | --help
staticws --version
Options:
-h --help Show this screen.
--version Show version.
--port=N Web server port number [default: 5000].`
}
func start(path, port string) {
log.Println("Serving files from", path)
log.Println("Listening on port", port)
panic(http.ListenAndServe(fmt.Sprintf(":%v", port), http.FileServer(http.Dir(path))))
}
|
Add error handling for missing resources | <?php
use Ontic\NoFraud\Controllers\IController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
require_once __DIR__ . '/vendor/autoload.php';
$routes = new RouteCollection();
$route = new Route('/capabilities', ['controller' => 'Ontic\\NoFraud\\Controllers\\CapabilitiesController']);
$route->setMethods(['GET']);
$routes->add('get_capabilities', $route);
$route = new Route('/assessment', ['controller' => 'Ontic\\NoFraud\\Controllers\\AssesmentController']);
$route->setMethods(['POST']);
$routes->add('create_assessment', $route);
$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
try
{
$parameters = $matcher->match($request->getPathInfo());
$controllerClass = $parameters['controller'];
/** @var IController $controller */
$controller = new $controllerClass();
$response = $controller->defaultAction();
$response->send();
die;
}
catch (MethodNotAllowedException $ex)
{
header('', true, 405);
echo '405 Method Not Allowed';
die;
}
catch (ResourceNotFoundException $ex)
{
header('', true, 404);
echo '404 Resource Not Found';
die;
}
| <?php
use Ontic\NoFraud\Controllers\IController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
require_once __DIR__ . '/vendor/autoload.php';
$routes = new RouteCollection();
$route = new Route('/capabilities', ['controller' => 'Ontic\\NoFraud\\Controllers\\CapabilitiesController']);
$route->setMethods(['GET']);
$routes->add('get_capabilities', $route);
$route = new Route('/assessment', ['controller' => 'Ontic\\NoFraud\\Controllers\\AssesmentController']);
$route->setMethods(['POST']);
$routes->add('create_assessment', $route);
$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($request->getPathInfo());
$controllerClass = $parameters['controller'];
/** @var IController $controller */
$controller = new $controllerClass();
$response = $controller->defaultAction();
$response->send();
die;
|
Remove attributes already provided in base type | <?php
namespace Mapbender\DigitizerBundle\Element\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DigitizerAdminType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'application' => null
));
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array(
'element_class' => 'Mapbender\CoreBundle\Element\Map',
'application' => $options['application'],
))
->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array(
'required' => false,
))
;
}
}
| <?php
namespace Mapbender\DigitizerBundle\Element\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DigitizerAdminType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'application' => null
));
}
/**
* @inheritdoc
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array(
'element_class' => 'Mapbender\CoreBundle\Element\Map',
'application' => $options['application'],
))
->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array(
'required' => false,
'attr' => array(
'class' => 'code-yaml',
),
))
;
}
}
|
Reset cursor's styles after each write (Windows issue) | 'use strict'
const ansi = require('ansi')
const Jimp = require('jimp')
module.exports = function imageToConsole (photoPath, cols, callback) {
Jimp.read(photoPath, (error, image) => {
if (error) return callback(error)
const cursor = ansi(process.stdout)
const resizedImage = image.resize(cols, Jimp.AUTO)
const height = resizedImage.bitmap.height
const width = resizedImage.bitmap.width
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let hexColor = `${resizedImage.getPixelColor(x, y).toString(16).substr(0, 6)}`
if (hexColor.length !== 6) hexColor = '000000'
cursor
.hex(`#${hexColor}`)
.write('██')
.reset()
}
cursor.write('\n')
}
callback(null, true)
})
}
| 'use strict'
const ansi = require('ansi')
const Jimp = require('jimp')
module.exports = function imageToConsole (photoPath, cols, callback) {
Jimp.read(photoPath, (error, image) => {
if (error) return callback(error)
const cursor = ansi(process.stdout)
const resizedImage = image.resize(cols, Jimp.AUTO)
const height = resizedImage.bitmap.height
const width = resizedImage.bitmap.width
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let hexColor = `${resizedImage.getPixelColor(x, y).toString(16).substr(0, 6)}`
if (hexColor.length !== 6) hexColor = '000000'
cursor.hex(`#${hexColor}`).write('██').fg.reset()
}
cursor.write('\n')
}
callback(null, true)
})
}
|
Add and update tests for video renderer | import pytest
from mfr.core.provider import ProviderMetadata
from mfr.extensions.video import VideoRenderer
@pytest.fixture
def metadata():
return ProviderMetadata('test', '.mp4', 'text/plain', '1234',
'http://wb.osf.io/file/test.mp4?token=1234')
@pytest.fixture
def file_path():
return '/tmp/test.mp4'
@pytest.fixture
def url():
return 'http://osf.io/file/test.mp4'
@pytest.fixture
def assets_url():
return 'http://mfr.osf.io/assets'
@pytest.fixture
def export_url():
return 'http://mfr.osf.io/export?url=' + url()
@pytest.fixture
def renderer(metadata, file_path, url, assets_url, export_url):
return VideoRenderer(metadata, file_path, url, assets_url, export_url)
class TestVideoRenderer:
def test_render_video(self, renderer, url):
body = renderer.render()
assert '<video controls' in body
assert 'src="{}"'.format(metadata().download_url) in body
assert '<style>body{margin:0;padding:0;}</style>' in ''.join(body.split())
def test_render_video_file_required(self, renderer):
assert renderer.file_required is False
def test_render_video_cache_result(self, renderer):
assert renderer.cache_result is False
| import pytest
from mfr.core.provider import ProviderMetadata
from mfr.extensions.video import VideoRenderer
@pytest.fixture
def metadata():
return ProviderMetadata('test', '.mp4', 'text/plain', '1234', 'http://wb.osf.io/file/test.mp4?token=1234')
@pytest.fixture
def file_path():
return '/tmp/test.mp4'
@pytest.fixture
def url():
return 'http://osf.io/file/test.mp4'
@pytest.fixture
def assets_url():
return 'http://mfr.osf.io/assets'
@pytest.fixture
def export_url():
return 'http://mfr.osf.io/export?url=' + url()
@pytest.fixture
def renderer(metadata, file_path, url, assets_url, export_url):
return VideoRenderer(metadata, file_path, url, assets_url, export_url)
class TestVideoRenderer:
def test_render_video(self, renderer, url):
body = renderer.render()
assert '<video controls' in body
assert 'src="{}"'.format(metadata().download_url) in body
def test_render_video_file_required(self, renderer):
assert renderer.file_required is False
def test_render_video_cache_result(self, renderer):
assert renderer.cache_result is False
|
Use basename instead of os.path.split(...)[-1] | from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@authenticated
def get(self, filepath_id):
filepath_id = int(filepath_id)
# Check access to file
accessible_filepaths = get_accessible_filepath_ids(self.current_user)
if filepath_id not in accessible_filepaths:
raise QiitaPetAuthorizationError(
self.current_user, 'filepath id %d' % filepath_id)
relpath = filepath_id_to_rel_path(filepath_id)
fname = basename(relpath)
self.set_header('Content-Description', 'File Transfer')
self.set_header('Content-Type', 'application/octet-stream')
self.set_header('Content-Transfer-Encoding', 'binary')
self.set_header('Expires', '0')
self.set_header('X-Accel-Redirect', '/protected/' + relpath)
self.set_header('Content-Disposition',
'attachment; filename=%s' % fname)
self.finish()
| from tornado.web import authenticated
from os.path import split
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@authenticated
def get(self, filepath_id):
filepath_id = int(filepath_id)
# Check access to file
accessible_filepaths = get_accessible_filepath_ids(self.current_user)
if filepath_id not in accessible_filepaths:
raise QiitaPetAuthorizationError(
self.current_user, 'filepath id %d' % filepath_id)
relpath = filepath_id_to_rel_path(filepath_id)
fname = split(relpath)[-1]
self.set_header('Content-Description', 'File Transfer')
self.set_header('Content-Type', 'application/octet-stream')
self.set_header('Content-Transfer-Encoding', 'binary')
self.set_header('Expires', '0')
self.set_header('X-Accel-Redirect', '/protected/' + relpath)
self.set_header('Content-Disposition',
'attachment; filename=%s' % fname)
self.finish()
|
Set accepted arguments to 2 for wp filter | <?php
function jf_template_path() {
return Wrapper::$main_template;
}
function jf_template_base() {
return Wrapper::$base;
}
class Wrapper {
/**
* Stores the full path to the main template file
*/
static $main_template;
/**
* Stores the base name of the template file; e.g. 'page' for 'page.php' etc.
*/
static $base;
static function jf_wrap( $template ) {
self::$main_template = $template;
self::$base = substr( basename( self::$main_template ), 0, -4 );
if ( 'index' == self::$base )
self::$base = false;
$templates = array( 'wrapper.php' );
if ( self::$base )
array_unshift( $templates, sprintf( 'wrapper-%s.php', self::$base ) );
return locate_template( $templates );
}
}
add_filter( 'template_include', array( 'Wrapper', 'jf_wrap' ), 99 );
function relinquish_theme_home_page_url( $link, $post ) {
$post = get_post($post);
if ( 'page' == get_option( 'show_on_front' ) && $post->ID == get_option( 'page_on_front' ) && defined('RELINQUISH_FRONTEND') )
$link = RELINQUISH_FRONTEND;
return $link;
}
add_filter('page_link', 'relinquish_theme_home_page_url', 10, 2); | <?php
function jf_template_path() {
return Wrapper::$main_template;
}
function jf_template_base() {
return Wrapper::$base;
}
class Wrapper {
/**
* Stores the full path to the main template file
*/
static $main_template;
/**
* Stores the base name of the template file; e.g. 'page' for 'page.php' etc.
*/
static $base;
static function jf_wrap( $template ) {
self::$main_template = $template;
self::$base = substr( basename( self::$main_template ), 0, -4 );
if ( 'index' == self::$base )
self::$base = false;
$templates = array( 'wrapper.php' );
if ( self::$base )
array_unshift( $templates, sprintf( 'wrapper-%s.php', self::$base ) );
return locate_template( $templates );
}
}
add_filter( 'template_include', array( 'Wrapper', 'jf_wrap' ), 99 );
function relinquish_theme_home_page_url( $link, $post ) {
$post = get_post($post);
if ( 'page' == get_option( 'show_on_front' ) && $post->ID == get_option( 'page_on_front' ) && defined('RELINQUISH_FRONTEND') )
$link = RELINQUISH_FRONTEND;
return $link;
}
add_filter('page_link', 'relinquish_theme_home_page_url'); |
Fix a bug that caused tests to raise a DatabaseError | from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'sqlite3',
'NAME': ':memory:'
}
},
INSTALLED_APPS = [
'fandjango',
'south',
'tests.app'
],
ROOT_URLCONF = 'tests.app.urls',
MIDDLEWARE_CLASSES = [
'fandjango.middleware.FacebookMiddleware'
],
FACEBOOK_APPLICATION_ID = 181259711925270,
FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b',
FACEBOOK_APPLICATION_URL = 'http://apps.facebook.com/fandjango-test'
)
call_command('syncdb')
call_command('migrate')
| from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'sqlite3',
'NAME': ':memory:'
}
},
INSTALLED_APPS = [
'fandjango',
'south',
'tests.app'
],
ROOT_URLCONF = 'tests.app.urls',
MIDDLEWARE_CLASSES = [
'fandjango.middleware.FacebookMiddleware'
],
FACEBOOK_APPLICATION_ID = 181259711925270,
FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b',
FACEBOOK_APPLICATION_URL = 'http://apps.facebook.com/fandjango-test'
)
call_command('syncdb')
|
Refactor get_default_finder to work without importing finders | from django.utils.module_loading import import_string
from django.conf import settings
MOVED_FINDERS = {
'wagtail.wagtailembeds.embeds.embedly': 'wagtail.wagtailembeds.finders.embedly.embedly',
'wagtail.wagtailembeds.embeds.oembed': 'wagtail.wagtailembeds.finders.oembed.oembed',
}
def get_default_finder():
# Check if the user has set the embed finder manually
if hasattr(settings, 'WAGTAILEMBEDS_EMBED_FINDER'):
finder_name = settings.WAGTAILEMBEDS_EMBED_FINDER
if finder_name in MOVED_FINDERS:
finder_name = MOVED_FINDERS[finder_name]
elif hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
# Default to Embedly as an embedly key is set
finder_name = 'wagtail.wagtailembeds.finders.embedly.embedly'
else:
# Default to oembed
finder_name = 'wagtail.wagtailembeds.finders.oembed.oembed'
return import_string(finder_name)
| from django.utils.module_loading import import_string
from django.conf import settings
from wagtail.wagtailembeds.finders.oembed import oembed
from wagtail.wagtailembeds.finders.embedly import embedly
MOVED_FINDERS = {
'wagtail.wagtailembeds.embeds.embedly': 'wagtail.wagtailembeds.finders.embedly.embedly',
'wagtail.wagtailembeds.embeds.oembed': 'wagtail.wagtailembeds.finders.oembed.oembed',
}
def get_default_finder():
# Check if the user has set the embed finder manually
if hasattr(settings, 'WAGTAILEMBEDS_EMBED_FINDER'):
finder_name = settings.WAGTAILEMBEDS_EMBED_FINDER
if finder_name in MOVED_FINDERS:
finder_name = MOVED_FINDERS[finder_name]
return import_string(finder_name)
# Use embedly if the embedly key is set
if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
return embedly
# Fall back to oembed
return oembed
|
Fix config PATH for windows batch file | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
| import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
|
Call completion callback in test:run | var gulp = require('gulp');
var tsc = require('gulp-tsc');
var tape = require('gulp-tape');
var tapSpec = require('tap-spec');
var del = require('del');
gulp.task("test:clean", function(done) {
del(['build-test/**']).then(function(paths) {
console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n=====");
done();
});
});
gulp.task("test:build", function (done) {
gulp.src(['test/**/*.ts'])
.pipe(tsc())
.pipe(gulp.dest('build-test/'))
.on('end', done);
});
gulp.task("test:run", function (done) {
gulp.src('build-test/test/**/*.test.js')
.pipe(tape({
reporter: tapSpec()
}))
.on('end', done);;
});
gulp.task("test", ["test:build"], function (done) {
gulp.src('build-test/test/**/*.test.js')
.pipe(tape({
reporter: tapSpec()
}));
});
| var gulp = require('gulp');
var tsc = require('gulp-tsc');
var tape = require('gulp-tape');
var tapSpec = require('tap-spec');
var del = require('del');
gulp.task("test:clean", function(done) {
del(['build-test/**']).then(function(paths) {
console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n=====");
done();
});
});
gulp.task("test:build", function (done) {
gulp.src(['test/**/*.ts'])
.pipe(tsc())
.pipe(gulp.dest('build-test/'))
.on('end', done);
});
gulp.task("test:run", function (done) {
gulp.src('build-test/test/**/*.test.js')
.pipe(tape({
reporter: tapSpec()
}));
});
gulp.task("test", ["test:build"], function (done) {
gulp.src('build-test/test/**/*.test.js')
.pipe(tape({
reporter: tapSpec()
}));
});
|
Use correct optional paramater JSDoc syntax | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule forEachAccumulated
* @flow
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
* @param {function} cb Callback invoked with each element or a collection.
* @param {?} [scope] Scope used as `this` in a callback.
*/
function forEachAccumulated<T>(
arr: ?(T | Array<T>),
cb: ((elem: T) => void),
scope: ?any,
) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
}
module.exports = forEachAccumulated;
| /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule forEachAccumulated
* @flow
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
* @param {function} cb Callback invoked with each element or a collection.
* @param {?*} scope Scope used as `this` in a callback.
*/
function forEachAccumulated<T>(
arr: ?(T | Array<T>),
cb: ((elem: T) => void),
scope: ?any,
) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
}
module.exports = forEachAccumulated;
|
Add Python 3 requests install | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install requests'):
print 'Error installing python3 requests package. Exiting...'
quit()
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
| #!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
|
Declare the trampoline variable before using it.
This makes the trampoline "module" work in strict mode which you are now using everywhere. | Elm.Native.Trampoline = {};
Elm.Native.Trampoline.make = function(elm) {
elm.Native = elm.Native || {};
elm.Native.Trampoline = elm.Native.Trampoline || {};
if (elm.Native.Trampoline.values) return elm.Native.Trampoline.values;
// trampoline : Trampoline a -> a
var trampoline;
trampoline = function(t) {
var tramp = t;
while(true) {
switch(tramp.ctor) {
case "Done":
return tramp._0;
case "Continue":
tramp = tramp._0({ctor: "_Tuple0"});
continue;
}
}
}
return elm.Native.Trampoline.values = { trampoline: trampoline };
};
| Elm.Native.Trampoline = {};
Elm.Native.Trampoline.make = function(elm) {
elm.Native = elm.Native || {};
elm.Native.Trampoline = elm.Native.Trampoline || {};
if (elm.Native.Trampoline.values) return elm.Native.Trampoline.values;
// trampoline : Trampoline a -> a
trampoline = function(t) {
var tramp = t;
while(true) {
switch(tramp.ctor) {
case "Done":
return tramp._0;
case "Continue":
tramp = tramp._0({ctor: "_Tuple0"});
continue;
}
}
}
return elm.Native.Trampoline.values = { trampoline: trampoline };
};
|
Add color to feedback msg | "use strict"
module.exports = (function(obj) {
var cli = require("cli"),
json = require("jsonfile");
function returnUnicArrays(arr) {
try {
var filteredArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
} catch (e) {
showError(e);
}
return filteredArray;
}
function writeJson(filePath, obj) {
json.writeFileSync(filePath, obj, {spaces: 2}, function (err) {
cli.error(err);
})
cli.ok("File created in: \x1b[92m" + filePath);
}
function showError(msg) {
cli.err(msg);
process.exit(1);
}
return {
returnUnicArrays: returnUnicArrays,
writeJson: writeJson,
showError: showError
}
})();
| "use strict"
module.exports = (function(obj) {
var cli = require("cli"),
json = require("jsonfile");
function returnUnicArrays(arr) {
try {
var filteredArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
} catch (e) {
showError(e);
}
return filteredArray;
}
function writeJson(filePath, obj) {
json.writeFileSync(filePath, obj, {spaces: 2}, function (err) {
cli.error(err);
})
cli.ok("File created in: " + filePath);
}
function showError(msg) {
cli.err(msg);
process.exit(1);
}
return {
returnUnicArrays: returnUnicArrays,
writeJson: writeJson,
showError: showError
}
})();
|
Update user repository to match removal of user approval logic. | /*
* Copyright 2014 Open mHealth
*
* 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.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.User;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of user accounts.
*
* @author Emerson Farrugia
*/
public interface UserRepository extends Repository<User, String> {
/**
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
*/
Optional<User> findOne(String username);
/**
* @see org.springframework.data.repository.CrudRepository#save(Object)
*/
User save(User user);
}
| /*
* Copyright 2014 Open mHealth
*
* 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.openmhealth.dsu.repository;
import org.openmhealth.dsu.domain.User;
import org.springframework.data.repository.Repository;
import java.util.Optional;
/**
* A repository of user accounts.
*
* @author Emerson Farrugia
*/
public interface UserRepository extends Repository<User, String> {
/**
* @see org.springframework.data.repository.CrudRepository#findOne(java.io.Serializable)
*/
Optional<User> findOne(String username);
Optional<User> findByRegistrationKey(String registrationKey);
/**
* @see org.springframework.data.repository.CrudRepository#save(Object)
*/
void save(User user);
}
|
Make it easy to use mocked/stubbed connections for testing | var express = require('express');
var Connection = require('./lib/backend/connection').Connection;
var restAdaptor = require('./lib/frontend/rest-adaptor');
var socketIoAdaptor = require('./lib/frontend/socket.io-adaptor');
var dashboardHandler = require('./lib/frontend/dashboard-handler');
express.application.kotoumi = function(params) {
params = params || {};
params.connection = params.connection || new Connection(params);
var connection = params.connection;
params.prefix = params.prefix || '';
params.prefix = params.prefix.replace(/\/$/, '');
restAdaptor.register(this, params);
if (params.server) {
socketIoAdaptor.register(this, params.server, params);
params.server.on('close', function() {
// The connection can be mocked/stubbed. We don't need to close
// such a fake connection.
if (typeof connection.close == 'function')
connection.close();
});
}
dashboardHandler.register(this, params);
this.connection = connection;
this.emitMessage = connection.emitMessage.bind(connection); // shorthand
}
| var express = require('express');
var Connection = require('./lib/backend/connection').Connection;
var restAdaptor = require('./lib/frontend/rest-adaptor');
var socketIoAdaptor = require('./lib/frontend/socket.io-adaptor');
var dashboardHandler = require('./lib/frontend/dashboard-handler');
express.application.kotoumi = function(params) {
params = params || {};
params.connection = params.connection || new Connection(params);
var connection = params.connection;
params.prefix = params.prefix || '';
params.prefix = params.prefix.replace(/\/$/, '');
restAdaptor.register(this, params);
if (params.server) {
socketIoAdaptor.register(this, params.server, params);
params.server.on('close', function() {
connection.close();
});
}
dashboardHandler.register(this, params);
this.connection = connection;
this.emitMessage = connection.emitMessage.bind(connection); // shorthand
}
|
Fix error responses to don't have a need of a view engine | var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var sites = require('./routes/sites');
var articles = require('./routes/articles');
var writers = require('./routes/writers');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/sites', sites);
app.use('/articles', articles);
app.use('/writers', writers);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.send({
message: err.message,
error: {}
});
});
module.exports = app;
| var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var sites = require('./routes/sites');
var articles = require('./routes/articles');
var writers = require('./routes/writers');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/sites', sites);
app.use('/articles', articles);
app.use('/writers', writers);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
Rename variable to avoid using reserved word `string` | 'use strict'
// Chess board
// Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.
// Passing this string to console.log should show something like this:
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.
const size = 8; // this can be changed to any size grid
let outputString = '';
for (let i = 0; i < size; i++) {
for (let j = 0; j <= size; j ++) {
if (j === size) {
outputString += '\n';
break;
}
let character = i + j; // toggles the output character on even/odd lines
if (character % 2 === 0)
outputString += ' ';
else
outputString += '#';
}
}
console.log(outputString); | 'use strict'
// Chess board
// Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.
// Passing this string to console.log should show something like this:
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// # # # #
// When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.
const size = 8; // this can be changed to any size grid
let string = '';
for (let i = 0; i < size; i++) {
for (let j = 0; j <= size; j ++) {
if (j === size) {
string += '\n';
break;
}
let character = i + j; // toggles the output character on even/odd lines
if (character % 2 === 0)
string += ' ';
else
string += '#';
}
}
console.log(string); |
Enable settings to be read without login.
- otherwise name of cloudconductor server could not be shown before login | package de.cinovo.cloudconductor.api.interfaces;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import de.cinovo.cloudconductor.api.IRestPath;
import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.model.Settings;
/**
* Copyright 2017 Cinovo AG<br>
* <br>
*
* @author psigloch
*/
@Path(IRestPath.SETTINGS)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ISettings {
/**
* @return set of service objects
*/
@GET
Settings get();
/**
* @param settings the settings to save
*/
@PUT
@RolesAllowed({"EDIT_CONFIGURATIONS"})
void save(Settings settings);
}
| package de.cinovo.cloudconductor.api.interfaces;
import de.cinovo.cloudconductor.api.IRestPath;
import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.model.Settings;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* Copyright 2017 Cinovo AG<br>
* <br>
*
* @author psigloch
*/
@Path(IRestPath.SETTINGS)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ISettings {
/**
* @return set of service objects
*/
@GET
@RolesAllowed({"VIEW_CONFIGURATIONS","EDIT_CONFIGURATIONS"})
Settings get();
/**
* @param settings the settings to save
*/
@PUT
@RolesAllowed({"EDIT_CONFIGURATIONS"})
void save(Settings settings);
}
|
Add a download url for the tarball from github | from os import path
from setuptools import setup
README = path.join(path.dirname(path.abspath(__file__)), "README.rst")
setup(
name="minecart",
version="0.3.0",
description=("Simple, Pythonic extraction of images, text, and shapes "
"from PDFs"),
long_description=open(README).read(),
author="Felipe Ochoa",
author_email="find me through Github",
url="https://github.com/felipeochoa/minecart",
download_url='https://github.com/felipeochoa/minecart/tarball/0.3.0',
license="MIT",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3 :: Only',
'License :: OSI Approved :: MIT License',
],
keywords='pdf pdfminer extract mining images',
install_requires=['pdfminer3k', 'six'],
extras_require={
'PIL': ['Pillow'],
},
packages=["minecart"],
)
| from os import path
from setuptools import setup
README = path.join(path.dirname(path.abspath(__file__)), "README.rst")
setup(
name="minecart",
version="0.3.0",
description=("Simple, Pythonic extraction of images, text, and shapes "
"from PDFs"),
long_description=open(README).read(),
author="Felipe Ochoa",
author_email="find me through Github",
url="https://github.com/felipeochoa/minecart",
license="MIT",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3 :: Only',
'License :: OSI Approved :: MIT License',
],
keywords='pdf pdfminer extract mining images',
install_requires=['pdfminer3k', 'six'],
extras_require={
'PIL': ['Pillow'],
},
packages=["minecart"],
)
|
Remove the Infrastructure panel group
Remove the Infrastructure panel group, and place the panels
directly under the Infrastructure dashboard.
Change-Id: I321f9a84dd885732438ad58b6c62c480c9c10e37 | #
# 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 django.utils.translation import ugettext_lazy as _
import horizon
class Infrastructure(horizon.Dashboard):
name = _("Infrastructure")
slug = "infrastructure"
panels = (
'overview',
'parameters',
'roles',
'nodes',
'flavors',
'images',
'history',
)
default_panel = 'overview'
permissions = ('openstack.roles.admin',)
horizon.register(Infrastructure)
| #
# 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 django.utils.translation import ugettext_lazy as _
import horizon
class BasePanels(horizon.PanelGroup):
slug = "infrastructure"
name = _("Infrastructure")
panels = (
'overview',
'parameters',
'roles',
'nodes',
'flavors',
'images',
'history',
)
class Infrastructure(horizon.Dashboard):
name = _("Infrastructure")
slug = "infrastructure"
panels = (
BasePanels,
)
default_panel = 'overview'
permissions = ('openstack.roles.admin',)
horizon.register(Infrastructure)
|
Unify access in Pythonic built ins | class ThingObjectBase(object):
def __getitem__(self, item):
return getattr(self, item.value)
def __contains__(self, item):
return hasattr(self, item.value)
class ThingObjectOutput(ThingObjectBase):
INTERNAL_NAME = "Output"
def __init__(self, heap):
self.data = []
self.heap = heap
def write(self, *args):
self.data.append(' '.join(str(x) for x in args))
class ThingObjectInput(ThingObjectBase):
INTERNAL_NAME = "Input"
def __init__(self, heap):
self.data = []
self.heap = heap
def get_line(self, line=None):
if line is not None:
self.heap['Output'].write(line)
line = input()
self.data.append(line)
return line
BUILTINS = ThingObjectOutput, ThingObjectInput | class ThingObjectBase(object):
def __getitem__(self, item):
return getattr(self, item)
def __contains__(self, item):
return hasattr(self, item)
class ThingObjectOutput(ThingObjectBase):
def __init__(self):
self.data = []
def write(self, *args):
self.data.append(' '.join(str(x) for x in args))
class ThingObjectInput(ThingObjectBase):
def __init__(self, heap):
self.data = []
self.heap = heap
def get_line(self, line=None):
if line is not None:
self.heap['Output'].write(line)
line = input()
self.data.append(line)
return line
|
Add more logging test stubs | """A module containing tests for the library implementation of accessing utilities."""
from lxml import etree
import iati.core.resources
import iati.core.utilities
class TestUtilities(object):
"""A container for tests relating to utilities"""
def test_convert_to_schema(self):
"""Check that an etree can be converted to a schema."""
path = iati.core.resources.path_schema('iati-activities-schema')
tree = iati.core.resources.load_as_tree(path)
if not tree:
assert False
schema = iati.core.utilities.convert_to_schema(tree)
assert isinstance(schema, etree.XMLSchema)
def test_log(self):
pass
def test_log_error(self):
pass
def test_log_exception(self):
pass
def test_log_warning(self):
pass
| """A module containing tests for the library implementation of accessing utilities."""
from lxml import etree
import iati.core.resources
import iati.core.utilities
class TestUtilities(object):
"""A container for tests relating to utilities"""
def test_convert_to_schema(self):
"""Check that an etree can be converted to a schema."""
path = iati.core.resources.path_schema('iati-activities-schema')
tree = iati.core.resources.load_as_tree(path)
if not tree:
assert False
schema = iati.core.utilities.convert_to_schema(tree)
assert isinstance(schema, etree.XMLSchema)
def test_log(self):
pass
def test_log_error(self):
pass
|
Add junit ant task support | /**
* Copyright (c) 2010 IBM Corporation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*
* $Id$
*/
package org.openhealthtools.mdht.uml.hl7.datatypes.operations;
import junit.framework.JUnit4TestAdapter;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* This class represents a suite of Junit 4 test cases for HL7 Datatypes.
*/
@RunWith(Suite.class)
@Suite.SuiteClasses( { ADOperationsTest.class, BNOperationsTest.class,
EDOperationsTest.class, ENOperationsTest.class, ONOperationsTest.class,
PNOperationsTest.class, TNOperationsTest.class })
public class ALLDatatypeOperationsTests {
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(ALLDatatypeOperationsTests.class);
}
// Nothing
} // ALLDatatypeOperationsTests | /**
* Copyright (c) 2010 IBM Corporation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*
* $Id$
*/
package org.openhealthtools.mdht.uml.hl7.datatypes.operations;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* This class represents a suite of Junit 4 test cases for HL7 Datatypes.
*/
@RunWith(Suite.class)
@Suite.SuiteClasses( { ADOperationsTest.class, BNOperationsTest.class,
EDOperationsTest.class, ENOperationsTest.class, ONOperationsTest.class,
PNOperationsTest.class, TNOperationsTest.class })
public class ALLDatatypeOperationsTests {
// Nothing
} // ALLDatatypeOperationsTests |
Change to_user to CharField for message model | from __future__ import unicode_literals
from django.db import models
class Activity(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
detail = models.TextField(editable=False)
to_user = models.ForeignKey('employees.Employee',
related_name='%(class)s_to',
blank=True, null=True)
from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from')
class Meta:
ordering = ['-datetime']
verbose_name_plural = 'activities'
class Message(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
message = models.TextField()
from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from')
to_user = models.CharField(max_length=250)
class Meta:
ordering = ['-datetime']
verbose_name_plural = 'messages'
| from __future__ import unicode_literals
from django.db import models
class Activity(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
detail = models.TextField(editable=False)
to_user = models.ForeignKey('employees.Employee',
related_name='%(class)s_to',
blank=True, null=True)
from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from')
class Meta:
ordering = ['-datetime']
verbose_name_plural = 'activities'
class Message(models.Model):
datetime = models.DateTimeField(auto_now_add=True)
message = models.TextField()
from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from')
to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to')
class Meta:
ordering = ['-datetime']
verbose_name_plural = 'messages'
|
Use new version of Schemer and make the version float | import setuptools
setuptools.setup(
name="Mongothon",
version="0.7.17",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
license="BSD",
keywords="mongo mongodb database pymongo odm validation",
url="http://github.com/gamechanger/mongothon",
packages=["mongothon"],
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer>=0.2.0, <0.3.0'],
tests_require=['mock', 'nose']
)
| import setuptools
setuptools.setup(
name="Mongothon",
version="0.7.16",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
license="BSD",
keywords="mongo mongodb database pymongo odm validation",
url="http://github.com/gamechanger/mongothon",
packages=["mongothon"],
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer==0.2.4'],
tests_require=['mock', 'nose']
)
|
Test calling settings button state | import { getWrapper } from '../shared';
import NavigationBar from '../../src/components/NavigationBar';
import SettingsPanel from '../../src/components/SettingsPanel';
import CallingSettings from '../../src/components/CallingSettingsPanel';
import LinkLine from '../../src/components/LinkLine';
import Button from '../../src/components/Button';
let wrapper = null;
let panel = null;
let callingSettings = null;
beforeEach(async () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 32000;
wrapper = await getWrapper();
const navigationBar = wrapper.find(NavigationBar).first();
await navigationBar.props().goTo('/settings');
panel = wrapper.find(SettingsPanel).first();
const callingLinkLine = panel.find(LinkLine).at(0);
await callingLinkLine.props().onClick();
callingSettings = wrapper.find(CallingSettings).first();
});
describe('calling settings', () => {
test('initial state', async () => {
expect(callingSettings.find('div.label').first().props().children).toEqual('Calling');
});
test('button state', async () => {
const saveButton = callingSettings.find(Button).first();
expect(saveButton.props().disabled).toEqual(true);
const items = callingSettings.find('.dropdownItem');
const lastItem = items.at(items.length - 1);
await lastItem.simulate('click');
expect(saveButton.props().disabled).toEqual(false);
});
});
| import { getWrapper } from '../shared';
import NavigationBar from '../../src/components/NavigationBar';
import SettingsPanel from '../../src/components/SettingsPanel';
import CallingSettings from '../../src/components/CallingSettingsPanel';
import LinkLine from '../../src/components/LinkLine';
import Button from '../../src/components/Button';
let wrapper = null;
let panel = null;
let callingSettings = null;
beforeEach(async () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 32000;
wrapper = await getWrapper();
const navigationBar = wrapper.find(NavigationBar).first();
await navigationBar.props().goTo('/settings');
panel = wrapper.find(SettingsPanel).first();
const callingLinkLine = panel.find(LinkLine).at(0);
await callingLinkLine.props().onClick();
callingSettings = wrapper.find(CallingSettings).first();
});
describe('calling settings', () => {
test('initial state', async () => {
expect(callingSettings.find('div.label').first().props().children).toEqual('Calling');
});
test('button state', () => {
const saveButton = callingSettings.find(Button).first();
expect(saveButton.props().disabled).toEqual(true);
});
});
|
Replace move by copy then delete | package dynamo.backlog.tasks.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import dynamo.manager.DownloadableManager;
public class MoveFileTaskExecutor extends FileOperationTaskExecutor<MoveFileTask> {
private Path source;
private Path destination;
public MoveFileTaskExecutor(MoveFileTask item) {
super(item);
this.source = item.getSource();
this.destination = item.getDestination();
}
@Override
public void execute() throws IOException {
if (!Files.exists(source)) {
throw new IOException( String.format("Source file %s does not exist", source.toAbsolutePath().toString() ));
}
if (Files.isWritable(source.getParent()) && !source.toAbsolutePath().equals( destination.toAbsolutePath() )) {
Files.createDirectories( destination.getParent() );
Files.copy( source, destination, StandardCopyOption.REPLACE_EXISTING);
Files.delete( source );
DownloadableManager.getInstance().addFile( task.getDownloadable(), destination );
}
boolean parentFolderEmpty = FileUtils.isDirEmpty( source.getParent() );
if (parentFolderEmpty) {
Files.delete( source.getParent() );
}
}
@Override
public boolean isFinished() {
if (!Files.exists( source )) {
return true;
}
return Files.exists( destination );
}
}
| package dynamo.backlog.tasks.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import dynamo.manager.DownloadableManager;
public class MoveFileTaskExecutor extends FileOperationTaskExecutor<MoveFileTask> {
private Path source;
private Path destination;
public MoveFileTaskExecutor(MoveFileTask item) {
super(item);
this.source = item.getSource();
this.destination = item.getDestination();
}
@Override
public void execute() throws IOException {
if (!Files.exists(source)) {
throw new IOException( String.format("Source file %s does not exist", source.toAbsolutePath().toString() ));
}
if (Files.isWritable(source.getParent()) && !source.toAbsolutePath().equals( destination.toAbsolutePath() )) {
Files.createDirectories( destination.getParent() );
Files.move( source, destination, StandardCopyOption.REPLACE_EXISTING);
DownloadableManager.getInstance().addFile( task.getDownloadable(), destination );
}
boolean parentFolderEmpty = FileUtils.isDirEmpty( source.getParent() );
if (parentFolderEmpty) {
Files.delete( source.getParent() );
}
}
@Override
public boolean isFinished() {
if (!Files.exists( source )) {
return true;
}
return Files.exists( destination );
}
}
|
Fix sample frontend event order | import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import RawViewLink from '../RawView/RawViewLink'
import Event from './Event'
import './EventLog.css'
const propTypes = {
events: PropTypes.arrayOf(PropTypes.object).isRequired
}
function EventLog ({ events }) {
const by = (prop) => (a, b) => (a[ prop ] > b[ prop ] ? 1 : -1)
const sortedEvents = [].concat(events).sort(by('timestamp')).reverse()
return (
<section className='EventLog'>
<h3>Recent events</h3>
<RawViewLink className='EventLog-raw' contentTitle='GET /api/events' rawContent={sortedEvents} />
<ul className='EventLogList'>
{sortedEvents.map((event, index) => <Event key={index} event={event} />)}
</ul>
</section>
)
}
EventLog.propTypes = propTypes
function mapStateToProps (state) {
return {
events: state.events
}
}
export default connect(mapStateToProps)(EventLog)
| import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import RawViewLink from '../RawView/RawViewLink'
import Event from './Event'
import './EventLog.css'
const propTypes = {
events: PropTypes.arrayOf(PropTypes.object).isRequired
}
function EventLog ({ events }) {
return (
<section className='EventLog'>
<h3>Recent events</h3>
<RawViewLink className='EventLog-raw' contentTitle='GET /api/events' rawContent={events} />
<ul className='EventLogList'>
{events.map((event, index) => <Event key={index} event={event} />)}
</ul>
</section>
)
}
EventLog.propTypes = propTypes
function mapStateToProps (state) {
return {
events: state.events
}
}
export default connect(mapStateToProps)(EventLog)
|
locking: Use the .class as the lock | package info.evanchik.maven.project;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.maven.project.DefaultProjectDependenciesResolver;
import org.apache.maven.project.DependencyResolutionException;
import org.apache.maven.project.DependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.codehaus.plexus.component.annotations.Component;
/**
* @author Stephen Evanchik
*/
@Component( role = ProjectDependenciesResolver.class )
public class SynchronizedProjectDependenciesResolver extends DefaultProjectDependenciesResolver
{
public DependencyResolutionResult resolve( DependencyResolutionRequest request )
throws DependencyResolutionException
{
synchronized ( SynchronizedProjectDependenciesResolver.class )
{
return super.resolve( request );
}
}
}
| package info.evanchik.maven.project;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.maven.project.DefaultProjectDependenciesResolver;
import org.apache.maven.project.DependencyResolutionException;
import org.apache.maven.project.DependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.codehaus.plexus.component.annotations.Component;
/**
* @author Stephen Evanchik
*/
@Component( role = ProjectDependenciesResolver.class )
public class SynchronizedProjectDependenciesResolver extends DefaultProjectDependenciesResolver
{
private Object lock = new Object();
public DependencyResolutionResult resolve( DependencyResolutionRequest request )
throws DependencyResolutionException
{
synchronized (lock)
{
return super.resolve( request );
}
}
}
|
Remove trailing slash (google charts don't like it) | # pipeurlbuilder.py
#
import urllib
from pipe2py import util
def pipe_urlbuilder(context, _INPUT, conf, **kwargs):
"""This source builds a url and yields it forever.
Keyword arguments:
context -- pipeline context
_INPUT -- not used
conf:
BASE -- base
PATH -- path elements
PARAM -- query parameters
Yields (_OUTPUT):
url
"""
for item in _INPUT:
#note: we could cache get_value results if item==True
url = util.get_value(conf['BASE'], item, **kwargs)
if not url.endswith('/'):
url += '/'
path = util.get_value(conf['PATH'], item, **kwargs)
if not isinstance(path, list):
path = [path]
url += "/".join(path)
url = url.rstrip("/")
params = dict([(util.get_value(p['key'], item, **kwargs), util.get_value(p['value'], item, **kwargs)) for p in conf['PARAM']])
if params:
url += "?" + urllib.urlencode(params)
yield url
| # pipeurlbuilder.py
#
import urllib
from pipe2py import util
def pipe_urlbuilder(context, _INPUT, conf, **kwargs):
"""This source builds a url and yields it forever.
Keyword arguments:
context -- pipeline context
_INPUT -- not used
conf:
BASE -- base
PATH -- path elements
PARAM -- query parameters
Yields (_OUTPUT):
url
"""
for item in _INPUT:
#note: we could cache get_value results if item==True
url = util.get_value(conf['BASE'], item, **kwargs)
if not url.endswith('/'):
url += '/'
path = util.get_value(conf['PATH'], item, **kwargs)
if not isinstance(path, list):
path = [path]
url += "/".join(path)
params = dict([(util.get_value(p['key'], item, **kwargs), util.get_value(p['value'], item, **kwargs)) for p in conf['PARAM']])
if params:
url += "?" + urllib.urlencode(params)
yield url
|
Add possibility to use custom Interceptors | package org.knowm.xchange.interceptor;
import com.google.common.base.Suppliers;
import java.util.Collection;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import si.mazi.rescu.Interceptor;
public class InterceptorProvider {
private static final Supplier<Collection<Interceptor>> INTERCEPTORS_SUPPLIER =
Suppliers.memoize(
() -> {
final ServiceLoader<Interceptor> serviceLoader = ServiceLoader.load(Interceptor.class);
return StreamSupport.stream(serviceLoader.spliterator(), false)
.collect(Collectors.toSet());
});
public static Collection<Interceptor> provide() {
return INTERCEPTORS_SUPPLIER.get();
}
} | package org.knowm.xchange.interceptor;
import com.google.common.base.Suppliers;
import java.util.Collection;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import si.mazi.rescu.Interceptor;
public class InterceptorProvider {
private static final Supplier<Collection<Interceptor>> INTERCEPTORS_SUPPLIER =
Suppliers.memoize(
() -> {
final ServiceLoader<Interceptor> serviceLoader = ServiceLoader.load(Interceptor.class);
return StreamSupport.stream(serviceLoader.spliterator(), false)
.collect(Collectors.toSet());
});
public static Collection<Interceptor> provide() {
return INTERCEPTORS_SUPPLIER.get();
}
}
|
Add lazy loading filter in model | /*
* Copyright 2018 Matthias Kesler
* Copyright 2018 New Vector Ltd
*
* 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.matrix.androidsdk.rest.model.filter;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Represents "RoomEventFilter" as mentioned in the SPEC
* https://matrix.org/docs/spec/client_server/r0.3.0.html#post-matrix-client-r0-user-userid-filter
*/
public class RoomEventFilter {
public Integer limit;
@SerializedName("not_senders")
public List<String> notSenders;
@SerializedName("not_types")
public List<String> notTypes;
public List<String> senders;
public List<String> types;
public List<String> rooms;
@SerializedName("not_rooms")
public List<String> notRooms;
@SerializedName("contains_url")
public Boolean containsUrl;
@SerializedName("lazy_load_members")
public Boolean lazyLoadMembers;
}
| /*
* Copyright 2018 Matthias Kesler
* Copyright 2018 New Vector Ltd
*
* 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.matrix.androidsdk.rest.model.filter;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Represents "RoomEventFilter" as mentioned in the SPEC
* https://matrix.org/docs/spec/client_server/r0.3.0.html#post-matrix-client-r0-user-userid-filter
*/
public class RoomEventFilter {
public Integer limit;
@SerializedName("not_senders")
public List<String> notSenders;
@SerializedName("not_types")
public List<String> notTypes;
public List<String> senders;
public List<String> types;
public List<String> rooms;
@SerializedName("not_rooms")
public List<String> notRooms;
@SerializedName("contains_url")
public Boolean containsUrl;
}
|
Add a missing timeout decoration
Signed-off-by: David Lee <15c338f3b79a63a0d5423e9c6562cd312918fe74@gmail.com> | package org.zstack.header.storage.primary;
import org.zstack.header.core.ApiTimeout;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.storage.snapshot.VolumeSnapshotStruct;
import org.zstack.header.volume.APICreateVolumeSnapshotMsg;
/**
*/
@ApiTimeout(apiClasses = {APICreateVolumeSnapshotMsg.class})
public class TakeSnapshotMsg extends NeedReplyMessage implements PrimaryStorageMessage {
private String primaryStorageUuid;
private VolumeSnapshotStruct struct;
@Override
public String getPrimaryStorageUuid() {
return primaryStorageUuid;
}
public void setPrimaryStorageUuid(String primaryStorageUuid) {
this.primaryStorageUuid = primaryStorageUuid;
}
public VolumeSnapshotStruct getStruct() {
return struct;
}
public void setStruct(VolumeSnapshotStruct struct) {
this.struct = struct;
}
}
| package org.zstack.header.storage.primary;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.storage.snapshot.VolumeSnapshotStruct;
/**
*/
public class TakeSnapshotMsg extends NeedReplyMessage implements PrimaryStorageMessage {
private String primaryStorageUuid;
private VolumeSnapshotStruct struct;
@Override
public String getPrimaryStorageUuid() {
return primaryStorageUuid;
}
public void setPrimaryStorageUuid(String primaryStorageUuid) {
this.primaryStorageUuid = primaryStorageUuid;
}
public VolumeSnapshotStruct getStruct() {
return struct;
}
public void setStruct(VolumeSnapshotStruct struct) {
this.struct = struct;
}
}
|
Add pupular RC objects to index view.
Earlier they was at context processor. | from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 4 requests to DB
feedbacks = Feedback.objects.all()[:4].prefetch_related(
'bought').prefetch_related(
'bought__type_of_complex').prefetch_related('social_media_links')
residental_complexes = ResidentalComplex.objects.filter(
is_popular=True)
context = {
'feedbacks': feedbacks,
'form': SearchForm,
'residental_complexes': residental_complexes,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
| from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 4 requests to DB
feedbacks = Feedback.objects.all()[:4].prefetch_related(
'bought').prefetch_related(
'bought__type_of_complex').prefetch_related('social_media_links')
context = {
'feedbacks': feedbacks,
'form': SearchForm,
}
return render(request,
'index.html',
context,
)
def privacy_policy(request):
return render(request, 'privacy_policy.html')
def thanks(request):
return render(request, 'thanks.html')
|
fix(keyframe-grid): Make all keyframes visible via scroll | import { LitElement, html } from '@polymer/lit-element/lit-element.js'
import { repeat } from 'lit-html/directives/repeat.js'
import { shared } from '../../styles/shared.js'
/*
* Show keyframes in a grid
*/
class KeyframeGrid extends LitElement {
static get properties() {
return { keyframes: { type: Object } }
}
_toArray(object) {
const array = []
for (const step in object) {
array.push({
step: parseFloat(step),
value: object[step]
})
}
array.sort((a, b) => a.step - b.step)
return array
}
render() {
const { keyframes } = this
return html`
${shared}
<style>
.items {
overflow-x: scroll;
}
.item {
font-size: 0.8em;
}
</style>
<div class="items">
${repeat(this._toArray(keyframes), keyframe => html`
<div class="item">${keyframe.step}: ${JSON.stringify(keyframe.value, null, '\t')}</div>
`)}
</div>
`
}
}
customElements.define('keyframe-grid', KeyframeGrid)
| import { LitElement, html } from '@polymer/lit-element/lit-element.js'
import { repeat } from 'lit-html/directives/repeat.js'
import { shared } from '../../styles/shared.js'
/*
* Show keyframes in a grid
*/
class KeyframeGrid extends LitElement {
static get properties() {
return { keyframes: { type: Object } }
}
_toArray(object) {
const array = []
for (const step in object) {
array.push({
step: parseFloat(step),
value: object[step]
})
}
array.sort((a, b) => a.step - b.step)
return array
}
render() {
const { keyframes } = this
return html`
${shared}
<style>
.item {
font-size: 0.8em;
}
</style>
<div class="items">
${repeat(this._toArray(keyframes), keyframe => html`
<div class="item">${keyframe.step}: ${JSON.stringify(keyframe.value)}</div>
`)}
</div>
`
}
}
customElements.define('keyframe-grid', KeyframeGrid)
|
ENYO-1648: Change endHold from onMove to onLeave in configureHoldPulse
Issue:
- The onHoldPulse event is canceled too early when user move mouse abound.
Fix:
- We are using onLeave instead of onMove.
- Now it is cancel hold when it leaves control.
DCO-1.1-Signed-Off-By: Kunmyon Choi kunmyon.choi@lge.com | 'use strict';
var
platform = require('enyo/platform'),
dispatcher = require('enyo/dispatcher'),
gesture = require('enyo/gesture');
exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';
// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
frequency: 200,
events: [{name: 'hold', time: 400}],
resume: false,
moveTolerance: 16,
endHold: 'onLeave'
});
/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
// Table of default keyCode mappings for webOS device
dispatcher.registerKeyMap({
415 : 'play',
413 : 'stop',
19 : 'pause',
412 : 'rewind',
417 : 'fastforward',
461 : 'back'
});
}
// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts'); | 'use strict';
var
platform = require('enyo/platform'),
dispatcher = require('enyo/dispatcher'),
gesture = require('enyo/gesture');
exports = module.exports = require('./lib/options');
exports.version = '2.6.0-pre';
// Override the default holdpulse config to account for greater delays between keydown and keyup
// events in Moonstone with certain input devices.
gesture.drag.configureHoldPulse({
frequency: 200,
events: [{name: 'hold', time: 400}],
resume: false,
moveTolerance: 1500,
endHold: 'onMove'
});
/**
* Registers key mappings for webOS-specific device keys related to media control.
*
* @private
*/
if (platform.webos >= 4) {
// Table of default keyCode mappings for webOS device
dispatcher.registerKeyMap({
415 : 'play',
413 : 'stop',
19 : 'pause',
412 : 'rewind',
417 : 'fastforward',
461 : 'back'
});
}
// ensure that these are registered
require('./lib/resolution');
require('./lib/fonts'); |
Fix for loading icon that wasn't displayed anymore for homepage's random sentence.
git-svn-id: 776ea4b3e47339c5b8782ec5e9346c740e073fb4@802 e0e46c49-be69-4f5a-ad62-21024a331aea | /*
Tatoeba Project, free collaborativ creation of languages corpuses project
Copyright (C) 2009 TATOEBA Project(should be changed)
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/>.
*/
$(document).ready(function(){
var lang = $("#randomLangChoice").val();
if(lang == null) lang = '';
loadRandom(lang);
$("#showRandom").click(function(){
lang = $("#randomLangChoice").val();
loadRandom(lang);
})
});
function loadRandom(lang){
$(".random_sentences_set").html("<img src='/img/loading.gif' alt='loading'>");
$(".random_sentences_set").load("http://" + self.location.hostname + ":" + self.location.port + "/" + $("#showRandom").attr("lang") + "/sentences/random/" + lang);
}
| /*
Tatoeba Project, free collaborativ creation of languages corpuses project
Copyright (C) 2009 TATOEBA Project(should be changed)
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/>.
*/
$(document).ready(function(){
var lang = $("#randomLangChoice").val();
if(lang == null) lang = '';
loadRandom(lang);
$("#showRandom").click(function(){
lang = $("#randomLangChoice").val();
loadRandom(lang);
})
});
function loadRandom(lang){
$(".random_sentences_set").html("<div class='loading'><img src='/img/loading.gif' alt='loading'></div>");
$(".random_sentences_set").load("http://" + self.location.hostname + ":" + self.location.port + "/" + $("#showRandom").attr("lang") + "/sentences/random/" + lang);
}
|
Add logging from image release script | const path = require('path');
const { execSync } = require('child_process');
const TAG = process.env.TRAVIS_TAG;
const BRANCH = process.env.TRAVIS_BRANCH;
if (TAG && /^v\d+\.\d+\.\d+$/.test(TAG)) {
// Latest release
console.log('release-images: Triggering release of latest images.');
execSync(`node ${path.join(__dirname, 'release-images-latest.js')} --dry-run'`, { stdio: 'inherit'});
} else if (BRANCH && /^master$/.test(BRANCH)) {
// Beta release
console.log('release-images: Triggering release of beta images.');
execSync(`node ${path.join(__dirname, 'release-images-beta.js')} --dry-run`, { stdio: 'inherit'});
} else {
console.log('release-images: Build is not a release build. Skipping.');
process.exit(0);
}
| const path = require('path');
const { execSync } = require('child_process');
const TAG = process.env.TRAVIS_TAG;
const BRANCH = process.env.TRAVIS_BRANCH;
if (TAG && /^v\d+\.\d+\.\d+$/.test(TAG)) {
// Latest release
console.log('release-images: Triggering release of latest images.');
execSync(`node ${path.join(__dirname, 'release-images-latest.js')} --dry-run'`);
} else if (BRANCH && /^master$/.test(BRANCH)) {
// Beta release
console.log('release-images: Triggering release of beta images.');
execSync(`node ${path.join(__dirname, 'release-images-beta.js')} --dry-run`);
} else {
console.log('release-images: Build is not a release build. Skipping.');
process.exit(0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.