text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use `$http` service to fetch stations data.
|
'use strict';
angular.module('velo-app').controller('MainCtrl', ['$scope', 'apiService', function ($scope, apiService) {
$scope.initialize = function () {
var map = L.mapbox.map('map', 'mapbox.streets');
apiService.getStations().then(
function (response) {
var stations = response.data;
var stationMarkers = [];
stations.forEach(function (station) {
var stationMarker = L.marker(L.latLng(station.position.lat, station.position.lng));
stationMarkers.push(stationMarker);
});
var group = L.featureGroup(stationMarkers);
group.addTo(map);
map.fitBounds(group.getBounds());
},
function (error) {
// TODO handle this error properly.
console.error(error);
}
);
};
$scope.initialize();
}]);
|
'use strict';
angular.module('velo-app').controller('MainCtrl', ['$scope', 'apiService', function ($scope, apiService) {
$scope.initialize = function () {
var map = L.mapbox.map('map', 'mapbox.streets');
var apiRequest = new XMLHttpRequest();
apiRequest.open('GET', '/api/cities/lyon/stations');
apiRequest.addEventListener('load', function () {
var stations = JSON.parse(this.response);
var stationMarkers = [];
stations.forEach(function (station) {
var stationMarker = L.marker(L.latLng(station.position.lat, station.position.lng));
stationMarkers.push(stationMarker);
});
var group = L.featureGroup(stationMarkers);
group.addTo(map);
map.fitBounds(group.getBounds());
});
apiRequest.send();
};
$scope.initialize();
}]);
|
Convert third pillar setup to react-intl
|
import React from 'react';
import Types from 'prop-types';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
export const ThirdPillarSetup = ({ nextPath, isThirdPillarActive }) => (
<div>
{isThirdPillarActive && <Redirect to={nextPath} />}
<p>
<FormattedMessage id="thirdPillarFlowSetup.text" />
</p>
<p>
<FormattedMessage id="thirdPillarFlowSetup.subtext" />
</p>
<div>
<Link to={nextPath}>
<button type="button" className="btn btn-primary mt-2">
<FormattedMessage id="thirdPillarFlowSetup.buttonText" />
</button>
</Link>
</div>
</div>
);
ThirdPillarSetup.propTypes = {
nextPath: Types.string,
isThirdPillarActive: Types.bool,
};
ThirdPillarSetup.defaultProps = {
nextPath: '',
isThirdPillarActive: false,
};
const mapStateToProps = (state) => ({
isThirdPillarActive: !!(
state.login.token &&
state.login.user &&
state.login.user.thirdPillarActive
),
});
export default connect(mapStateToProps)(ThirdPillarSetup);
|
import React from 'react';
import Types from 'prop-types';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { Message } from 'retranslate';
export const ThirdPillarSetup = ({ nextPath, isThirdPillarActive }) => (
<div>
{isThirdPillarActive && <Redirect to={nextPath} />}
<p>
<Message>thirdPillarFlowSetup.text</Message>
</p>
<p>
<Message>thirdPillarFlowSetup.subtext</Message>
</p>
<div>
<Link to={nextPath}>
<button type="button" className="btn btn-primary mt-2">
<Message>thirdPillarFlowSetup.buttonText</Message>
</button>
</Link>
</div>
</div>
);
ThirdPillarSetup.propTypes = {
nextPath: Types.string,
isThirdPillarActive: Types.bool,
};
ThirdPillarSetup.defaultProps = {
nextPath: '',
isThirdPillarActive: false,
};
const mapStateToProps = (state) => ({
isThirdPillarActive: !!(
state.login.token &&
state.login.user &&
state.login.user.thirdPillarActive
),
});
export default connect(mapStateToProps)(ThirdPillarSetup);
|
Add getter method for scanner queue.
|
<?php
namespace Orbt\StyleMirror\Css;
use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;
/**
* Scans a stylesheet for resources.
*/
class ResourceScanner
{
/**
* Scanner queue.
* @var SingleUseQueue
*/
protected $queue;
public function __construct(SingleUseQueue $queue)
{
$this->queue = $queue;
}
/**
* Returns the queue used by this scanner.
*/
public function getQueue()
{
return $this->queue;
}
/**
* Scans CSS content for resources.
*
* @param GenericResource $resource
* @param string $content
*/
public function scan(GenericResource $resource, $content)
{
// Match all URL references.
preg_match_all('!url\(\s*[\'"]?([^\'"):/]+(?:/[^\'"):/]+)*)[\'"]?\s*\)!i', $content, $matches);
foreach ($matches[1] as $path) {
$this->queue->add(new GenericResource($resource->resolvePath($path)));
}
}
}
|
<?php
namespace Orbt\StyleMirror\Css;
use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;
/**
* Scans a stylesheet for resources.
*/
class ResourceScanner
{
protected $queue;
public function __construct(SingleUseQueue $queue)
{
$this->queue = $queue;
}
/**
* Scans CSS content for resources.
*
* @param GenericResource $resource
* @param string $content
*/
public function scan(GenericResource $resource, $content)
{
// Match all URL references.
preg_match_all('!url\(\s*[\'"]?([^\'"):/]+(?:/[^\'"):/]+)*)[\'"]?\s*\)!i', $content, $matches);
foreach ($matches[1] as $path) {
$this->queue->add(new GenericResource($resource->resolvePath($path)));
}
}
}
|
Fix selected value for select field.
|
<div class="{{$config['divClass']}} {{$wrapperClass}} @if($errors)f-error @endif">
@if($label) <label for="{{$name}}">{!! $label !!} @if($required)<i class="f-required">*</i>@endif</label>@endif
<select
id="{{$name}}"
name="{{$name}}"
@if($value)value="{{$value}}" @endif
@if($required)required @endif
@if($placeholder)placeholder="{{$placeholder}}"@endif
@foreach($attr as $key => $value)
@if(is_int($key)){{$value}}@else{{$key}}="{{$value}}"@endif
@endforeach
>
@if($placeholder !== null)<option disabled selected>Choisir une valeur</option>@endif
@foreach($options as $option)
<option value="{{$option['value']}}" @if($option['value'] == $value)selected @endif >{{$option['label']}}</option>
@endforeach
</select>
@if($errors)
<ul class="{{$config['errorMessageClass']}}">
@foreach ($errors as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
</div>
|
<div class="{{$config['divClass']}} {{$wrapperClass}} @if($errors)f-error @endif">
@if($label) <label for="{{$name}}">{!! $label !!} @if($required)<i class="f-required">*</i>@endif</label>@endif
<select
id="{{$name}}"
name="{{$name}}"
@if($value)value="{{$value}}" @endif
@if($required)required @endif
@if($placeholder)placeholder="{{$placeholder}}"@endif
@foreach($attr as $key => $value)
@if(is_int($key)){{$value}}@else{{$key}}="{{$value}}"@endif
@endforeach
>
@if($placeholder !== null)<option disabled selected>Choisir une valeur</option>@endif
@foreach($options as $option)
<option value="{{$option['value']}}">{{$option['label']}}</option>
@endforeach
</select>
@if($errors)
<ul class="{{$config['errorMessageClass']}}">
@foreach ($errors as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
</div>
|
Remove unnecessary branching and pass reject handler as second args to then()
|
"use strict";
/**
* Fix operator that continuously resolves next promise returned from the function that consumes
* resolved previous value.
*
* ```javascript
* fix(fn)(promise).catch(errorHandler);
* ```
*
* is equivalent to:
*
* ```javascript
* promise.then(fn).then(fn).then(fn) ...
* .catch(errorHandler);
* ```
*
* @param {function(<T>) : Promise} fn
* @returns {function(Promise.<T>) : Promise.<Promise>}
* @template T
*/
var fix = (fn) => (promise) => {
var rejecter;
var resolver = (v) => {
try {
var nextPromise = fn(v);
nextPromise.then(resolver, rejecter);
} catch(err) {
rejecter(err);
}
};
return new Promise((resolve, reject) => {
rejecter = reject;
promise.then(resolver, reject);
});
};
export default fix;
|
"use strict";
/**
* Fix operator that continuously resolves next promise returned from the function that consumes
* resolved previous value.
*
* ```javascript
* fix(fn)(promise).catch(errorHandler);
* ```
*
* is equivalent to:
*
* ```javascript
* promise.then(fn).then(fn).then(fn) ...
* .catch(errorHandler);
* ```
*
* @param {function(<T>) : Promise} fn
* @returns {function(Promise.<T>) : Promise.<Promise>}
* @template T
*/
var fix = (fn) => (promise) => {
var rejecter;
var resolver = (v) => {
try {
var nextPromise = fn(v);
nextPromise.then(resolver);
if (nextPromise.catch) {
nextPromise.catch(rejecter);
}
} catch(err) {
rejecter(err);
}
};
return new Promise((resolve, reject) => {
rejecter = reject;
promise.then(resolver);
if (promise.catch) {
promise.catch(reject);
}
});
};
export default fix;
|
Fix typo in resource file path
|
package com.redhat.victims;
public class Resources {
public static final String JAR_FILE = "testdata/junit-4.11/junit-4.11.jar";
public static final String JAR_SHA1 = JAR_FILE + ".sha1";
public static final String JAR_JSON = JAR_FILE + ".json";
public static final String POM_FILE = "testdata/junit-4.11/junit-4.11.pom";
public static final String POM_SHA1 = POM_FILE + ".sha1";
public static final String POM_JSON = POM_FILE + ".json";
public static final String RECORD_CLIENT_JAR = "testdata/records/victims-client.jar.json";
public static final String TEST_RESPONSE = "testdata/service/test.response";
public static final String TEST_SHA512 = "testdata/service/test.sha512";
public static final String TEST_CVE = "testdata/service/test.cve";
}
|
package com.redhat.victims;
public class Resources {
public static final String JAR_FILE = "testdata/junit-4.11/junit-4.11.jar";
public static final String JAR_SHA1 = JAR_FILE + ".sha1";
public static final String JAR_JSON = JAR_FILE + ".json";
public static final String POM_FILE = "testdata/junit-4.11/junit-4.11.pom";
public static final String POM_SHA1 = POM_FILE + ".sha1";
public static final String POM_JSON = POM_FILE + ".json";
public static final String RECORD_CLIENT_JAR = "testdata/records/victims-client-1.0-SNAPSHOT.jar.json";
public static final String TEST_RESPONSE = "testdata/service/test.response";
public static final String TEST_SHA512 = "testdata/service/test.sha512";
public static final String TEST_CVE = "testdata/service/test.cve";
}
|
Implement md5 for demo known users password
|
'use strict';
var userDAO = require('../index').UserDAO.createInstance();
var userService = require('../index').UserService.singleton(userDAO);
var UsersGenerator = require('../index').UsersGenerator;
var md5 = require('MD5');
var usersGen = new UsersGenerator();
// Generate some fake users
var fakeUsers = usersGen.generateUsers(3);
// Generate known users
var users = [
{
username: 'widget',
password: md5('test1'),
role: "WIDGET_DESIGNER"
},
{
username: 'manager',
password: md5('test2'),
role: "MANAGER"
},
{
username: 'admin',
password: md5('1234567'),
role: "ADMIN"
}
];
users.forEach(function (user, iUser) {
users[iUser] = usersGen.generateUser(user);
});
// Put together
users = users.concat(fakeUsers);
// Save users (This creates the file with the collection of users)
userService.save( users );
|
'use strict';
var userDAO = require('../index').UserDAO.createInstance();
var userService = require('../index').UserService.singleton(userDAO);
var UsersGenerator = require('../index').UsersGenerator;
var usersGen = new UsersGenerator();
// Generate some fake users
var fakeUsers = usersGen.generateUsers(3);
// Generate known users
var users = [
{
username: 'widget',
password: 'test1',
role: "WIDGET_DESIGNER"
},
{
username: 'manager',
password: 'test2',
role: "MANAGER"
},
{
username: 'admin',
password: '1234567',
role: "ADMIN"
}
];
users.forEach(function (user, iUser) {
users[iUser] = usersGen.generateUser(user);
});
// Put together
users = users.concat(fakeUsers);
// Save users (This creates the file with the collection of users)
userService.save( users );
|
Add tests for nonlistening addresses as well.
|
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
def build_addr_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
@pytest.fixture(**build_addr_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
@pytest.fixture(**build_addr_infos())
def nonlistening_addr(request):
af, socktype, proto, canonname, sa = request.param
return sa
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
def test_check_port_nonlistening(self, nonlistening_addr):
portend._check_port(*nonlistening_addr[:2])
|
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
def build_listening_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
@pytest.fixture(**build_listening_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
|
Use real network interface for gRPC acceptance testing
|
// +build acceptance
package app_test
import (
"net"
"github.com/DATA-DOG/godog"
"github.com/deshboard/boilerplate-grpc-service/test"
"google.golang.org/grpc"
)
func init() {
test.RegisterFeaturePath("../features")
test.RegisterFeatureContext(FeatureContext)
}
func FeatureContext(s *godog.Suite) {
lis, err := net.Listen("tcp", ":0")
if err != nil {
panic(err)
}
client, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
if err != nil {
panic(err)
}
server := grpc.NewServer()
// Add steps here
func(s *godog.Suite, server *grpc.Server, client *grpc.ClientConn) {}(s, server, client)
go server.Serve(lis)
}
|
// +build acceptance
package app_test
import (
stdnet "net"
"time"
"github.com/DATA-DOG/godog"
"github.com/deshboard/boilerplate-grpc-service/test"
"github.com/goph/stdlib/net"
"google.golang.org/grpc"
)
func init() {
test.RegisterFeaturePath("../features")
test.RegisterFeatureContext(FeatureContext)
}
func FeatureContext(s *godog.Suite) {
addr := net.ResolveVirtualAddr("pipe", "pipe")
listener, dialer := net.PipeListen(addr)
server := grpc.NewServer()
client, _ := grpc.Dial("", grpc.WithInsecure(), grpc.WithDialer(func(s string, t time.Duration) (stdnet.Conn, error) { return dialer.Dial() }))
// Add steps here
func(s *godog.Suite, server *grpc.Server, client *grpc.ClientConn) {}(s, server, client)
go server.Serve(listener)
}
|
Resolve image icon path relative to module
|
var {JFrame, JButton, ImageIcon, JLabel} = javax.swing;
var {setInterval} = require('ringo/scheduler');
var n = 0;
function main() {
var frame = new JFrame("Swing Demo");
var button = new JButton(new ImageIcon(module.resolve("img/ringo-drums.png")));
button.addActionListener(function(e) {
setInterval(function() {
if (n++ > 200) system.exit();
frame.setLocation(200 + random(), 200 + random());
}, 5);
});
frame.add("Center", button);
frame.add("South", new JLabel("Click Button for Visual Drumroll!"));
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
}
function random() (Math.random() - 0.5) * 50;
if (require.main == module) {
main();
}
|
var {JFrame, JButton, ImageIcon, JLabel} = javax.swing;
var {setInterval} = require('ringo/scheduler');
var n = 0;
function main() {
var frame = new JFrame("Swing Demo");
var button = new JButton(new ImageIcon("img/ringo-drums.png"));
button.addActionListener(function(e) {
setInterval(function() {
if (n++ > 200) system.exit();
frame.setLocation(200 + random(), 200 + random());
}, 5);
});
frame.add("Center", button);
frame.add("South", new JLabel("Click Button for Visual Drumroll!"));
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
}
function random() (Math.random() - 0.5) * 50;
if (require.main == module) {
main();
}
|
Handle the case where hash.Members is undefined
|
import ApplicationSerializer from './application';
import { AdapterError } from 'ember-data/adapters/errors';
export default ApplicationSerializer.extend({
attrs: {
datacenter: 'dc',
address: 'Addr',
serfPort: 'Port',
},
normalize(typeHash, hash) {
if (!hash) {
// It's unusual to throw an adapter error from a serializer,
// but there is no single server end point so the serializer
// acts like the API in this case.
const error = new AdapterError([{ status: '404' }]);
error.message = 'Requested Agent was not found in set of available Agents';
throw error;
}
hash.ID = hash.Name;
hash.Datacenter = hash.Tags && hash.Tags.dc;
hash.Region = hash.Tags && hash.Tags.region;
hash.RpcPort = hash.Tags && hash.Tags.port;
return this._super(typeHash, hash);
},
normalizeResponse(store, typeClass, hash, ...args) {
return this._super(store, typeClass, hash.Members || [], ...args);
},
normalizeSingleResponse(store, typeClass, hash, id, ...args) {
return this._super(store, typeClass, hash.findBy('Name', id), id, ...args);
},
});
|
import ApplicationSerializer from './application';
import { AdapterError } from 'ember-data/adapters/errors';
export default ApplicationSerializer.extend({
attrs: {
datacenter: 'dc',
address: 'Addr',
serfPort: 'Port',
},
normalize(typeHash, hash) {
if (!hash) {
// It's unusual to throw an adapter error from a serializer,
// but there is no single server end point so the serializer
// acts like the API in this case.
const error = new AdapterError([{ status: '404' }]);
error.message = 'Requested Agent was not found in set of available Agents';
throw error;
}
hash.ID = hash.Name;
hash.Datacenter = hash.Tags && hash.Tags.dc;
hash.Region = hash.Tags && hash.Tags.region;
hash.RpcPort = hash.Tags && hash.Tags.port;
return this._super(typeHash, hash);
},
normalizeResponse(store, typeClass, hash, ...args) {
return this._super(store, typeClass, hash.Members, ...args);
},
normalizeSingleResponse(store, typeClass, hash, id, ...args) {
return this._super(store, typeClass, hash.findBy('Name', id), id, ...args);
},
});
|
Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found
|
#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response, HTTPException
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
try:
response = yield from next_handler(request)
except HTTPException as exc:
response = exc
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
|
#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
response = yield from next_handler(request)
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
|
Throw error at invalid inputs
|
/**
* Created by Umayr Shahid on 4/28/16.
*/
'use strict';
const ParenthesisRegex = /\([^()"]*(?:"[^"]*"[^()"]*)*\)/;
const Dictionary = Object.freeze({
'AND': '&&',
'OR': '||'
});
const evaluate = require('safe-eval');
class Slq {
constructor(target) {
this.target = target;
}
query(q) {
if (q === void 0 || q === '') throw new Error('slq: query should not be empty');
let matches = q.match(ParenthesisRegex);
if (!matches) return this.evaluate(q);
matches.forEach(match => {
let result = this.evaluate(match);
q = q.replace(match, result);
});
return this.query(q);
}
substitute(value) {
value = String(value);
if (value === 'true' || value === 'false') return value;
return this.target[value];
}
trim(value) {
value = String(value).trim();
if (value.indexOf('(') > -1) value = value.slice(1);
if (value.indexOf(')') > -1) value = value.slice(0, -1);
return value;
}
evaluate(value) {
value = this.trim(value);
let parts = value.split(' ');
let operator = Dictionary[parts[1]];
if (operator === void 0) throw new Error('slq: invalid operator');
return evaluate(`${this.substitute(parts[0])} ${operator} ${this.substitute(parts[2])}`);
}
}
module.exports = Slq;
|
/**
* Created by Umayr Shahid on 4/28/16.
*/
'use strict';
const ParenthesisRegex = /\([^()"]*(?:"[^"]*"[^()"]*)*\)/;
const Dictionary = Object.freeze({
'AND': '&&',
'OR': '||'
});
const evaluate = require('safe-eval');
class Slq {
constructor(target) {
this.target = target;
}
query(q) {
let matches = q.match(ParenthesisRegex);
if (!matches) {
return this.evaluate(q);
}
matches.forEach(match => {
let result = this.evaluate(match);
q = q.replace(match, result);
});
return this.query(q);
}
substitute(value) {
if (value === 'true' || value === 'false') return value;
return this.target[value];
}
trim(value) {
value = String(value).trim();
if (value.indexOf('(') > -1) value = value.slice(1);
if (value.indexOf(')') > -1) value = value.slice(0, -1);
return value;
}
evaluate(value) {
value = this.trim(value);
let parts = value.split(' ');
let operator = Dictionary[parts[1]];
let expression = this.substitute(parts[0]) + operator + this.substitute(parts[2]);
return evaluate(expression);
}
}
module.exports = Slq;
|
Use host as localhost address instead of server name
|
<?php
function adminer_object()
{
// Required to run any plugin.
include_once "./plugins/plugin.php";
// Plugins auto-loader.
foreach (glob("plugins/*.php") as $filename) {
include_once "./$filename";
}
// Specify enabled plugins here.
$plugins = [
new AdminerDatabaseHide(["mysql", "information_schema", "performance_schema"]),
new AdminerLoginServers([
filter_input(INPUT_SERVER, 'HTTP_HOST') => filter_input(INPUT_SERVER, 'SERVER_NAME')
]),
new AdminerSimpleMenu(),
new AdminerCollations(["utf8mb4_general_ci", "ascii_general_ci"]),
new AdminerJsonPreview(),
// AdminerTheme has to be the last one.
new AdminerTheme(),
];
return new AdminerPlugin($plugins);
}
// Include original Adminer or Adminer Editor.
include "./adminer.php";
|
<?php
function adminer_object()
{
// Required to run any plugin.
include_once "./plugins/plugin.php";
// Plugins auto-loader.
foreach (glob("plugins/*.php") as $filename) {
include_once "./$filename";
}
// Specify enabled plugins here.
$plugins = array(
new AdminerDatabaseHide(array("mysql", "information_schema", "performance_schema")),
new AdminerLoginServers(array(filter_input(INPUT_SERVER, 'SERVER_NAME'))),
new AdminerSimpleMenu(),
new AdminerCollations(array("utf8mb4_general_ci", "ascii_general_ci")),
new AdminerJsonPreview(),
// AdminerTheme has to be the last one.
new AdminerTheme(),
);
return new AdminerPlugin($plugins);
}
// Include original Adminer or Adminer Editor.
include "./adminer.php";
|
Use includes instead of indexOf
|
'use strict';
const path = require('path');
const fs = require('fs');
const camelCase = require('camelcase');
function getPackageDeps() {
const pkgFile = fs.readFileSync('./package.json');
return Object.keys(JSON.parse(pkgFile).devDependencies);
}
function renamePlugin(name) {
return camelCase(name.replace(/^gulp(-|\.)/, ''));
}
function getHelpers() {
const helpers = {};
fs.readdirSync('./gulp/helpers').forEach((helper) => {
const name = path.basename(helper, '.js');
helpers[camelCase(name)] = require(path.join('..', 'helpers', helper));
});
return helpers;
}
global.needDeps = [];
global.use = function() {
const pkgDeps = getPackageDeps();
const taskDeps = Array.from(arguments);
const needDeps = taskDeps.filter((dependName) => {
return !pkgDeps.includes(dependName);
});
if (needDeps.length) {
global.needDeps = global.needDeps.concat(needDeps);
return;
}
const deps = {
gulp: require('gulp'),
helper: getHelpers()
};
taskDeps.forEach((dependName) => {
deps[renamePlugin(dependName)] = require(dependName);
});
return deps;
};
|
'use strict';
const path = require('path');
const fs = require('fs');
const camelCase = require('camelcase');
function getPackageDeps() {
const pkgFile = fs.readFileSync('./package.json');
return Object.keys(JSON.parse(pkgFile).devDependencies);
}
function renamePlugin(name) {
return camelCase(name.replace(/^gulp(-|\.)/, ''));
}
function getHelpers() {
const helpers = {};
fs.readdirSync('./gulp/helpers').forEach((helper) => {
const name = path.basename(helper, '.js');
helpers[camelCase(name)] = require(path.join('..', 'helpers', helper));
});
return helpers;
}
global.needDeps = [];
global.use = function() {
const pkgDeps = getPackageDeps();
const taskDeps = Array.from(arguments);
const needDeps = taskDeps.filter((dependName) => {
return (pkgDeps.indexOf(dependName) === -1);
});
if (needDeps.length) {
global.needDeps = global.needDeps.concat(needDeps);
return;
}
const deps = {
gulp: require('gulp'),
helper: getHelpers()
};
taskDeps.forEach((dependName) => {
deps[renamePlugin(dependName)] = require(dependName);
});
return deps;
};
|
Resolve old Django 1.1 bug in URLs to keep it DRY.
|
from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.utils.functional import lazy
reverse_lazy = lazy(reverse, unicode)
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='logout'),
url(r'^password/forgot/$', 'password_reset',
{'post_reset_redirect':reverse_lazy('users:password_reset_done')},
name='password_reset'),
url(r'^password/forgot/done/$', 'password_reset_done',
name='password_reset_done'),
url(r'^password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'post_reset_redirect':
reverse_lazy('users:password_reset_complete')},
name='password_reset_confirm'),
url(r'^password/reset/done/$', 'password_reset_complete',
name='password_reset_complete'),
url(r'^password/change/', 'password_change',
name='password_change'),
url(r'^password/change/done', 'password_change_done',
name='password_change'),
)
|
from django.conf.urls.defaults import *
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='logout'),
url(r'^password/forgot/$', 'password_reset',
# LH #269 - ideally this wouldn't be hard coded
{'post_reset_redirect':'/accounts/password/forgot/done/'},
name='password_reset'),
url(r'^password/forgot/done/$', 'password_reset_done',
name='password_reset_done'),
url(r'^password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
# LH #269
{'post_reset_redirect':'/accounts/password/reset/done/'},
name='password_reset_confirm'),
url(r'^password/reset/done/$', 'password_reset_complete',
name='password_reset_complete'),
url(r'^password/change/', 'password_change',
name='password_change'),
url(r'^password/change/done', 'password_change_done',
name='password_change'),
)
|
Update dsub version to 0.4.6.dev0
PiperOrigin-RevId: 393201424
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.6.dev0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.5'
|
Fix a ESM bug in build script
|
/*
* Copyright 2021 Simon Edwards <simon@simonzone.com>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import * as https from 'node:https';
const log = console.log.bind(console);
/**
* @param {string} url
* @return {Promise<Buffer>}
*/
export async function fetchUrl(url) {
log(`Downloading ${url}`);
return new Promise( (resolve, reject) => {
https.get(url, {}, (resp) => {
// log(resp.headers);
// log(`statusCode: ${resp.statusCode}`);
if (resp.statusCode === 302) {
fetchUrl(resp.headers.location).then(data => resolve(data));
return;
}
const data = [];
resp.on('data', (chunk) => {
data.push(chunk);
});
resp.on('end', () => {
resolve(Buffer.concat(data));
});
}).on("error", (err) => {
log("Error: " + err.message);
reject("Error: " + err.message);
});
});
}
|
/*
* Copyright 2021 Simon Edwards <simon@simonzone.com>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import * as https from 'node:https';
const log = console.log.bind(console);
/**
* @param {string} url
* @return {Promise<Buffer>}
*/
async function fetchUrl(url) {
log(`Downloading ${url}`);
return new Promise( (resolve, reject) => {
https.get(url, {}, (resp) => {
// log(resp.headers);
// log(`statusCode: ${resp.statusCode}`);
if (resp.statusCode === 302) {
fetchUrl(resp.headers.location).then(data => resolve(data));
return;
}
const data = [];
resp.on('data', (chunk) => {
data.push(chunk);
});
resp.on('end', () => {
resolve(Buffer.concat(data));
});
}).on("error", (err) => {
log("Error: " + err.message);
reject("Error: " + err.message);
});
});
}
exports.fetchUrl = fetchUrl;
|
Refactor Javadoc on converter API
|
/*
* Copyright (c) OSGi Alliance (2014, 2016). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.converter;
import org.osgi.annotation.versioning.ConsumerType;
/**
* An functional interface with a single convert method that is passed the
* object to be converted.
*
* @param <F> Type parameter for the source object.
* @param <T> Type parameter for the converted object.
* @ThreadSafe
* @author $Id$
*/
@ConsumerType
@FunctionalInterface
public interface Function<F, T> {
/**
* /** Convert the object into the target type.
*
* @param obj The object to be converted. This object will never be
* {@code null} as the convert function will not be invoked for
* null values.
* @return The conversion result or {@code null} to indicate that the
* convert function cannot handle this conversion. In this case the
* next matching rule or adapter will be given a opportunity to
* convert.
* @throws Exception
*/
T convert(F obj) throws Exception;
}
|
/*
* Copyright (c) OSGi Alliance (2014, 2016). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.converter;
import org.osgi.annotation.versioning.ConsumerType;
/**
* A function that accepts a single argument and produces a result.
* <p>
* This is a functional interface and can be used as the assignment target for a
* lambda expression or method reference.
*
* @param <F> The type of the function input.
* @param <T> The type of the function output.
* @ThreadSafe
* @author $Id$
*/
@ConsumerType
@FunctionalInterface
public interface Function<F, T> {
/**
* Applies this function to the specified argument.
*
* @param t The input to this function.
* @return The output of this function.
* @throws Exception An exception thrown by the method.
*/
T convert(F t) throws Exception;
}
|
Extend timeout before killing process.
|
const R = require("ramda");
const Promise = require("bluebird");
const pubsub = require("../")("amqp://docker");
const publish = (event, index) => {
const data = { number: index + 1 };
console.log(` [-] Published event '${ event.name }' with data:`, data);
event.publish(data)
};
// Create the event.
const events = {
foo: pubsub.event("foo"),
bar: pubsub.event("bar")
};
// Read in the command-line args, to determine which event to fire
// and how many events to fire it.
const args = process.argv.slice(2);
const eventName = args[0] || "foo";
const count = parseInt(args[1]) || 1;
if (events[eventName]) {
const promises = R.times((index) => publish(events[eventName], index), count);
Promise.all(promises)
.then(() => {
console.log("");
setTimeout(() => process.exit(0), 500);
})
} else {
console.log(`Event named '${ eventName }' does not exist.\n`);
}
|
const R = require("ramda");
const Promise = require("bluebird");
const pubsub = require("../")("amqp://docker");
const publish = (event, index) => {
const data = { number: index + 1 };
console.log(` [-] Published event '${ event.name }' with data:`, data);
event.publish(data)
};
// Create the event.
const events = {
foo: pubsub.event("foo"),
bar: pubsub.event("bar")
};
// Read in the command-line args, to determine which event to fire
// and how many events to fire it.
const args = process.argv.slice(2);
const eventName = args[0] || "foo";
const count = parseInt(args[1]) || 1;
if (events[eventName]) {
const promises = R.times((index) => publish(events[eventName], index), count);
Promise.all(promises)
.then(() => {
console.log("");
setTimeout(() => process.exit(0), 200);
})
} else {
console.log(`Event named '${ eventName }' does not exist.\n`);
}
|
Add comment referencing Django CSRF docs.
|
/*
* Internal module that is used by the default client, http client, and
* the session fetching apparatus. Made as a separate module to avoid
* circular dependencies and repeated code.
*/
import rest from 'rest';
import interceptor from 'rest/interceptor';
import errorCode from 'rest/interceptor/errorCode';
import cookiejs from 'js-cookie';
/*
* Vendored and modified from https://github.com/cujojs/rest/blob/master/interceptor/csrf.js
*/
/**
* Applies a Cross-Site Request Forgery protection header to a request
*
* CSRF protection helps a server verify that a request came from a
* trusted client and not another client that was able to masquerade
* as an authorized client. Sites that use cookie based authentication
* are particularly vulnerable to request forgeries without extra
* protection.
*
* @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
*
* @param {Client} [client] client to wrap
*
* @returns {Client}
*/
const csrf = interceptor({
request: function handleRequest(request) {
// For more information on how the CSRF token is used on the backend
// please refer to the Django documentation on the subject:
// https://docs.djangoproject.com/en/1.11/ref/csrf/
var headers, name, token;
headers = request.headers || (request.headers = {});
name = request.csrfTokenName || 'X-CSRFToken';
token = request.csrfToken || cookiejs.get('csrftoken');
if (token) {
headers[name] = token;
}
return request;
},
});
export default rest.wrap(errorCode).wrap(csrf);
|
/*
* Internal module that is used by the default client, http client, and
* the session fetching apparatus. Made as a separate module to avoid
* circular dependencies and repeated code.
*/
import rest from 'rest';
import interceptor from 'rest/interceptor';
import errorCode from 'rest/interceptor/errorCode';
import cookiejs from 'js-cookie';
/*
* Vendored and modified from https://github.com/cujojs/rest/blob/master/interceptor/csrf.js
*/
/**
* Applies a Cross-Site Request Forgery protection header to a request
*
* CSRF protection helps a server verify that a request came from a
* trusted client and not another client that was able to masquerade
* as an authorized client. Sites that use cookie based authentication
* are particularly vulnerable to request forgeries without extra
* protection.
*
* @see http://en.wikipedia.org/wiki/Cross-site_request_forgery
*
* @param {Client} [client] client to wrap
*
* @returns {Client}
*/
const csrf = interceptor({
request: function handleRequest(request) {
var headers, name, token;
headers = request.headers || (request.headers = {});
name = request.csrfTokenName || 'X-CSRFToken';
token = request.csrfToken || cookiejs.get('csrftoken');
if (token) {
headers[name] = token;
}
return request;
},
});
export default rest.wrap(errorCode).wrap(csrf);
|
Fix collapsing of rule explanations
|
/**
* This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project.
* @copyright 2020 subtitulamos.tv
*/
import "../css/rules.scss";
import { get_all, onDomReady } from "./utils";
onDomReady(() => {
for (const $spoilerName of get_all(".spoiler-name")) {
$spoilerName.addEventListener("click", function () {
const $spoilerWrapper = this.closest(".spoiler-wrapper");
const $spoiler = $spoilerWrapper.querySelector(".spoiler-content");
if ($spoilerName.innerHTML.includes("VER")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("VER", "OCULTAR");
} else if ($spoilerName.innerHTML.includes("OCULTAR")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("OCULTAR", "VER");
}
if ($spoilerName.innerHTML.includes("MÁS")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("MÁS", "MENOS");
} else if ($spoilerName.innerHTML.includes("MENOS")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("MENOS", "MÁS");
}
const $icon = this.querySelector(".spoiler-name i");
$icon.classList.toggle("fa-chevron-down");
$icon.classList.toggle("fa-chevron-up");
$spoiler.classList.toggle("expanded");
});
}
});
|
/**
* This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project.
* @copyright 2020 subtitulamos.tv
*/
import "../css/rules.scss";
import { onDomReady } from "./utils";
onDomReady(() => {
for (const $spoilerWrapper of document.querySelectorAll(".spoiler-wrapper")) {
$spoilerWrapper.addEventListener("click", function () {
const $spoiler = this.querySelector(".spoiler-content");
const $spoilerName = this.querySelector(".spoiler-name");
if ($spoilerName.innerHTML.includes("VER")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("VER", "OCULTAR");
} else if ($spoilerName.innerHTML.includes("OCULTAR")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("OCULTAR", "VER");
}
if ($spoilerName.innerHTML.includes("MÁS")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("MÁS", "MENOS");
} else if ($spoilerName.innerHTML.includes("MENOS")) {
$spoilerName.innerHTML = $spoilerName.innerHTML.replace("MENOS", "MÁS");
}
const $icon = this.querySelector(".spoiler-name i");
$icon.classList.toggle("fa-chevron-down");
$icon.classList.toggle("fa-chevron-up");
$spoiler.classList.toggle("expanded");
});
}
});
|
Update the version for 2.0.0~rc2 release.
|
__version__ = '2.0.0~rc2'
__license__ = '''
Copyright (c) 2009-2011, Cameron Dale <camrdale@gmail.com>
Copyright (c) 2005-2009, Bill McCloskey <bill.mccloskey@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
'''
|
__version__ = '2.0.0~rc1'
__license__ = '''
Copyright (c) 2009-2011, Cameron Dale <camrdale@gmail.com>
Copyright (c) 2005-2009, Bill McCloskey <bill.mccloskey@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
'''
|
Remove all info pertaining to pygooglechart
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging to a Database in Django',
packages=find_packages(),
zip_safe=False,
install_requires=[
'django-paging>=0.2.2',
'django-indexer==0.2',
],
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging to a Database in Django',
packages=find_packages(),
zip_safe=False,
install_requires=[
# Optional
'django-paging>=0.2.2',
'django-indexer==0.2',
],
include_package_data=True,
classifiers=[
'Framework :: Django',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
],
)
|
Add an option to disable code reloader to runserver command
|
#!/usr/bin/env python
import os
from argh import arg, ArghParser
from functools import wraps
def with_app(func):
@wraps(func)
@arg('--config', help='Path to config file', required=True)
def wrapper(*args, **kwargs):
config = args[0].config
from alfred_listener import create_app
app = create_app(config)
return func(app, *args, **kwargs)
return wrapper
@arg('--host', default='127.0.0.1', help='the host')
@arg('--port', default=5000, help='the port')
@arg('--noreload', action='store_true', help='disable code reloader')
@with_app
def runserver(app, args):
app.run(args.host, args.port, use_reloader=not args.noreload)
@with_app
def shell(app, args):
from alfred_listener.helpers import get_shell
with app.test_request_context():
sh = get_shell()
sh(app=app)
def main():
parser = ArghParser()
parser.add_commands([runserver, shell])
parser.dispatch()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import os
from argh import arg, ArghParser
from functools import wraps
def with_app(func):
@wraps(func)
@arg('--config', help='Path to config file', required=True)
def wrapper(*args, **kwargs):
config = args[0].config
from alfred_listener import create_app
app = create_app(config)
return func(app, *args, **kwargs)
return wrapper
@arg('--host', default='127.0.0.1', help='the host')
@arg('--port', default=5000, help='the port')
@with_app
def runserver(app, args):
app.run(args.host, args.port)
@with_app
def shell(app, args):
from alfred_listener.helpers import get_shell
with app.test_request_context():
sh = get_shell()
sh(app=app)
def main():
parser = ArghParser()
parser.add_commands([runserver, shell])
parser.dispatch()
if __name__ == '__main__':
main()
|
Change cmg get to post
|
<?
session_start();
if($_REQUEST['logout']){unset($_SESSION['admin']);}
if($_SESSION['admin'] == ""){
die();
}
include("../lib/CloudMngr/cloudmngr.core.class.php");
$CloudMngr = new CloudMngr($_GET['id']);
$module = $_POST['module'];//{TODO input filertering
$action = $_POST['action'];
if($module != "" && file_exists($CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . $module.'.php')){
$file = $CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . "cmd" . DIRECTORY_SEPARATOR . $action .'.php';
if(file_exists($action_file)){
include($action_file);
}
}
?>
|
<?
session_start();
if($_REQUEST['logout']){unset($_SESSION['admin']);}
if($_SESSION['admin'] == ""){
die();
}
include("../lib/CloudMngr/cloudmngr.core.class.php");
$CloudMngr = new CloudMngr($_GET['id']);
$module = $_GET['module'];//{TODO input filertering
$action = $_GET['action'];
if($module != "" && file_exists($CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . $module.'.php')){
$file = $CloudMngr->class_path . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . "cmd" . DIRECTORY_SEPARATOR . $action .'.php';
if(file_exists($action_file)){
include($action_file);
}
}
?>
|
Add radix to a parseInt()
|
Gittip.upgrade = {};
Gittip.upgrade.init = function () {
var userAgent = navigator.userAgent.toLowerCase();
var browser = (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1], 10) : -1;
if(browser != -1 && browser < 9) {
var message = '' +
'<div id="upgrade_browser">' +
' <div class="container">' +
'This browser isn\'t supported by GitTip.com. ' +
'We encourage You to upgrade or change browser. ' +
'<a href="http://browsehappy.com">Learn more</a>' +
' </div>' +
'</div>';
$("body").prepend(message);
}
};
$(document).ready(Gittip.upgrade.init);
|
Gittip.upgrade = {};
Gittip.upgrade.init = function () {
var userAgent = navigator.userAgent.toLowerCase();
var browser = (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1]) : -1;
if(browser != -1 && browser < 9) {
var message = '' +
'<div id="upgrade_browser">' +
' <div class="container">' +
'This browser isn\'t supported by GitTip.com. ' +
'We encourage You to upgrade or change browser. ' +
'<a href="http://browsehappy.com">Learn more</a>' +
' </div>' +
'</div>';
$("body").prepend(message);
}
};
$(document).ready(Gittip.upgrade.init);
|
Test reflects passing raw string at initialization.
|
var nodehun = require('./../lib/index.js'),
Dictionary = nodehun.Dictionary;
var fs = require('fs'),
mctime = require('microtime'),
unit = typeof mctime !== "undefined" ? "μs":"ms",
time = typeof mctime !== "undefined" ? mctime.now : Date.now;
var affbuf = fs.readFileSync(__dirname+'/../dictionaries/en_US/en_US.aff').toString();
var dictbuf = fs.readFileSync(__dirname+'/../dictionaries/en_US/en_US.dic').toString();
var timeInit = time();
//var dict = new Dictionary('en_US');
var dict = new Dictionary(affbuf,dictbuf);
console.log('time to initialize dictionary class:',time() - timeInit,unit);
timeInit = time();
dict.spellSuggest('Tacoma',function(a,b){console.log('misspelling "Tacoma"',a,b,'time to receive result:',time() - timeInit,unit)});
dict.spellSuggestions('calor',function(a,b){console.log('misspelling "calor"',a,b)});
dict.spellSuggest('color',function(a,b){console.log('correct "color"',a,b)});
dict.spellSuggestions('color',function(a,b){console.log('correct "color"',a,b)});
|
var nodehun = require('./../lib/index.js'),
Dictionary = nodehun.Dictionary,
mctime = require('microtime'),
unit = typeof mctime !== "undefined" ? "μs":"ms",
time = typeof mctime !== "undefined" ? mctime.now : Date.now;
var timeInit = time();
var dict = new Dictionary('en_US');
console.log('time to initialize dictionary class:',time() - timeInit,unit);
timeInit = time();
dict.spellSuggest('Tacoma',function(a,b){console.log('misspelling "Tacoma"',a,b,'time to receive result:',time() - timeInit,unit)});
dict.spellSuggestions('calor',function(a,b){console.log('misspelling "calor"',a,b)});
dict.spellSuggest('color',function(a,b){console.log('correct "color"',a,b)});
dict.spellSuggestions('color',function(a,b){console.log('correct "color"',a,b)});
|
Revert "Remove the 'end' type from format()"
This reverts commit aff79b167029fa45c3bef6af187d795e1b012cd1.
|
var util = require('util');
var mochaFormatter = {
suite: "describe('%s', function () {",
test: "it('%s');",
end: '});'
};
function format(line, type) {
if (type === 'end') {
return mochaFormatter.end;
} else {
return util.format(mochaFormatter[type], line.trim());
}
}
function getIndentLength(line) {
return (line.match(/ {2}/g) || []).length;
}
module.exports = function (input) {
var newline = '\n';
var inputLines = input.split(newline);
var outputLines = [];
inputLines.forEach(function (line, index) {
var indentLength = getIndentLength(line);
var nextLine = inputLines[index + 1];
var nextIndentLength = nextLine === undefined ? 0 : getIndentLength(nextLine);
if (line.length === 0) {
outputLines.push('');
} else if (nextLine === undefined || indentLength >= nextIndentLength) {
outputLines.push(format(line, 'test'));
if (indentLength > nextIndentLength) {
for (var i = 0; i < indentLength - nextIndentLength; i++) {
outputLines.push(format(line, 'end'));
}
}
} else {
outputLines.push(format(line, 'suite'));
}
});
return outputLines.join(newline);
};
|
var util = require('util');
var mochaFormatter = {
suite: "describe('%s', function () {",
test: "it('%s');",
end: '});'
};
function format(line, type) {
return util.format(mochaFormatter[type], line.trim());
}
function getIndentLength(line) {
return (line.match(/ {2}/g) || []).length;
}
module.exports = function (input) {
var newline = '\n';
var inputLines = input.split(newline);
var outputLines = [];
inputLines.forEach(function (line, index) {
var indentLength = getIndentLength(line);
var nextLine = inputLines[index + 1];
var nextIndentLength = nextLine === undefined ? 0 : getIndentLength(nextLine);
if (line.length === 0) {
outputLines.push('');
} else if (nextLine === undefined || indentLength >= nextIndentLength) {
outputLines.push(format(line, 'test'));
if (indentLength > nextIndentLength) {
for (var i = 0; i < indentLength - nextIndentLength; i++) {
outputLines.push(mochaFormatter.end);
}
}
} else {
outputLines.push(format(line, 'suite'));
}
});
return outputLines.join(newline);
};
|
Add event key to match score notification
|
from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
self._event_feed = self.event.key_name
self._district_feed = self.event.event_district_enum
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.event.name
data['message_data']['event_key'] = self.event.key_name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
|
from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
self._event_feed = self.event.key_name
self._district_feed = self.event.event_district_enum
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.event.name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
|
Allow for lazy translation of message tags
|
from django import template
from django.contrib.messages.utils import get_level_tags
from django.utils.encoding import force_text
LEVEL_TAGS = get_level_tags()
register = template.Library()
@register.simple_tag()
def get_message_tags(message):
"""
Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix
along with any tags included in message.extra_tags
Messages in Django >= 1.7 have a message.level_tag attr
"""
level_tag = force_text(LEVEL_TAGS.get(message.level, ''), strings_only=True)
if level_tag == u"error":
level_tag = u"danger"
alert_level_tag = u"alert-{tag}".format(tag=level_tag)
tags = [alert_level_tag]
extra_tags = force_text(message.extra_tags, strings_only=True)
if extra_tags:
tags.append(extra_tags)
return u" ".join(tags)
|
from django import template
from django.contrib.messages.utils import get_level_tags
LEVEL_TAGS = get_level_tags()
register = template.Library()
@register.simple_tag()
def get_message_tags(message):
"""
Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix
along with any tags included in message.extra_tags
Messages in Django >= 1.7 have a message.level_tag attr
"""
level_tag = LEVEL_TAGS[message.level]
if level_tag == u"error":
level_tag = u"danger"
alert_level_tag = u"alert-{tag}".format(tag=level_tag)
tags = [alert_level_tag]
if message.extra_tags:
tags.append(message.extra_tags)
return u" ".join(tags)
|
Add packageName variable and fix styleguide location
|
// TODO: Make options linear.
// Would make configuration more user friendly.
'use strict'
var path = require('path')
var packageName = 'chewingum'
module.exports = function (options) {
function n (pathString) {
return path.normalize(pathString)
}
var opts = options || {}
opts.location = (opts.location) ? opts.location : {}
opts.extensions = (opts.extensions) ? opts.extensions : {}
opts.location.root = n(opts.location.root || '/')
opts.location.src = n(opts.location.src || 'src/components/')
opts.location.dest = n(opts.location.dest || 'dest/components/')
opts.location.styleguide = n(opts.location.styleguide || 'node_modules/' + packageName + '/doc-template/')
opts.extensions.template = opts.extensions.template || '.twig'
opts.extensions.output = opts.extensions.output || '.html'
return opts
}
|
'use strict'
// var console = require('better-console')
var path = require('path')
module.exports = function (options) {
function n (pathString) {
return path.normalize(pathString)
}
var opts = options || {}
opts.location = (opts.location) ? opts.location : {}
opts.extensions = (opts.extensions) ? opts.extensions : {}
opts.location.root = n(opts.location.root || '/')
opts.location.src = n(opts.location.src || 'src/components/')
opts.location.dest = n(opts.location.dest || 'dest/components/')
opts.location.styleguide = n(opts.location.styleguide || 'node_modules/component-library-core/doc-template/')
opts.extensions.template = opts.extensions.template || '.twig'
opts.extensions.output = opts.extensions.output || '.html'
// console.warn(opts)
return opts
}
|
Use native Map instead of plain object
Also reduce the use of lodash
|
class TextLocationRegistry {
constructor() {
this._recordMap = new Map();
}
register({editorId, decorationId, ranges}) {
const editorDecorations = this._recordMap.get(editorId) || new Map();
editorDecorations.set(decorationId, ranges);
this._recordMap.set(editorId, editorDecorations);
}
deregister(decorationId) {
Array.from(this._recordMap.values()).forEach(decorationIdMap => {
decorationIdMap.delete(decorationId);
});
}
queryDecorationId({editorId, offset}) {
const decorationMap = this._recordMap.get(editorId);
if (!decorationMap) return null;
const [decorationId] = Array.from(decorationMap.entries())
.find(([_decorationId, ranges]) =>
ranges.some(range => range.start <= offset && offset <= range.end)
) || [];
return decorationId || null;
}
}
module.exports = TextLocationRegistry;
|
const _ = require('lodash');
class TextLocationRegistry {
constructor() {
this._recordMap = {};
}
register({editorId, decorationId, ranges}) {
const editorDecorations = Object.assign(
{},
this._recordMap[editorId],
{[decorationId]: ranges}
);
Object.assign(
this._recordMap,
{[editorId]: editorDecorations}
);
}
deregister(decorationId) {
_.forEach(this._recordMap, decorationIdMap => {
if (decorationIdMap[decorationId]) {
decorationIdMap[decorationId] = null;
}
});
}
queryDecorationId({editorId, offset}) {
const decorationMap = this._recordMap[editorId];
const decorationId = _.findKey(decorationMap, ranges =>
_.some(ranges, range => range.start <= offset && offset <= range.end)
);
return decorationId || null;
}
}
module.exports = TextLocationRegistry;
|
Add linear filter on image little planet texture
|
( function () {
/**
* Image Little Planet
* @param {string} source - URL for the image source
* @param {number} [size=10000] - Size of plane geometry
* @param {number} [ratio=0.5] - Ratio of plane geometry's height against width
*/
PANOLENS.ImageLittlePlanet = function ( source, size, ratio ) {
PANOLENS.LittlePlanet.call( this, 'image', source, size, ratio );
};
PANOLENS.ImageLittlePlanet.prototype = Object.create( PANOLENS.LittlePlanet.prototype );
PANOLENS.ImageLittlePlanet.prototype.constructor = PANOLENS.ImageLittlePlanet;
PANOLENS.ImageLittlePlanet.prototype.onLoad = function ( texture ) {
this.updateTexture( texture );
PANOLENS.ImagePanorama.prototype.onLoad.call( this, texture );
PANOLENS.LittlePlanet.prototype.onLoad.call( this );
};
PANOLENS.ImageLittlePlanet.prototype.updateTexture = function ( texture ) {
texture.minFilter = texture.magFilter = THREE.LinearFilter;
this.material.uniforms[ "tDiffuse" ].value = texture;
};
} )();
|
( function () {
/**
* Image Little Planet
* @param {string} source - URL for the image source
* @param {number} [size=10000] - Size of plane geometry
* @param {number} [ratio=0.5] - Ratio of plane geometry's height against width
*/
PANOLENS.ImageLittlePlanet = function ( source, size, ratio ) {
PANOLENS.LittlePlanet.call( this, 'image', source, size, ratio );
};
PANOLENS.ImageLittlePlanet.prototype = Object.create( PANOLENS.LittlePlanet.prototype );
PANOLENS.ImageLittlePlanet.prototype.constructor = PANOLENS.ImageLittlePlanet;
PANOLENS.ImageLittlePlanet.prototype.onLoad = function ( texture ) {
this.updateTexture( texture );
PANOLENS.ImagePanorama.prototype.onLoad.call( this, texture );
PANOLENS.LittlePlanet.prototype.onLoad.call( this );
};
PANOLENS.ImageLittlePlanet.prototype.updateTexture = function ( texture ) {
this.material.uniforms[ "tDiffuse" ].value = texture;
};
} )();
|
Clean up ios delete key test
Clean up ios delete key test
|
"use strict";
var setup = require("../../common/setup-base"),
desired = require('./desired'),
unorm = require('unorm');
describe('testapp - accented characters', function () {
var driver;
setup(this, desired).then(function (d) { driver = d; });
it('should send accented text', function (done) {
var testText = unorm.nfd("é Œ ù ḍ");
driver
.elementsByClassName('UIATextField').at(1)
.sendKeys(testText)
.text()
.should.become(testText)
.nodeify(done);
});
it('should send delete key', function (done) {
driver
.elementsByClassName('UIATextField').at(1)
.clear()
.sendKeys("abcd")
.sendKeys('\uE003\uE003')
.text()
.should.become("ab")
.nodeify(done);
});
});
|
"use strict";
var setup = require("../../common/setup-base"),
desired = require('./desired'),
unorm = require('unorm');
describe('testapp - accented characters', function () {
var driver;
setup(this, desired).then(function (d) { driver = d; });
it('should send accented text', function (done) {
var testText = unorm.nfd("é Œ ù ḍ");
driver
.elementsByClassName('UIATextField').at(1)
.sendKeys(testText)
.text()
.should.become(testText)
.nodeify(done);
});
it('should send delete key', function (done) {
driver
.elementsByClassName('UIATextField').at(1)
.clear()
.sendKeys("abc")
.sendKeys('\uE003\uE003\uE003')
.text()
.should.become("")
.nodeify(done);
});
});
|
Update and fix external history plugin
|
"use strict";
window.arethusaInitPlugin('external_history', function() {
/* global HistoryObj */
var obj = {
name: 'external_history',
arethusa: window.arethusaExternalApi(),
hist: new HistoryObj(2),
container: function() {
return $('#' + obj.name);
},
select: function(selector) {
return obj.container().find(selector);
},
renderHistory: function() {
var items = [];
$.each(obj.hist.elements, function(i, item) {
items.push('<li>' + JSON.stringify(item) + '</li>');
});
obj.select('#ext-hist-elements').html('<ul>' + items.join('') + '</ul>');
},
catchArethusaEvent: function(event) {
obj.hist.save(event);
obj.renderHistory();
},
apply: function() {
obj.arethusa.scope.$apply();
}
};
// Event handling code
$('#undo').click(function(e) {
obj.hist.undo();
obj.renderHistory();
obj.apply();
});
$('#redo').click(function(e) {
obj.hist.redo();
obj.renderHistory();
obj.apply();
});
return obj;
});
|
"use strict";
window.arethusaInitPlugin('external_history', function() {
/* global HistoryObj */
var obj = {
name: 'external_history',
api: window.arethusaExternalApi(),
hist: new HistoryObj(2),
container: function() {
return $('#' + obj.name);
},
select: function(selector) {
return obj.container().find(selector);
},
renderHistory: function() {
var items = [];
$.each(obj.hist.elements, function(i, item) {
items.push('<li>' + JSON.stringify(item) + '</li>');
});
obj.select('#ext-hist-elements').html('<ul>' + items.join('') + '</ul>');
},
catchArethusaEvent: function(event) {
obj.hist.save(event);
obj.renderHistory();
},
};
// Event handling code
$('#undo').click(function(e) {
obj.api.apply(obj.hist.undo());
obj.renderHistory();
});
$('#redo').click(function(e) {
obj.api.apply(obj.hist.redo());
obj.renderHistory();
});
return obj;
});
|
Use sqlalchemy 0.7.7 instead of 0.6
|
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='porick',
version='0.1',
description='',
author='',
author_email='',
url='',
install_requires=[
"Pylons>=1.0.1rc1",
"SQLAlchemy==0.7.7",
],
setup_requires=["PasteScript>=1.6.3"],
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
test_suite='nose.collector',
package_data={'porick': ['i18n/*/LC_MESSAGES/*.mo']},
#message_extractors={'porick': [
# ('**.py', 'python', None),
# ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}),
# ('public/**', 'ignore', None)]},
zip_safe=False,
paster_plugins=['PasteScript', 'Pylons'],
entry_points="""
[paste.app_factory]
main = porick.config.middleware:make_app
[paste.app_install]
main = pylons.util:PylonsInstaller
""",
)
|
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='porick',
version='0.1',
description='',
author='',
author_email='',
url='',
install_requires=[
"Pylons>=1.0.1rc1",
"SQLAlchemy==0.6.8",
],
setup_requires=["PasteScript>=1.6.3"],
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
test_suite='nose.collector',
package_data={'porick': ['i18n/*/LC_MESSAGES/*.mo']},
#message_extractors={'porick': [
# ('**.py', 'python', None),
# ('templates/**.mako', 'mako', {'input_encoding': 'utf-8'}),
# ('public/**', 'ignore', None)]},
zip_safe=False,
paster_plugins=['PasteScript', 'Pylons'],
entry_points="""
[paste.app_factory]
main = porick.config.middleware:make_app
[paste.app_install]
main = pylons.util:PylonsInstaller
""",
)
|
Remove the last occurence of PHP_EOL in a commented test and enabling it
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Code\Generator\TestAsset;
class TestClassWithManyProperties
{
const FOO = 'foo';
public static $fooStaticProperty = null;
/**
* @var bool
*/
public $fooProperty = true;
protected static $_barStaticProperty = 1;
protected $_barProperty = 1.1115;
private static $_bazStaticProperty = self::FOO;
private $_bazProperty = array(true, false, true);
protected $_complexType = array(
5,
'one' => 1,
'two' => '2',
array(
'bar',
'baz',
"\n"
)
);
}
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Code\Generator\TestAsset;
class TestClassWithManyProperties
{
const FOO = 'foo';
public static $fooStaticProperty = null;
/**
* @var bool
*/
public $fooProperty = true;
protected static $_barStaticProperty = 1;
protected $_barProperty = 1.1115;
private static $_bazStaticProperty = self::FOO;
private $_bazProperty = array(true, false, true);
protected $_complexType = array(
5,
'one' => 1,
'two' => '2',
array(
'bar',
'baz',
//PHP_EOL
)
);
}
|
Add unit test 0.1 + 0.2 = 0.3.
|
package com.github.verylargenumber;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static com.github.verylargenumber.VeryLargeNumber.add;
public class AddUnitTest {
@Test
public void addToNull() {
assertEquals("0", add(null, null));
assertEquals("12", add("12", null));
assertEquals("78", add("something dull", "78"));
}
@Test
public void probeAdd() {
assertEquals("-10023", add("-10002", "-21"));
assertEquals("456", add("12", "444"));
assertEquals("71945", add("72663", "-718"));
assertEquals("-495116", add("-500034", "4918"));
assertEquals("0", add("-0.23", "0.23"));
assertEquals("0.3", add("0.1", "0.2"));
assertEquals("7909.5991", add("7892.81", "16.7891"));
assertEquals("0.9999921796", add("-0.0000078204", "1"));
}
}
|
package com.github.verylargenumber;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static com.github.verylargenumber.VeryLargeNumber.add;
public class AddUnitTest {
@Test
public void addToNull() {
assertEquals("0", add(null, null));
assertEquals("12", add("12", null));
assertEquals("78", add("something dull", "78"));
}
@Test
public void probeAdd() {
assertEquals("-10023", add("-10002", "-21"));
assertEquals("456", add("12", "444"));
assertEquals("71945", add("72663", "-718"));
assertEquals("-495116", add("-500034", "4918"));
assertEquals("0", add("-0.23", "0.23"));
assertEquals("7909.5991", add("7892.81", "16.7891"));
assertEquals("0.9999921796", add("-0.0000078204", "1"));
}
}
|
Sort files before choosing one to upload
|
#!/usr/bin/python3
from __future__ import print_function
import os
import time
import subprocess
import sys
WAIT = 30
def main():
directory = sys.argv[1]
url = os.environ['RSYNC_URL']
while True:
fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz')))
if len(fnames):
fname = os.path.join(directory, fnames[0])
print("Uploading %r" % (fname,))
exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url])
if exit == 0:
print("Removing %r" % (fname,))
os.remove(fname)
else:
print("Nothing to upload")
print("Waiting %d seconds" % (WAIT,))
time.sleep(WAIT)
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
from __future__ import print_function
import os
import time
import subprocess
import sys
WAIT = 30
def main():
directory = sys.argv[1]
url = os.environ['RSYNC_URL']
while True:
fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))
if len(fnames):
fname = os.path.join(directory, fnames[0])
print("Uploading %r" % (fname,))
exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url])
if exit == 0:
print("Removing %r" % (fname,))
os.remove(fname)
else:
print("Nothing to upload")
print("Waiting %d seconds" % (WAIT,))
time.sleep(WAIT)
if __name__ == '__main__':
main()
|
Fix problem with navigating to static methods in the reference guide
|
var showing = null
function hashChange() {
var hash = decodeURIComponent(document.location.hash.slice(1))
var found = document.getElementById(hash), prefix, sect
if (found && (prefix = /^([^\.]+)/.exec(hash)) && (sect = document.getElementById("part_" + prefix[1]))) {
if (!sect.style.display) {
sect.style.display = "block"
if (showing) showing.style.display = ""
showing = sect
var rect = found.getBoundingClientRect()
window.scrollTo(0, hash == prefix[1] ? 0 : rect.top)
}
}
}
window.addEventListener("hashchange", hashChange)
hashChange()
if (!showing) {
showing = document.querySelector("section")
showing.style.display = "block"
}
var toc = document.querySelector("nav ul")
var openToc = null
for (var item = toc.firstChild; item; item = item.nextSibling) {
if (item.nodeName != "li") (function(item) {
item.addEventListener("click", function(e) {
if (openToc == item) return
if (openToc) openToc.className = ""
item.className = "toc_open"
openToc = item
})
}(item))
}
|
var showing = null
function hashChange() {
var hash = document.location.hash.slice(1)
var found = document.getElementById(hash), prefix, sect
if (found && (prefix = /^([^\.]+)/.exec(hash)) && (sect = document.getElementById("part_" + prefix[1]))) {
if (!sect.style.display) {
sect.style.display = "block"
if (showing) showing.style.display = ""
showing = sect
var rect = found.getBoundingClientRect()
window.scrollTo(0, hash == prefix[1] ? 0 : rect.top)
}
}
}
window.addEventListener("hashchange", hashChange)
hashChange()
if (!showing) {
showing = document.querySelector("section")
showing.style.display = "block"
}
var toc = document.querySelector("nav ul")
var openToc = null
for (var item = toc.firstChild; item; item = item.nextSibling) {
if (item.nodeName != "li") (function(item) {
item.addEventListener("click", function(e) {
if (openToc == item) return
if (openToc) openToc.className = ""
item.className = "toc_open"
openToc = item
})
}(item))
}
|
Put package name in QUnit header
|
/*globals QUnit spade */
require('jquery');
var qunit = require('./qunit');
var packageName = location.search.match(/package=([^&]+)&?/);
packageName = packageName && packageName[1];
var prefix = location.search.match(/prefix=([^&]+)&?/);
prefix = prefix && prefix[1];
if (!packageName) {
$('#qunit-header').text('Pass package=foo on URL to test package');
} else {
require(packageName);
$.extend(window, qunit);
QUnit.config.autostart = false;
QUnit.onload();
$('h1 > a').text(packageName);
QUnit.jsDump.setParser('object', function(obj) {
return obj.toString();
});
var runtime = spade["package"](packageName);
var files = runtime.files, file;
for(var i=0, l=files.length; i<l; i++) {
file = files[i];
if (file.match(/tests\/.*\.js$/)) {
if (!prefix || file.indexOf('tests/'+prefix)===0) {
require(packageName+"/~" + file);
}
}
}
}
|
/*globals QUnit spade */
require('jquery');
var qunit = require('./qunit');
var packageName = location.search.match(/package=([^&]+)&?/);
packageName = packageName && packageName[1];
var prefix = location.search.match(/prefix=([^&]+)&?/);
prefix = prefix && prefix[1];
if (!packageName) {
$('#qunit-header').text('Pass package=foo on URL to test package');
} else {
require(packageName);
$.extend(window, qunit);
QUnit.config.autostart = false;
QUnit.onload();
QUnit.jsDump.setParser('object', function(obj) {
return obj.toString();
});
var runtime = spade["package"](packageName);
var files = runtime.files, file;
for(var i=0, l=files.length; i<l; i++) {
file = files[i];
if (file.match(/tests\/.*\.js$/)) {
if (!prefix || file.indexOf('tests/'+prefix)===0) {
require(packageName+"/~" + file);
}
}
}
}
|
Fix bad console command path
|
<?php
namespace App\console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Console\Commands\QueryServerStatusesCommand;
use App\Console\Commands\ImportCommand;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
QueryServerStatusesCommand::class,
ImportCommand::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('query-servers:all')
->everyFiveMinutes();
$schedule->command('cleanup:password-reset')
->daily();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('app/console/Routes.php');
}
}
|
<?php
namespace App\console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\console\Commands\QueryServerStatusesCommand;
use App\console\Commands\ImportCommand;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
QueryServerStatusesCommand::class,
ImportCommand::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('query-servers:all')
->everyFiveMinutes();
$schedule->command('cleanup:password-reset')
->daily();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('app/Console/Routes.php');
}
}
|
Simplify state and save server URL
|
#!/usr/bin/env python
# encoding=utf8
import requests
from flexbe_core import EventState, Logger
class Wonderland_Request(EventState):
'''
Send requests to Wonderland server
># url string url to call
<= response string Finish job.
'''
def __init__(self):
# See example_state.py for basic explanations.
super(Wonderland_Request, self).__init__(outcomes=['done', 'error'],
input_keys=['url'],
output_keys=['response'])
self._header = {'api-key': 'asdf'}
def execute(self, userdata):
# This method is called periodically while the state is active.
# Main purpose is to check state conditions and trigger a corresponding outcome.
# If no outcome is returned, the state will stay active.
url = "http://192.168.0.46:8000/api/" + userdata.url
try:
response = requests.get(url, headers=self._header)
except requests.exceptions.RequestException as e:
print e
return 'error'
userdata.response = response.content
return 'done' # One of the outcomes declared above.
|
#!/usr/bin/env python
# encoding=utf8
import requests
from flexbe_core import EventState, Logger
class Wonderland_Request(EventState):
'''
MoveArm receive a ROS pose as input and launch a ROS service with the same pose
># url string url to call
<= response string Finish job.
'''
def __init__(self):
# See example_state.py for basic explanations.
super(Wonderland_Request, self).__init__(outcomes=['done', 'error'],
input_keys=['url'],
output_keys=['response'])
self._header = {'api-key': 'asdf'}
def execute(self, userdata):
# This method is called periodically while the state is active.
# Main purpose is to check state conditions and trigger a corresponding outcome.
# If no outcome is returned, the state will stay active.
try:
response = requests.get(userdata.url, headers=self._header)
except requests.exceptions.RequestException as e:
print e
return 'error'
userdata.response = response.content
return 'done' # One of the outcomes declared above.
|
Make Model available in main openmc namespace
|
from openmc.arithmetic import *
from openmc.cell import *
from openmc.checkvalue import *
from openmc.mesh import *
from openmc.element import *
from openmc.geometry import *
from openmc.nuclide import *
from openmc.macroscopic import *
from openmc.material import *
from openmc.plots import *
from openmc.region import *
from openmc.volume import *
from openmc.source import *
from openmc.settings import *
from openmc.surface import *
from openmc.universe import *
from openmc.lattice import *
from openmc.filter import *
from openmc.filter_expansion import *
from openmc.trigger import *
from openmc.tally_derivative import *
from openmc.tallies import *
from openmc.mgxs_library import *
from openmc.executor import *
from openmc.statepoint import *
from openmc.summary import *
from openmc.particle_restart import *
from openmc.mixin import *
from openmc.plotter import *
from openmc.search import *
from openmc.polynomial import *
from . import examples
# Import a few names from the model module
from openmc.model import rectangular_prism, hexagonal_prism, Model
__version__ = '0.13.0-dev'
|
from openmc.arithmetic import *
from openmc.cell import *
from openmc.checkvalue import *
from openmc.mesh import *
from openmc.element import *
from openmc.geometry import *
from openmc.nuclide import *
from openmc.macroscopic import *
from openmc.material import *
from openmc.plots import *
from openmc.region import *
from openmc.volume import *
from openmc.source import *
from openmc.settings import *
from openmc.surface import *
from openmc.universe import *
from openmc.lattice import *
from openmc.filter import *
from openmc.filter_expansion import *
from openmc.trigger import *
from openmc.tally_derivative import *
from openmc.tallies import *
from openmc.mgxs_library import *
from openmc.executor import *
from openmc.statepoint import *
from openmc.summary import *
from openmc.particle_restart import *
from openmc.mixin import *
from openmc.plotter import *
from openmc.search import *
from openmc.polynomial import *
from . import examples
# Import a few convencience functions that used to be here
from openmc.model import rectangular_prism, hexagonal_prism
__version__ = '0.13.0-dev'
|
Add third place in version number, why not
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup, find_packages
requires = ['cornice', 'mozsvc', 'powerhose', 'circus', 'wimms', 'PyBrowserID',
'metlog-py']
setup(name='tokenserver',
version='1.2.0',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points="""\
[paste.app_factory]
main = tokenserver:main
""",
install_requires=requires,
tests_require=requires,
test_suite='tokenserver.tests')
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from setuptools import setup, find_packages
requires = ['cornice', 'mozsvc', 'powerhose', 'circus', 'wimms', 'PyBrowserID',
'metlog-py']
setup(name='tokenserver',
version='1.2',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points="""\
[paste.app_factory]
main = tokenserver:main
""",
install_requires=requires,
tests_require=requires,
test_suite='tokenserver.tests')
|
Allow an onDone listener to be associated with a slot
|
'use strict';
var Node = require('./Node');
class Slot extends Node {
constructor(def) {
super('Slot');
this.onDone = def.onDone;
this.generatorSlot = null;
}
generateCode(generator) {
if (this.onDone) {
generator.onDone((generator) => {
this.onDone(this, generator);
});
}
// At the time the code for this node is to be generated we instead
// create a slot. A slot is just a marker in the output code stream
// that we can later inject code into. The injection happens after
// the entire tree has been walked.
this.generatorSlot = generator.beginSlot(this);
}
setContent(content) {
this.generatorSlot.setContent(content);
}
toJSON() {
return {
type: this.type
};
}
}
module.exports = Slot;
|
'use strict';
var Node = require('./Node');
class Slot extends Node {
constructor(def) {
super('Slot');
this.generatorSlot = null;
}
generateCode(generator) {
// At the time the code for this node is to be generated we instead
// create a slot. A slot is just a marker in the output code stream
// that we can later inject code into. The injection happens after
// the entire tree has been walked.
this.generatorSlot = generator.createSlot();
}
setContent(content) {
this.generatorSlot.setContent(content, {
statement: this.statement
});
}
toJSON() {
return {
type: this.type
};
}
}
module.exports = Slot;
|
Remove blank line that breaks cgo
|
package rc4
// #cgo LDFLAGS: -lcrypto
// #include <openssl/rc4.h>
import "C"
import (
"strconv"
)
type Cipher struct {
key *_Ctype_RC4_KEY
}
type KeySizeError int
func (k KeySizeError) Error() string {
return "rc4: invalid key size " + strconv.Itoa(int(k))
}
func NewCipher(key []byte) (*Cipher, error) {
k := len(key)
if k < 1 || k > 256 {
return nil, KeySizeError(k)
}
var c Cipher
c.key = &_Ctype_RC4_KEY{}
C.RC4_set_key(c.key, C.int(k), (*_Ctype_unsignedchar)(&key[0]))
return &c, nil
}
func (c *Cipher) XORKeyStream(dst, src []byte) {
C.RC4(c.key, C.size_t(len(dst)), (*_Ctype_unsignedchar)(&src[0]),
(*_Ctype_unsignedchar)(&dst[0]))
}
func (c *Cipher) Reset() {
for i := 0; i < 256; i++ {
c.key.data[i] = 0
}
c.key.x = 0
c.key.y = 0
}
|
package rc4
// #cgo LDFLAGS: -lcrypto
// #include <openssl/rc4.h>
import "C"
import (
"strconv"
)
type Cipher struct {
key *_Ctype_RC4_KEY
}
type KeySizeError int
func (k KeySizeError) Error() string {
return "rc4: invalid key size " + strconv.Itoa(int(k))
}
func NewCipher(key []byte) (*Cipher, error) {
k := len(key)
if k < 1 || k > 256 {
return nil, KeySizeError(k)
}
var c Cipher
c.key = &_Ctype_RC4_KEY{}
C.RC4_set_key(c.key, C.int(k), (*_Ctype_unsignedchar)(&key[0]))
return &c, nil
}
func (c *Cipher) XORKeyStream(dst, src []byte) {
C.RC4(c.key, C.size_t(len(dst)), (*_Ctype_unsignedchar)(&src[0]),
(*_Ctype_unsignedchar)(&dst[0]))
}
func (c *Cipher) Reset() {
for i := 0; i < 256; i++ {
c.key.data[i] = 0
}
c.key.x = 0
c.key.y = 0
}
|
Use better health check details
|
package com.simplerecipemanager.resources;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.codahale.metrics.annotation.Timed;
import com.codahale.metrics.health.HealthCheck.Result;
import com.codahale.metrics.health.HealthCheckRegistry;
@Path("/healthcheck")
public class HealthCheckResource {
private HealthCheckRegistry registry;
public HealthCheckResource(HealthCheckRegistry hcr) {
this.registry = hcr;
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Timed
public Response returnHealthCheck() {
Map<String, Result> hcResults = registry.runHealthChecks();
int fails = 0;
StringBuilder failureMessage = new StringBuilder();
for (Entry<String, Result> r : hcResults.entrySet()) {
if (!r.getValue().isHealthy()) {
failureMessage.append(String.format("%s message was %s", r.getKey(), r.getValue().getMessage()));
}
}
if (fails == 0) {
return Response.ok().entity("OK").build();
} else {
return Response.serverError().entity(failureMessage.toString()).build();
}
}
}
|
package com.simplerecipemanager.resources;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import com.codahale.metrics.health.HealthCheck.Result;
import com.codahale.metrics.health.HealthCheckRegistry;
@Path("/healthcheck")
public class HealthCheckResource {
private HealthCheckRegistry registry;
public HealthCheckResource(HealthCheckRegistry hcr) {
}
@GET
public Response returnHealthCheck() {
Map<String, Result> hcResults = registry.runHealthChecks();
for (Entry<String, Result> r : hcResults.entrySet()) {
if (!r.getValue().isHealthy()) {
return Response.serverError().entity(r.getValue().getMessage())
.build();
}
}
return Response.ok().build();
}
}
|
Update badge to show number of sensors currently in breach
|
import { generalStrings } from '../localization';
import { UIDatabase } from '../database';
const routeList = {
customerRequisitions: 'ResponseRequisition',
supplierRequisitions: 'RequestRequisition',
supplierInvoices: 'SupplierInvoice',
stocktakes: 'Stocktake',
customerInvoices: 'CustomerInvoice',
vaccines: 'Sensor',
};
const getBadgeData = routeName => {
const dataType = routeName in routeList ? routeList[routeName] : '';
switch (dataType) {
case 'Sensor': {
return [
{
count: UIDatabase.objects(dataType).filter(
sensor => sensor.isInHotBreach || sensor.isInColdBreach
).length,
title: `${generalStrings.unacknowledged} ${generalStrings[routeName]}`,
},
];
}
default:
return [
{
count: dataType
? UIDatabase.objects(dataType).filtered('status != "finalised"').length
: 0,
title: `${generalStrings.unfinalised} ${generalStrings[routeName]}`,
},
];
}
};
export default getBadgeData;
export { getBadgeData };
|
import { generalStrings } from '../localization';
import { UIDatabase } from '../database';
const routeList = {
customerRequisitions: 'ResponseRequisition',
supplierRequisitions: 'RequestRequisition',
supplierInvoices: 'SupplierInvoice',
stocktakes: 'Stocktake',
customerInvoices: 'CustomerInvoice',
vaccines: 'TemperatureBreach',
};
const getBadgeData = routeName => {
const dataType = routeName in routeList ? routeList[routeName] : '';
switch (dataType) {
case 'TemperatureBreach':
return [
{
count: UIDatabase.objects(dataType).filtered('acknowledged == false').length,
title: `${generalStrings.unacknowledged} ${generalStrings[routeName]}`,
},
];
default:
return [
{
count: dataType
? UIDatabase.objects(dataType).filtered('status != "finalised"').length
: 0,
title: `${generalStrings.unfinalised} ${generalStrings[routeName]}`,
},
];
}
};
export default getBadgeData;
export { getBadgeData };
|
Refactor async wrapper. Use asyncio.run() for Py3.7
|
import asyncio
import functools
import inspect
import sys
from rollbar.contrib.asgi import ASGIApp
def run(coro):
if sys.version_info >= (3, 7):
return asyncio.run(coro)
assert inspect.iscoroutine(coro)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
asyncio.set_event_loop(None)
def wrap_async(asyncfunc):
@functools.wraps(asyncfunc)
def wrapper(*args, **kwargs):
run(asyncfunc(*args, **kwargs))
return wrapper
@ASGIApp
class FailingTestASGIApp:
def __init__(self):
self.asgi_app = wrap_async(self.asgi_app)
async def app(self, scope, receive, send):
raise RuntimeError("Invoked only for testing")
|
import asyncio
import functools
from rollbar.contrib.asgi import ASGIApp
def async_test_func_wrapper(asyncfunc):
@functools.wraps(asyncfunc)
def wrapper(*args, **kwargs):
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(asyncfunc(*args, **kwargs))
finally:
loop.close()
else:
loop.run_until_complete(asyncfunc(*args, **kwargs))
return wrapper
@ASGIApp
class FailingTestASGIApp:
def __init__(self):
self.asgi_app = async_test_func_wrapper(self.asgi_app)
async def app(self, scope, receive, send):
raise RuntimeError("Invoked only for testing")
|
Add frontend side of cookie auth
|
var User = function(baseUrl) {
var self = this;
this.baseUrl = baseUrl;
this.username = '';
this.password = '';
this.errorThrown = '';
this.onAuthUpdate = function() {
// This cookie is set when the login API call returns 200.
// As we may be running on a different domain, we ensure this cookie is used
// by setting it ourselves.
self.isAuthenticated = ($.cookie('sessionid') !== undefined);
};
this.onAuthUpdate();
ko.track(this);
}
User.prototype = Object.create(Object.prototype);
User.prototype.login = function(success) {
var self = this;
$.ajax({
url: this.baseUrl + '/data/login',
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({user: this.username, password: this.password}),
error: function(xhr, _, errorThrown) {
self.errorThrown = xhr.status + ': ' + xhr.responseText;
self.onAuthUpdate();
},
success: function() {
self.password = '';
self.errorThrown = '';
if (!$.cookie('sessionid')) {
$.cookie('sessionid', true);
}
self.onAuthUpdate();
success();
}
});
this.password = '';
this.errorThrown = '';
}
|
var User = function(baseUrl) {
var self = this;
this.baseUrl = baseUrl;
this.username = '';
this.password = '';
this.errorThrown = '';
this.onAuthUpdate = function() {
// as long as the frontend and backend are served from different domains,
// this doesn't work, as we can't access the backend's cookie.
// An alternative would be to introduce a REST endpoint to check for
// authentication status.
self.isAuthenticated = ($.cookie('sessionid') !== undefined);
};
this.onAuthUpdate();
ko.track(this);
}
User.prototype = Object.create(Object.prototype);
User.prototype.login = function(success) {
var self = this;
$.ajax({
url: this.baseUrl + '/data/login',
type: 'POST',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({user: this.username, password: this.password}),
error: function(xhr, _, errorThrown) {
self.errorThrown = xhr.status + ': ' + xhr.responseText;
self.onAuthUpdate();
},
success: function() {
self.password = '';
self.errorThrown = '';
self.onAuthUpdate();
success();
}
});
this.password = '';
this.errorThrown = '';
}
|
Update count fields on RawDataVersionAdmin
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom administration panels for tracking models.
"""
from __future__ import unicode_literals
from django.contrib import admin
from calaccess_raw import models
from .base import BaseAdmin
@admin.register(models.RawDataVersion)
class RawDataVersionAdmin(BaseAdmin):
"""
Custom admin for the RawDataVersion model.
"""
list_display = (
"id",
"release_datetime",
"pretty_download_size",
"download_file_count",
"download_record_count",
"clean_file_count",
"clean_record_count",
"pretty_clean_size",
)
list_display_links = ('release_datetime',)
list_filter = ("release_datetime",)
@admin.register(models.RawDataFile)
class RawDataFileAdmin(BaseAdmin):
"""
Custom admin for the RawDataFile model.
"""
list_display = (
"id",
"version",
"file_name",
"download_records_count",
"clean_records_count",
"load_records_count",
"error_count"
)
list_display_links = ('id', 'file_name',)
list_filter = ("version__release_datetime",)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom administration panels for tracking models.
"""
from __future__ import unicode_literals
from django.contrib import admin
from calaccess_raw import models
from .base import BaseAdmin
@admin.register(models.RawDataVersion)
class RawDataVersionAdmin(BaseAdmin):
"""
Custom admin for the RawDataVersion model.
"""
list_display = (
"id",
"release_datetime",
"pretty_download_size",
"file_count",
"record_count",
"pretty_clean_size",
)
list_display_links = ('release_datetime',)
list_filter = ("release_datetime",)
@admin.register(models.RawDataFile)
class RawDataFileAdmin(BaseAdmin):
"""
Custom admin for the RawDataFile model.
"""
list_display = (
"id",
"version",
"file_name",
"download_records_count",
"clean_records_count",
"load_records_count",
"error_count"
)
list_display_links = ('id', 'file_name',)
list_filter = ("version__release_datetime",)
|
Switch browserify back to debugging mode.
|
'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, {read: true})
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
return gulp.src(paths.app + '/js/main.js', { read: false })
.pipe($.browserify({
transform: [istanbul],
debug: true
}))
.pipe(gulp.dest(paths.tmp + '/js'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
|
'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, {read: true})
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
return gulp.src(paths.app + '/js/main.js', { read: false })
.pipe($.browserify({
transform: [istanbul],
debug: false
}))
.pipe(gulp.dest(paths.tmp + '/js'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
|
Fix search sorting so that a search result never has "undefined" plays or favorities. This could break sorting in unexpected ways. E.g. Katy Perry shows plays but favorites on YouTube. It is better to simply avoid the use of undefined variables.
|
var _ = require('underscore')._;
function SearchResult(options) {
_.extend(this, _.pick(options,
'url', 'permalink', 'siteMediaID',
'siteCode', 'icon', 'author',
'mediaName', 'duration', 'type'));
var stats = {querySimilarity: 1, playRelevance: 1, favoriteRelevance: 1, relevance: 0.5};
stats = _.extend(stats, _.pick(options, 'plays', 'favorites'));
stats.plays = parseInt(stats.plays) || 0;
stats.favorites = parseInt(stats.favorites) || 0;
stats.querySimilarity = 1;
stats.playRelevance = 1;
stats.favoriteRelevance = 1;
this.stats = stats;
}
SearchResult.prototype = {
calculateRelevance: function() {
var lambdaPlays = 0.70,
lambdaFavorites = 0.30,
playRelevance = lambdaPlays * this.stats.playRelevance,
favRelevance = lambdaFavorites * this.stats.favoriteRelevance;
//console.log(playRelevance, favRelevance);
this.stats.relevance = (playRelevance + favRelevance) * this.stats.querySimilarity;
}
};
module.exports = {
SearchResult: SearchResult
}
|
var _ = require('underscore')._;
function SearchResult(options) {
_.extend(this, _.pick(options,
'url', 'permalink', 'siteMediaID',
'siteCode', 'icon', 'author',
'mediaName', 'duration', 'type'));
var stats = {querySimilarity: 1, playRelevance: 1, favoriteRelevance: 1, relevance: 0.5};
stats = _.extend(stats, _.pick(options, 'plays', 'favorites'));
stats.plays = parseInt(stats.plays) || undefined;
stats.favorites = parseInt(stats.favorites) || undefined;
stats.querySimilarity = 1;
stats.playRelevance = 1;
stats.favoriteRelevance = 1;
this.stats = stats;
}
SearchResult.prototype = {
calculateRelevance: function() {
var lambdaPlays = 0.70,
lambdaFavorites = 0.30,
playRelevance = lambdaPlays * this.stats.playRelevance,
favRelevance = lambdaFavorites * this.stats.favoriteRelevance;
//console.log(playRelevance, favRelevance);
this.stats.relevance = (playRelevance + favRelevance) * this.stats.querySimilarity;
}
};
module.exports = {
SearchResult: SearchResult
}
|
Change the api.update_status() call to explicitly state the 'status' message.
- A recent version of Tweepy required it to be explicit, no harm in always being so
|
#!/usr/bin/env python
# twitterfunctions.py
# description: This file contains all the functions that are used when connecting to Twitter. Almost all of them rely on Tweepy
# copyrigtht: 2015 William Patton - PattonWebz
# licence: GPLv3
import tweepy
def authenticatetwitter(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET):
# Authenticate with Twitter using keys and secrets and return
# an 'api' object
# Authorize with consumer credentials and get an access token
# with access credentials
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
# get an authenticated instance of the API class
api = tweepy.API(auth)
# return API object 'api'
return api
def sendtweet(api, tweet):
# Send 'tweet' using Tweepy API function
api.update_status(status=tweet)
|
#!/usr/bin/env python
# twitterfunctions.py
# description: This file contains all the functions that are used when connecting to Twitter. Almost all of them rely on Tweepy
# copyrigtht: 2015 William Patton - PattonWebz
# licence: GPLv3
import tweepy
def authenticatetwitter(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET):
# Authenticate with Twitter using keys and secrets and return
# an 'api' object
# Authorize with consumer credentials and get an access token
# with access credentials
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
# get an authenticated instance of the API class
api = tweepy.API(auth)
# return API object 'api'
return api
def sendtweet(api, tweet):
# Send 'tweet' using Tweepy API function
api.update_status(tweet)
|
Move Gogland report higher up list because it couldn’t be used.
|
package reporters
import (
"os/exec"
"github.com/approvals/go-approval-tests/utils"
)
// NewFrontLoadedReporter creates the default front loaded reporter.
func NewFrontLoadedReporter() *Reporter {
tmp := NewFirstWorkingReporter(
NewContinuousIntegrationReporter(),
)
return &tmp
}
// NewDiffReporter creates the default diff reporter.
func NewDiffReporter() *Reporter {
tmp := NewFirstWorkingReporter(
NewBeyondCompareReporter(),
NewIntelliJReporter(),
NewGoGlandReporter(),
NewPrintSupportedDiffProgramsReporter(),
NewQuietReporter(),
)
return &tmp
}
func launchProgram(programName, approved string, args ...string) bool {
if !utils.DoesFileExist(programName) {
return false
}
utils.EnsureExists(approved)
cmd := exec.Command(programName, args...)
cmd.Start()
return true
}
|
package reporters
import (
"os/exec"
"github.com/approvals/go-approval-tests/utils"
)
// NewFrontLoadedReporter creates the default front loaded reporter.
func NewFrontLoadedReporter() *Reporter {
tmp := NewFirstWorkingReporter(
NewContinuousIntegrationReporter(),
)
return &tmp
}
// NewDiffReporter creates the default diff reporter.
func NewDiffReporter() *Reporter {
tmp := NewFirstWorkingReporter(
NewBeyondCompareReporter(),
NewIntelliJReporter(),
NewPrintSupportedDiffProgramsReporter(),
NewQuietReporter(),
NewGoGlandReporter(),
)
return &tmp
}
func launchProgram(programName, approved string, args ...string) bool {
if !utils.DoesFileExist(programName) {
return false
}
utils.EnsureExists(approved)
cmd := exec.Command(programName, args...)
cmd.Start()
return true
}
|
Remove unused byName @SecondaryKey from ApprovalCategory
Change-Id: Ic00e7fcd48f206f16d49b96dc4890c5ae3dc7252
Signed-off-by: Shawn O. Pearce <f3ea74d906fa9fe97c1fef6bad9cb871485c7045@google.com>
|
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb;
import com.google.gwtorm.client.Access;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.PrimaryKey;
import com.google.gwtorm.client.Query;
import com.google.gwtorm.client.ResultSet;
public interface ApprovalCategoryAccess extends
Access<ApprovalCategory, ApprovalCategory.Id> {
@PrimaryKey("categoryId")
ApprovalCategory get(ApprovalCategory.Id id) throws OrmException;
@Query("ORDER BY position, name")
ResultSet<ApprovalCategory> all() throws OrmException;
}
|
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb;
import com.google.gwtorm.client.Access;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.PrimaryKey;
import com.google.gwtorm.client.Query;
import com.google.gwtorm.client.ResultSet;
import com.google.gwtorm.client.SecondaryKey;
public interface ApprovalCategoryAccess extends
Access<ApprovalCategory, ApprovalCategory.Id> {
@PrimaryKey("categoryId")
ApprovalCategory get(ApprovalCategory.Id id) throws OrmException;
@SecondaryKey("name")
ApprovalCategory byName(String name) throws OrmException;
@Query("ORDER BY position, name")
ResultSet<ApprovalCategory> all() throws OrmException;
}
|
Add an accessor for the SecurityClassification enum.
|
/**
* Copyright (c) Codice Foundation
*
* This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or 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
* Lesser General Public License for more details. A copy of the GNU Lesser General Public License
* is distributed along with this program and can be found at
* <http://www.gnu.org/licenses/lgpl.html>.
*
**/
package org.codice.nitf.filereader;
public enum NitfSecurityClassification
{
UNKNOWN (""),
UNCLASSIFIED ("U"),
RESTRICTED ("R"),
CONFIDENTIAL ("C"),
SECRET ("S"),
TOP_SECRET ("T");
private final String textEquivalent;
NitfSecurityClassification(String abbreviation) {
this.textEquivalent = abbreviation;
}
static public NitfSecurityClassification getEnumValue(String textEquivalent) {
for (NitfSecurityClassification classification : values()) {
if (textEquivalent.equals(classification.textEquivalent)) {
return classification;
}
}
return UNKNOWN;
}
public String getTextEquivalent() {
return textEquivalent;
}
};
|
/**
* Copyright (c) Codice Foundation
*
* This is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or 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
* Lesser General Public License for more details. A copy of the GNU Lesser General Public License
* is distributed along with this program and can be found at
* <http://www.gnu.org/licenses/lgpl.html>.
*
**/
package org.codice.nitf.filereader;
public enum NitfSecurityClassification
{
UNKNOWN (""),
UNCLASSIFIED ("U"),
RESTRICTED ("R"),
CONFIDENTIAL ("C"),
SECRET ("S"),
TOP_SECRET ("T");
private final String textEquivalent;
NitfSecurityClassification(String abbreviation) {
this.textEquivalent = abbreviation;
}
static public NitfSecurityClassification getEnumValue(String textEquivalent) {
for (NitfSecurityClassification classification : values()) {
if (textEquivalent.equals(classification.textEquivalent)) {
return classification;
}
}
return UNKNOWN;
}
};
|
Fix bug with daily forecast
|
import React from 'react';
const Daily = ({ weather }) => {
const daily = weather[0].forecast.simpleforecast.forecastday;
const nextTen = daily.filter((day, i) => {
return i > 0;
});
return (
<section className='extended-forecast'>
<h3 className='title'>10 Day Forecast</h3>
<div className='daily-forecast'>
{nextTen.map((day, i) => {
return (
<div className='day' key={i}>
<p>{day.date.weekday_short}</p>
<img className='icon-small' src={day.icon_url}/>
<p className='range'>{day.high.fahrenheit}° | {day.low.fahrenheit}°</p>
</div>
);
})}
</div>
</section>
);
};
export default Daily;
|
import React from 'react';
const Daily = ({ weather }) => {
const daily = weather[0].forecast.simpleforecast.forecastday;
daily.shift();
return (
<section className='extended-forecast'>
<h3 className='title'>10 Day Forecast</h3>
<div className='daily-forecast'>
{daily.map((day, i) => {
return (
<div className='day' key={i}>
<p>{day.date.weekday_short}</p>
<img className='icon-small' src={day.icon_url}/>
<p className='range'>{day.high.fahrenheit}° | {day.low.fahrenheit}°</p>
</div>
);
})}
</div>
</section>
);
};
export default Daily;
|
Improve help text of registry server opts
Partial-Bug: #1570946
Change-Id: Iad255d3ab5d96b91f897731f4f29cd804d6b1840
|
# Copyright 2010-2011 OpenStack Foundation
# 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.
"""
Registry API
"""
from oslo_config import cfg
from glance.i18n import _
registry_addr_opts = [
cfg.StrOpt('registry_host', default='0.0.0.0',
help=_("""
Address the registry server is hosted on.
Possible values:
* A valid IP or hostname
Related options:
* None
""")),
cfg.PortOpt('registry_port', default=9191,
help=_("""
Port the registry server is listening on.
Possible values:
* A valid port number
Related options:
* None
""")),
]
CONF = cfg.CONF
CONF.register_opts(registry_addr_opts)
|
# Copyright 2010-2011 OpenStack Foundation
# 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.
"""
Registry API
"""
from oslo_config import cfg
from glance.i18n import _
registry_addr_opts = [
cfg.StrOpt('registry_host', default='0.0.0.0',
help=_('Address to find the registry server.')),
cfg.PortOpt('registry_port', default=9191,
help=_('Port the registry server is listening on.')),
]
CONF = cfg.CONF
CONF.register_opts(registry_addr_opts)
|
Implement a search test for when there is no matching template
|
# -*- coding: utf-8 -*-
import pathlib
import json
import pytest
@pytest.fixture
def templates_file():
return 'tests/templates.json'
def scenarios():
yield ['django', 'docker'], ['cookiecutter-django']
yield ['pytest'], [
'cookiecutter-pylibrary',
'cookiecutter-pypackage',
'cookiecutter-pytest-plugin',
]
yield ['api'], ['cookiecutter-tapioca']
@pytest.mark.parametrize('tags, templates', scenarios())
def test_search_templates(cli_runner, tmp_rc, templates_file, tags, templates):
result = cli_runner([
'-c', tmp_rc, 'search', '--load-file', templates_file, *tags
])
assert result.exit_code == 0
for template in templates:
assert template in result.output
def test_search_cant_find_match(cli_runner, tmp_rc, templates_file):
result = cli_runner([
'-c', tmp_rc, 'search', '--load-file', templates_file, 'NopeNopeNope'
])
assert result.exit_code == 0
assert 'No match for "NopeNopeNope"' in result.output
|
# -*- coding: utf-8 -*-
import pathlib
import json
import pytest
@pytest.fixture
def templates_file():
return 'tests/templates.json'
def scenarios():
yield ['django', 'docker'], ['cookiecutter-django']
yield ['pytest'], [
'cookiecutter-pylibrary',
'cookiecutter-pypackage',
'cookiecutter-pytest-plugin',
]
yield ['api'], ['cookiecutter-tapioca']
@pytest.mark.parametrize('tags, templates', scenarios())
def test_search_templates(cli_runner, tmp_rc, templates_file, tags, templates):
result = cli_runner([
'-c', tmp_rc, 'search', '--load-file', templates_file, *tags
])
assert result.exit_code == 0
for template in templates:
assert template in result.output
|
Load orgs inside location promise
|
import React, { Component } from 'react'
import globalConfig from '../../config'
import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI'
import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import Location from '../../components/Location'
export default class LocationPage extends Component {
constructor(props) {
super(props)
this.state = {
location: null,
organization: null,
}
}
componentDidMount() {
const match = this.props.route.pattern.exec(window.location.pathname)
const locationId = match[1]
fetchLocation(locationId)
.then(location => {
this.setState({ location })
fetchOrganization(location.organizationId)
.then(organization => {
this.setState({ organization })
})
})
}
componentDidUpdate() {
const { location } = this.state
document.title = location ? location.name : globalConfig.title
}
render() {
const { location, organization } = this.state
return (
<Layout>
{(location && organization) ?
<Location location={location} organization={organization} /> :
<Loading />
}
</Layout>
)
}
}
|
import React, { Component } from 'react'
import globalConfig from '../../config'
import { fetchLocation, fetchOrganization } from '../../core/firebaseRestAPI'
import Layout from '../../components/Layout'
import Loading from '../../components/Loading'
import Location from '../../components/Location'
export default class LocationPage extends Component {
constructor(props) {
super(props)
this.state = {
location: null,
organization: null,
}
}
componentDidMount() {
const match = this.props.route.pattern.exec(window.location.pathname)
const locationId = match[1]
fetchLocation(locationId)
.then(location => {
this.setState({ location })
})
fetchOrganization(location.organizationId)
.then(organization => {
this.setState({ organization })
})
}
componentDidUpdate() {
const { location } = this.state
document.title = location ? location.name : globalConfig.title
}
render() {
const { location, organization } = this.state
return (
<Layout>
{(location && organization) ?
<Location location={location} organization={organization} /> :
<Loading />
}
</Layout>
)
}
}
|
Use the Link component from react-router in combination with our custom styled Link
|
import React, { PureComponent } from 'react';
import { Link, Heading1, Section } from '../../components/';
import { BrowserRouter as Router, Link as ReactRouterLink } from 'react-router-dom';
Link.use(ReactRouterLink);
class LinkTest extends PureComponent {
handleClick = () => {
console.log('Clicked on a link');
};
render () {
return (
<Router>
<article>
<Section color="neutral" dark>
<Heading1>Links</Heading1>
</Section>
<div className="component-spec">
<div className="preview">
<p><Link to="http://www.facebook.com" target="_blank">I'm an external link</Link></p>
<p><Link to="#" onClick={this.handleClick}>I'm an internal link</Link></p>
</div>
</div>
</article>
</Router>
);
}
}
export default LinkTest;
|
import React, { PureComponent } from 'react';
import Link from '../../components/link';
class LinkTest extends PureComponent {
handleClick = () => {
console.log('Clicked on a link');
};
render () {
return (
<article>
<header>
<h1>Links</h1>
</header>
<div className="component-spec">
<div className="preview">
<p><Link url="#">I'm a link</Link></p>
<p><Link onClick={this.handleClick}>I'm a link</Link></p>
</div>
</div>
</article>
);
}
}
export default LinkTest;
|
fix: Add default case and fix help/version flag
|
package main
import (
"flag"
"fmt"
"github.com/cristianoliveira/ergo/commands"
"github.com/cristianoliveira/ergo/proxy"
"os"
)
const VERSION = "0.0.4"
const USAGE = `
Ergo proxy.
The local proxy agent for multiple services development.
Usage:
ergo [options]
ergo run [options]
ergo list
Options:
-h Shows this message.
-v Shows ergs's version.
`
func main() {
var command string = "run"
if len(os.Args) > 1 {
command = os.Args[1]
}
help := flag.Bool("h", false, "Shows ergs's help.")
version := flag.Bool("v", false, "Shows ergs's version.")
flag.Parse()
if *help {
fmt.Println(USAGE)
os.Exit(0)
}
if *version {
fmt.Println(VERSION)
os.Exit(0)
}
config := proxy.LoadConfig("./.ergo")
switch command {
case "list":
commands.List(config)
os.Exit(0)
case "run":
commands.Run(config)
default:
fmt.Println(USAGE)
os.Exit(0)
}
}
|
package main
import (
"flag"
"fmt"
"github.com/cristianoliveira/ergo/commands"
"github.com/cristianoliveira/ergo/proxy"
"os"
)
const VERSION = "0.0.4"
const USAGE = `
Ergo proxy.
The local proxy agent for multiple services development.
Usage:
ergo [options]
ergo run [options]
ergo list
Options:
-h Shows this message.
-v Shows ergs's version.
`
func main() {
var command string = "run"
if len(os.Args) > 1 {
command = os.Args[1]
}
help := flag.Bool("-h", false, "Shows ergs's help.")
version := flag.Bool("-v", false, "Shows ergs's version.")
flag.Parse()
if *help {
fmt.Println(USAGE)
os.Exit(0)
}
if *version {
fmt.Println(VERSION)
os.Exit(0)
}
config := proxy.LoadConfig("./.ergo")
switch command {
case "list":
commands.List(config)
os.Exit(0)
case "run":
commands.Run(config)
}
}
|
Use MutationObserver API to catch dom updates
|
function hide_covers() {
// Remove covers
$(".mix_element div.cover").remove()
// Add class so cards can be restyled
$(".mix_card.half_card").addClass("ext-coverless_card")
// Remove covers on track page
$("#cover_art").remove()
// Remove covers in the sidebar of a track page
$(".card.sidebar_mix .cover").remove()
$(".card.sidebar_mix").addClass("ext-coverless_card")
}
function filter() {
chrome.storage.local.get("state", function(result) {
if(result["state"] == "on") {
hide_covers()
}
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
var observer = new MutationObserver(filter)
observer.observe(document.getElementById("main"), {childList: true, subtree: true})
filter();
|
function hide_covers() {
// Remove covers
$(".mix_element div.cover").remove()
// Add class so cards can be restyled
$(".mix_card.half_card").addClass("ext-coverless_card")
// Remove covers on track page
$("#cover_art").remove()
// Remove covers in the sidebar of a track page
$(".card.sidebar_mix .cover").remove()
$(".card.sidebar_mix").addClass("ext-coverless_card")
}
function filter() {
chrome.storage.local.get("state", function(result) {
if(result["state"] == "on") {
hide_covers()
}
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
$('#body_container').bind('DOMSubtreeModified',filter);
filter();
|
Add option to deploy specific branch/tag which defaults to master
|
/*
@method gitPull
Takes a flightplan instance and transport
@param remote {Object} Flightplan transport instance
@param webRoot {string} path to run git pull on the remote server
@param [gitIdentifier=master] {string} branch/tag/commit identifier
e.g. /var/www/project
*/
var gitPull = function (remote, webRoot, gitIdentifier) {
// git pull
var gitIdentifier = gitIdentifier || 'master';
remote.with('cd ' + webRoot, function() {
remote.exec('git pull');
remote.exec('git checkout ' + gitIdentifier);
});
};
/*
@method addToPlan
Takes a flightplan instance and adds a task called gitDeploy
@param plan {Object} Flightplan instance
@param plan.runtime.options.webRoot {String} Remote path to run git pull
*/
var addToPlan = function (plan) {
// Task to git deploy via ssh remote
plan.remote('gitDeploy', function(remote) {
var webRoot = plan.runtime.options.webRoot;
gitPull(remote, webRoot);
});
};
module.exports = {
addToPlan: addToPlan,
gitPull: gitPull
};
|
/*
@method gitPull
Takes a flightplan instance and transport
@param remote {Object} Flightplan transport instance
@param webRoot {string} path to run git pull on the remote server
e.g. /var/www/project
*/
var gitPull = function (remote, webRoot) {
// git pull
remote.with('cd ' + webRoot, function() {
remote.exec('git pull');
});
};
/*
@method addToPlan
Takes a flightplan instance and adds a task called gitDeploy
@param plan {Object} Flightplan instance
@param plan.runtime.options.webRoot {String} Remote path to run git pull
*/
var addToPlan = function (plan) {
// Task to git deploy via ssh remote
plan.remote('gitDeploy', function(remote) {
var webRoot = plan.runtime.options.webRoot;
gitPull(remote, webRoot);
});
};
module.exports = {
addToPlan: addToPlan,
gitPull: gitPull
};
|
Validate the test github request
|
<?php
/**
* Created by PhpStorm.
* User: Danny
* Date: 15/06/2017
* Time: 06:37 PM
*/
namespace App\Http\Controllers;
use App\Notifications\ReviewerNotifier;
use App\SlackToken;
use App\User;
use function dd;
use Illuminate\Http\Request;
use Illuminate\Notifications\Notifiable;
use function json_decode;
class NotifierController
{
use Notifiable;
/**
* Trigger the notification
*
* @param Request $request
*/
public function index(Request $request)
{
$notification = json_decode($request->toArray()["payload"], true);
// We need this because Github send us a request to verify if the given endpoint exists
if(is_null(array_key_exists("action", $notification))) return;
if ($notification["action"] !== "review_requested") return;
$username = $notification["requested_reviewer"]["login"];
$slackToken = SlackToken::where("github_username", $username)->first();
if ($slackToken) {
$user = User::where("id", $slackToken->user_id)->first();
$user->notify(new ReviewerNotifier($notification));
}
}
public function noAllowed()
{
return view("notifier.notallowed");
}
}
|
<?php
/**
* Created by PhpStorm.
* User: Danny
* Date: 15/06/2017
* Time: 06:37 PM
*/
namespace App\Http\Controllers;
use App\Notifications\ReviewerNotifier;
use App\SlackToken;
use App\User;
use function dd;
use Illuminate\Http\Request;
use Illuminate\Notifications\Notifiable;
use function json_decode;
class NotifierController
{
use Notifiable;
/**
* Trigger the notification
*
* @param Request $request
*/
public function index(Request $request)
{
$notification = json_decode($request->toArray()["payload"], true);
if (!$notification) return;
if ($notification["action"] !== "review_requested") return;
$username = $notification["requested_reviewer"]["login"];
$slackToken = SlackToken::where("github_username", $username)->first();
if ($slackToken) {
$user = User::where("id", $slackToken->user_id)->first();
$user->notify(new ReviewerNotifier($notification));
}
}
public function noAllowed()
{
return view("notifier.notallowed");
}
}
|
Update snapshot util, disable javascript
My CentOs server was segfaulting without this option, and having
javascript on to render email templates just don't make any sense
anyway
|
<?php
namespace Ob\CampaignBundle\Utils;
use Knp\Snappy\Image;
class Snapshot
{
/**
* @var string
*/
private $folder;
/**
* @var string
*/
private $binaryPath;
/**
* @param null $folder The folder where to save the image
* @param string $binaryPath The path to the wkhtmltoimage binary
*/
public function __construct($folder = null, $binaryPath = '/usr/local/bin/wkhtmltoimage')
{
$this->folder = $folder;
$this->binaryPath = $binaryPath;
}
/**
* @param string $html
* @param null $fileName
*
* @return string
*/
public function render($html, $fileName = null)
{
if (null == $fileName) {
$fileName = uniqid() . '.jpg';
}
$filePath = $this->folder . $fileName;
$snappy = new Image($this->binaryPath);
$snappy->setOption('disable-javascript', true);
$snappy->setTimeout(0);
$snappy->generateFromHtml($html, $filePath);
return $fileName;
}
}
|
<?php
namespace Ob\CampaignBundle\Utils;
use Knp\Snappy\Image;
class Snapshot
{
/**
* @var string
*/
private $folder;
/**
* @var string
*/
private $binaryPath;
/**
* @param null $folder The folder where to save the image
* @param string $binaryPath The path to the wkhtmltoimage binary
*/
public function __construct($folder = null, $binaryPath = '/usr/local/bin/wkhtmltoimage')
{
$this->folder = $folder;
$this->binaryPath = $binaryPath;
}
/**
* @param string $html
* @param null $fileName
*
* @return string
*/
public function render($html, $fileName = null)
{
if (null == $fileName) {
$fileName = uniqid() . '.jpg';
}
$filePath = $this->folder . $fileName;
$snappy = new Image($this->binaryPath);
$snappy->setTimeout(0);
$snappy->generateFromHtml($html, $filePath);
return $fileName;
}
}
|
Use PAPERTRAIL_HOSTNAME env var instead of creating the hostname manually
|
'use strict';
const winston = require('winston'),
DEBUG = process.env.DEBUG,
LOGGING_LEVEL = DEBUG ? 'debug' : 'info',
transports = [];
require('winston-papertrail').Papertrail;
if (!process.env.HIDE_ALL_LOGS) {
transports.push(new (winston.transports.Console)({
level: LOGGING_LEVEL,
colorize: true,
prettyPrint: DEBUG === 'debug'
}));
if (process.env.PAPERTRAIL_HOST && process.env.PAPERTRAIL_PORT) {
let papertrail = new winston.transports.Papertrail({
host: process.env.PAPERTRAIL_HOST,
port: process.env.PAPERTRAIL_PORT,
hostname: process.env.PAPERTRAIL_HOSTNAME,
level: LOGGING_LEVEL,
colorize: true
});
transports.push(papertrail);
}
}
const logger = new (winston.Logger)({transports});
module.exports = logger;
|
'use strict';
const winston = require('winston'),
DEBUG = process.env.DEBUG,
LOGGING_LEVEL = DEBUG ? 'debug' : 'info',
transports = [];
require('winston-papertrail').Papertrail;
if (!process.env.HIDE_ALL_LOGS) {
transports.push(new (winston.transports.Console)({
level: LOGGING_LEVEL,
colorize: true,
prettyPrint: DEBUG === 'debug'
}));
if (process.env.PAPERTRAIL_HOST && process.env.PAPERTRAIL_PORT) {
let hostname = process.env.PAPERTRAIL_HOSTNAME || 'API';
let deployMode = process.env.DEPLOY_MODE || '';
let papertrail = new winston.transports.Papertrail({
host: process.env.PAPERTRAIL_HOST,
port: process.env.PAPERTRAIL_PORT,
hostname: `${hostname} ${deployMode}`.toUpperCase(),
level: LOGGING_LEVEL,
colorize: true
});
transports.push(papertrail);
}
}
const logger = new (winston.Logger)({transports});
module.exports = logger;
|
Make the build script P2/3 compatible
|
#! /usr/bin/env python
import os
import stat
import zipfile
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
package_dir = 'xyppy'
python_directive = '#!/usr/bin/env python'
packed = StringIO()
packed_writer = zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED)
for fname in os.listdir(package_dir):
fpath = os.path.join(package_dir, fname)
if os.path.isfile(fpath):
packed_writer.write(fpath)
packed_writer.writestr('__main__.py', '''
from xyppy import __main__
if __name__ == '__main__':
__main__.main()
''')
packed_writer.close()
pyfile = package_dir + '.py'
with open(pyfile, 'wb') as f:
shebang = bytes((python_directive + '\n').encode('ascii'))
f.write(shebang)
f.write(packed.getvalue())
os.chmod(pyfile, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
|
#! /usr/bin/env python
import os
import stat
import zipfile
import StringIO
package_dir = 'xyppy'
python_directive = '#!/usr/bin/env python'
packed = StringIO.StringIO()
packed_writer = zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED)
for fname in os.listdir(package_dir):
fpath = os.path.join(package_dir, fname)
if os.path.isfile(fpath):
packed_writer.write(fpath)
packed_writer.writestr('__main__.py', '''
from xyppy import __main__
if __name__ == '__main__':
__main__.main()
''')
packed_writer.close()
pyfile = package_dir + '.py'
with open(pyfile, 'wb') as f:
f.write(python_directive + '\n')
f.write(packed.getvalue())
os.chmod(pyfile, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
|
Change sendReports time to 11am
Signed-off-by: Felipe Milani <6def120dcec8fcb28aed4723fac713cfff66d853@gmail.com>
|
import { SyncedCron } from 'meteor/percolate:synced-cron';
import { sendReports } from '../../api/email/server/reports.js';
import EndOfMonthEnum from '../../api/settings/EndOfMonthEnum';
SyncedCron.add({
name: 'Send reports for users with end of month on last day',
schedule(parser) {
return parser.recur()
.on(1)
.dayOfMonth()
.on(11)
.hour();
},
job() {
sendReports(undefined, EndOfMonthEnum.LAST_DAY);
},
});
SyncedCron.add({
name: 'Send reports for users with end of month on day 20',
schedule(parser) {
return parser.recur()
.on(21)
.dayOfMonth()
.on(11)
.hour();
},
job() {
sendReports(undefined, EndOfMonthEnum.DAY_20);
},
});
SyncedCron.start();
|
import { SyncedCron } from 'meteor/percolate:synced-cron';
import { sendReports } from '../../api/email/server/reports.js';
import EndOfMonthEnum from '../../api/settings/EndOfMonthEnum';
SyncedCron.add({
name: 'Send reports for users with end of month on last day',
schedule(parser) {
return parser.recur()
.on(1)
.dayOfMonth()
.on(5)
.hour();
},
job() {
sendReports(undefined, EndOfMonthEnum.LAST_DAY);
},
});
SyncedCron.add({
name: 'Send reports for users with end of month on day 20',
schedule(parser) {
return parser.recur()
.on(21)
.dayOfMonth()
.on(5)
.hour();
},
job() {
sendReports(undefined, EndOfMonthEnum.DAY_20);
},
});
SyncedCron.start();
|
Add missing comment and fix copyright date.
|
/**
* Copyright 2014 Rackspace
*
* 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.
*
*/
var util = require('util');
/**
* Error for when the client times out a query.
* @constructor
*
* @param {String} message The error message.
*/
function ClientTimeoutError(message) {
Error.call(this, error);
this.message = message;
this.name = 'ClientTimeoutException';
}
util.inherits(ClientTimeoutError, Error);
exports.ClientTimeoutError = ClientTimeoutError;
|
/**
* Copyright 2013 Rackspace
*
* 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.
*
*/
var util = require('util');
/**
*
* @constructor
*
* @param {String} message The error message.
*/
function ClientTimeoutError(message) {
Error.call(this, error);
this.message = message;
this.name = 'ClientTimeoutException';
}
util.inherits(ClientTimeoutError, Error);
exports.ClientTimeoutError = ClientTimeoutError;
|
Make hhvm-have-source-tarball take S3 info, and pass through input
|
'use strict'
/**
* Copyright (c) 2017-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.
*/
const AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
const source = event.source;
if (!(source && source.bucket && source.path)) {
callback("Input does not include source information");
return;
}
const params = {
Bucket: source.bucket,
Key: source.path
};
const s3 = new AWS.S3();
s3.headObject(params, function(err, data) {
if (err) {
callback(err, data);
}
callback(null, event);
});
}
|
'use strict'
/**
* Copyright (c) 2017-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.
*/
const AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {
const version = event.version;
if (!version) {
callback('Version is required');
}
const nightly = /^\d{4}(\.\d{2}){2}$/.exec(version);
const path = nightly
? 'source/nightlies/hhvm-nightly-'+version+'.tar.gz'
: 'source/hhvm-'+version+'.tar.gz';
const params = {
Bucket: 'hhvm-downloads',
Key: path
};
const s3 = new AWS.S3();
s3.headObject(params, function(err, data) {
if (err) {
callback(err, params);
}
callback(null, {version: version, params: params});
});
}
|
Fix detection of request type in IE
|
/*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
(function() {
"use strict";
/* globals core */
core.Module("lowland.detect.IoRequest", {
VALUE : (function(global) {
if (!global.ActiveXObject) {
try {
new global.XMLHttpRequest();
return "XHR";
} catch (e) {
}
} else {
if (global.location.protocol !== "file:") {
try {
new global.XMLHttpRequest();
return "XHR";
} catch (e) {
}
}
try {
new global.ActiveXObject("Microsoft.XMLHTTP");
return "ACTIVEX";
} catch(e) {
}
}
return "NONE";
})(core.Main.getGlobal())
});
})();
|
/*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
core.Module("lowland.detect.IoRequest", {
VALUE : (function(global) {
if (!global.ActiveXObject) {
try {
new global.XMLHttpRequest();
return "XHR";
} catch (e) {
}
} else {
if (window.location.protocol !== "file:") {
try {
new global.XMLHttpRequest();
return "XHR";
} catch (e) {
}
}
try {
new window.ActiveXObject("Microsoft.XMLHTTP");
return "ACTIVEX";
} catch(e) {
}
}
return "NONE";
})(this)
});
|
Make sure the aggregate service only using the IDirectoryService interface when interactive with its sub-services.
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@10781 e27351fd-9f3e-4f54-a53b-843176b1656c
|
##
# Copyright (c) 2013 Apple 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.
##
"""
Aggregate directory service tests
"""
from twisted.python.components import proxyForInterface
from twext.who.idirectory import IDirectoryService
from twext.who.aggregate import DirectoryService
from twext.who.test import test_directory
from twext.who.test.test_xml import xmlService
class BaseTest(object):
def service(self, services=None):
if services is None:
services = (self.xmlService(),)
#
# Make sure aggregate DirectoryService isn't making
# implementation assumptions about the IDirectoryService
# objects it gets.
#
services = tuple((
proxyForInterface(IDirectoryService)(s)
for s in services
))
return DirectoryService("xyzzy", services)
def xmlService(self, xmlData=None):
return xmlService(self.mktemp(), xmlData)
class DirectoryServiceTest(BaseTest, test_directory.DirectoryServiceTest):
pass
|
##
# Copyright (c) 2013 Apple 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.
##
"""
Aggregate directory service tests
"""
from twisted.python.components import proxyForInterface
from twext.who.idirectory import IDirectoryService
from twext.who.aggregate import DirectoryService
from twext.who.test import test_directory
from twext.who.test.test_xml import xmlService
class BaseTest(object):
def service(self, services=None):
if services is None:
services = (self.xmlService(),)
#
# Make sure aggregate DirectoryService isn't making
# implementation assumptions about the IDirectoryService
# objects it gets.
#
# services = tuple((
# proxyForInterface(IDirectoryService)(s)
# for s in services
# ))
return DirectoryService("xyzzy", services)
def xmlService(self, xmlData=None):
return xmlService(self.mktemp(), xmlData)
class DirectoryServiceTest(BaseTest, test_directory.DirectoryServiceTest):
pass
|
Use white when selected to contrast with blue
|
import React from 'react';
import PropTypes from 'prop-types';
//Custom all purpose dashboard button
class DashButton extends React.Component {
render() {
const {isSelected} = this.props;
return (
<div className="DashButton">
<a
style={{
backgroundColor: isSelected ? 'rgba(49, 119, 201, 0.75)' : '',
color: isSelected ? 'white' : 'black',
width: '100%',
display: 'flex',
justifyContent: 'center'
}}
onClick={this.props.onClick}>
{this.props.buttonText}
</a>
</div>
);
}
}
DashButton.propTypes = {
buttonText: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
isSelected: PropTypes.bool.isRequired
};
export default DashButton;
|
import React from 'react';
import PropTypes from 'prop-types';
//Custom all purpose dashboard button
class DashButton extends React.Component {
render() {
return (
<div className="DashButton">
<a
style={{
backgroundColor: this.props.isSelected? 'rgba(49, 119, 201, 0.75)' : '',
width: '100%',
display: 'flex',
justifyContent: 'center'
}}
onClick={this.props.onClick}>
{this.props.buttonText}
</a>
</div>
);
}
}
DashButton.propTypes = {
buttonText: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
isSelected: PropTypes.bool.isRequired
};
export default DashButton;
|
Add switch to activate debug in tests
Helpful in developing tests
|
var bs = require('../lib/beanstalk_client');
var net = require('net');
var port = process.env.BEANSTALK_PORT || 11333;
var mock = process.env.BEANSTALKD !== '1';
var mock_server;
var connection;
module.exports = {
bind : function (fn, closeOnEnd) {
if(!mock) {
return false;
}
mock_server = net.createServer(function(conn) {
connection = conn;
connection.on('data', function (data) {
fn.call(mock_server, connection, data);
});
if(closeOnEnd === true) {
closeOnEnd = function () {
mock_server.close();
}
}
if(closeOnEnd) {
connection.on('end', function () {
closeOnEnd.call(mock_server);
});
}
});
mock_server.listen(port);
},
getClient : function () {
return bs.Client('127.0.0.1:' + port);
},
activateDebug : function() {
bs.Debug.activate();
}
}
|
var bs = require('../lib/beanstalk_client');
var net = require('net');
var port = process.env.BEANSTALK_PORT || 11333;
var mock = process.env.BEANSTALKD !== '1';
var mock_server;
var connection;
module.exports = {
bind : function (fn, closeOnEnd) {
if(!mock) {
return false;
}
mock_server = net.createServer(function(conn) {
connection = conn;
connection.on('data', function (data) {
fn.call(mock_server, connection, data);
});
if(closeOnEnd === true) {
closeOnEnd = function () {
mock_server.close();
}
}
if(closeOnEnd) {
connection.on('end', function () {
closeOnEnd.call(mock_server);
});
}
});
mock_server.listen(port);
},
getClient : function () {
return bs.Client('127.0.0.1:' + port);
}
}
|
Disable Redux devtools in production.
|
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';
import MainContainer from './containers/main-container';
import VisibleBookmarksList from './containers/visible-bookmarks-list';
require('file?name=[name].[ext]!../assets/favicon.ico');
require('../assets/octicons/octicons.css');
require('../assets/octicons/octicons.eot');
require('../assets/octicons/octicons.woff');
require('../assets/octicons/octicons.ttf');
require('../assets/octicons/octicons.svg');
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunkMiddleware),
process.env.NODE_ENV !== 'production' && window.devToolsExtension
? window.devToolsExtension() : f => f
)
);
const routes = (
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={MainContainer}>
<IndexRoute component={VisibleBookmarksList} />
<Route path="tag/:tag" component={VisibleBookmarksList} />
</Route>
</Router>
</Provider>
);
ReactDOM.render(routes, document.getElementById('app'));
|
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';
import MainContainer from './containers/main-container';
import VisibleBookmarksList from './containers/visible-bookmarks-list';
require('file?name=[name].[ext]!../assets/favicon.ico');
require('../assets/octicons/octicons.css');
require('../assets/octicons/octicons.eot');
require('../assets/octicons/octicons.woff');
require('../assets/octicons/octicons.ttf');
require('../assets/octicons/octicons.svg');
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunkMiddleware),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
const routes = (
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={MainContainer}>
<IndexRoute component={VisibleBookmarksList} />
<Route path="tag/:tag" component={VisibleBookmarksList} />
</Route>
</Router>
</Provider>
);
ReactDOM.render(routes, document.getElementById('app'));
|
Add UserId column to migration
|
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Tasks', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
price: {
type: Sequelize.INTEGER
},
complete: {
defaultValue: false,
type: Sequelize.BOOLEAN
},
UserId: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Tasks');
}
};
|
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Tasks', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
price: {
type: Sequelize.INTEGER
},
complete: {
defaultValue: false,
type: Sequelize.BOOLEAN
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Tasks');
}
};
|
Add dedicated method to send request
|
<?php
namespace Powermash\ComicVine;
use Buzz\Browser;
use Buzz\Exception\RequestException;
/**
*
*/
class Client
{
const DEFAULT_ENDPOINT = 'http://www.comicvine.com/api/characters';
protected $apiKey;
protected $endpoint;
protected $browser;
public function __construct($key, $endpoint = null)
{
$this->apiKey = $key;
$this->endpoint = $endpoint ?: self::DEFAULT_ENDPOINT;
$this->browser = new Browser();
}
public function randomCharacter()
{
$payload = $this->sendRequest('characters', ['offset' => mt_rand(0, 87150), 'limit' => 1]);
$character = reset($payload['results']);
return [
'name' => $character['name'],
'description' => $character['description'],
'thumbnail' => $character['image']['super_url']
];
}
public function sendRequest($ressource, array $parameters = array())
{
$url = sprintf('%s?%s', $this->endpoint, http_build_query([
'format' => 'json',
'api_key' => $this->apiKey
]));
$response = $this->browser->get($url);
$payload = json_decode($response->getContent(), true);
if ($error = json_last_error()) {
throw new JSONException($error);
}
return $payload;
}
}
/**
*
*/
class JSONException extends \RuntimeException
{
}
|
<?php
namespace Powermash\ComicVine;
use Buzz\Browser;
use Buzz\Exception\RequestException;
/**
*
*/
class Client
{
protected $apiKey;
protected $browser;
public function __construct($key)
{
$this->apiKey = $key;
$this->browser = new Browser();
}
public function randomCharacter()
{
$url = 'http://www.comicvine.com/api/characters?'.http_build_query([
'offset' => mt_rand(0, 87150),
'limit' => 1,
'format' => 'json',
'field_list' => 'name,image,publisher,description',
'api_key' => $this->apiKey,
]);
$response = $this->browser->get($url);
$characters = json_decode($response->getContent(), true);
$character = reset($characters['results']);
return [
'name' => $character['name'],
'description' => $character['description'],
'thumbnail' => $character['image']['super_url']
];
}
}
|
Add final modifiers to immutable variables
|
package jp.setchi.HitAndBlow;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StringUtility {
private StringUtility() {}
public static Boolean isDistinctChars(String str) {
if (str == null) {
throw new IllegalArgumentException("nullłB");
}
final Set<Character> existedCharacters = new HashSet<>();
for (char c : str.toCharArray()) {
if (existedCharacters.contains(c)) {
return false;
}
existedCharacters.add(c);
}
return true;
}
public static String generateDistinctRandomNumeric(int digits) {
final List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
if (digits < 0 || numbers.size() < digits) {
throw new IllegalArgumentException(
"0~" + numbers.size() + "͈̔͂Ŏw肵Ă: " + digits);
}
Collections.shuffle(numbers);
final StringBuilder stringBuilder = new StringBuilder();
for (int number : numbers.subList(0, digits)) {
stringBuilder.append(number);
}
return stringBuilder.toString();
}
}
|
package jp.setchi.HitAndBlow;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StringUtility {
private StringUtility() {}
public static Boolean isDistinctChars(String str) {
if (str == null) {
throw new IllegalArgumentException("nullłB");
}
final Set<Character> existedCharacters = new HashSet<>();
for (char c : str.toCharArray()) {
if (existedCharacters.contains(c)) {
return false;
}
existedCharacters.add(c);
}
return true;
}
public static String generateDistinctRandomNumeric(int digits) {
final List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
if (digits < 0 || numbers.size() < digits) {
throw new IllegalArgumentException(
"0~" + numbers.size() + "͈̔͂Ŏw肵Ă: " + digits);
}
Collections.shuffle(numbers);
StringBuilder stringBuilder = new StringBuilder();
for (int number : numbers.subList(0, digits)) {
stringBuilder.append(number);
}
return stringBuilder.toString();
}
}
|
Fix bug with pip install. Update version to 0.1.1.
|
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 setuptools
def readme():
return '`pstar` documentation and source code can be found at https://github.com/iansf/pstar.'
def version():
return '0.1.1'
setuptools.setup(
name='pstar',
description='pstar: numpy for arbitrary data',
long_description=readme(),
version=version(),
url='https://github.com/iansf/pstar',
download_url='https://github.com/iansf/pstar/archive/%s.tar.gz' % version(),
author='Ian Fischer, Google',
author_email='iansf@google.com',
packages=['pstar'],
license='Apache 2.0',
install_requires=[],
test_suite='nose.collector',
tests_require=['nose'],
)
|
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 setuptools
def readme():
with open('docs/README.md') as f:
return f.read()
setuptools.setup(
name='pstar',
description='pstar: better python collections',
long_description=readme(),
version='0.1.0',
url='https://github.com/iansf/pstar',
download_url='https://github.com/iansf/pstar/archive/0.1.0.tar.gz',
author='Ian Fischer, Google',
author_email='iansf@google.com',
packages=['pstar'],
license='Apache 2.0',
install_requires=[],
test_suite='nose.collector',
tests_require=['nose'],
)
|
Allow more time for goroutines to exit
|
// Copyright 2012-2013 Apcera Inc. All rights reserved.
package test
import (
"runtime"
"testing"
"time"
)
func TestSimpleGoServerShutdown(t *testing.T) {
base := runtime.NumGoroutine()
s := RunDefaultServer()
s.Shutdown()
time.Sleep(10 * time.Millisecond)
delta := (runtime.NumGoroutine() - base)
if delta > 1 {
t.Fatalf("%d Go routines still exist post Shutdown()", delta)
}
}
func TestGoServerShutdownWithClients(t *testing.T) {
base := runtime.NumGoroutine()
s := RunDefaultServer()
for i := 0; i < 50; i++ {
createClientConn(t, "localhost", 4222)
}
s.Shutdown()
// Wait longer for client connections
time.Sleep(500 * time.Millisecond)
delta := (runtime.NumGoroutine() - base)
// There may be some finalizers or IO, but in general more than
// 2 as a delta represents a problem.
if delta > 2 {
t.Fatalf("%d Go routines still exist post Shutdown()", delta)
}
}
func TestGoServerMultiShutdown(t *testing.T) {
s := RunDefaultServer()
s.Shutdown()
s.Shutdown()
}
|
// Copyright 2012-2013 Apcera Inc. All rights reserved.
package test
import (
"runtime"
"testing"
"time"
)
func TestSimpleGoServerShutdown(t *testing.T) {
base := runtime.NumGoroutine()
s := RunDefaultServer()
s.Shutdown()
time.Sleep(10 * time.Millisecond)
delta := (runtime.NumGoroutine() - base)
if delta > 1 {
t.Fatalf("%d Go routines still exist post Shutdown()", delta)
}
}
func TestGoServerShutdownWithClients(t *testing.T) {
base := runtime.NumGoroutine()
s := RunDefaultServer()
for i := 0; i < 50; i++ {
createClientConn(t, "localhost", 4222)
}
s.Shutdown()
// Wait longer for client connections
time.Sleep(100 * time.Millisecond)
delta := (runtime.NumGoroutine() - base)
// There may be some finalizers or IO, but in general more than
// 2 as a delta represents a problem.
if delta > 2 {
t.Fatalf("%d Go routines still exist post Shutdown()", delta)
}
}
func TestGoServerMultiShutdown(t *testing.T) {
s := RunDefaultServer()
s.Shutdown()
s.Shutdown()
}
|
Revert "progress on DDG cog & aiohttp wrapper"
This reverts commit 6b6d243e96bd13583e7f02dfe6669578d238a594.
|
#!/bin/env python
import aiohttp
async def aio_get(url: str):
async with aiohttp.ClientSession() as session:
<<<<<<< HEAD
async with session.get(url, headers=headers) as r:
if r.status == 200:
return r.text()
else:
return None
async def aio_get_json(url, headers=None):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as r:
if r.status == 200:
return r.json()
else:
return None
=======
async with session.get(url) as r:
if r.status == 200:
return r
else:
return None
>>>>>>> parent of 6b6d243... progress on DDG cog & aiohttp wrapper
|
#!/bin/env python
import aiohttp
async def aio_get_text(url, headers=None):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as r:
if r.status == 200:
return r.text()
else:
return None
async def aio_get_json(url, headers=None):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as r:
if r.status == 200:
return r.json()
else:
return None
|
Make cleanBin escape carriage returns.
We get confusing output on terminals if we leave \r unescaped.
|
def cleanBin(s, fixspacing=False):
"""
Cleans binary data to make it safe to display. If fixspacing is True,
tabs, newlines and so forth will be maintained, if not, they will be
replaced with a placeholder.
"""
parts = []
for i in s:
o = ord(i)
if (o > 31 and o < 127):
parts.append(i)
elif i in "\n\t" and not fixspacing:
parts.append(i)
else:
parts.append(".")
return "".join(parts)
def hexdump(s):
"""
Returns a set of tuples:
(offset, hex, str)
"""
parts = []
for i in range(0, len(s), 16):
o = "%.10x"%i
part = s[i:i+16]
x = " ".join("%.2x"%ord(i) for i in part)
if len(part) < 16:
x += " "
x += " ".join(" " for i in range(16 - len(part)))
parts.append(
(o, x, cleanBin(part, True))
)
return parts
|
def cleanBin(s, fixspacing=False):
"""
Cleans binary data to make it safe to display. If fixspacing is True,
tabs, newlines and so forth will be maintained, if not, they will be
replaced with a placeholder.
"""
parts = []
for i in s:
o = ord(i)
if (o > 31 and o < 127):
parts.append(i)
elif i in "\n\r\t" and not fixspacing:
parts.append(i)
else:
parts.append(".")
return "".join(parts)
def hexdump(s):
"""
Returns a set of tuples:
(offset, hex, str)
"""
parts = []
for i in range(0, len(s), 16):
o = "%.10x"%i
part = s[i:i+16]
x = " ".join("%.2x"%ord(i) for i in part)
if len(part) < 16:
x += " "
x += " ".join(" " for i in range(16 - len(part)))
parts.append(
(o, x, cleanBin(part, True))
)
return parts
|
Music: Fix stopAll() not working (at all)
|
var Music = {
sounds: { },
prepareSound: function(filename) {
if (typeof(this.sounds[filename]) == 'undefined') {
this.sounds[filename] = new Audio('assets/audio/' + filename);
}
return this.sounds[filename];
},
loopSound: function(filename) {
var sound = this.prepareSound(filename);
sound.currentTime = 0;
sound.addEventListener('ended', function() {
this.currentTime = 0;
this.load();
this.play();
});
sound.load();
sound.play();
},
stopSound: function(filename) {
var sound = this.prepareSound(filename);
sound.pause();
},
stopAll: function() {
for (var sound in this.sounds) {
var soundObj = this.sounds[sound];
soundObj.pause();
}
}
};
|
var Music = {
sounds: { },
prepareSound: function(filename) {
if (typeof(this.sounds[filename]) == 'undefined') {
this.sounds[filename] = new Audio('assets/audio/' + filename);
}
return this.sounds[filename];
},
loopSound: function(filename) {
var sound = this.prepareSound(filename);
sound.currentTime = 0;
sound.addEventListener('ended', function() {
this.currentTime = 0;
this.load();
this.play();
});
sound.load();
sound.play();
},
stopSound: function(filename) {
var sound = this.prepareSound(filename);
sound.pause();
},
stopAll: function() {
for (var sound in this.sounds) {
if (this.sounds.hasOwnProperty(sound)) {
sound.pause();
}
}
}
};
|
Drop python2-era manual encode dance
|
import sys
import csv
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from wafer.talks.models import Talk, ACCEPTED, PROVISIONAL
class Command(BaseCommand):
help = ("List talks and the associated video_reviewer emails."
" Only reviewers for accepted talks are listed")
def _video_reviewers(self, options):
talks = Talk.objects.filter(status=ACCEPTED)
csv_file = csv.writer(sys.stdout)
for talk in talks:
reviewer = talk.video_reviewer
if not reviewer:
reviewer = 'NO REVIEWER'
row = [talk.title,
talk.get_authors_display_name(),
reviewer,
]
csv_file.writerow(row)
def handle(self, *args, **options):
self._video_reviewers(options)
|
import sys
import csv
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from wafer.talks.models import Talk, ACCEPTED, PROVISIONAL
class Command(BaseCommand):
help = ("List talks and the associated video_reviewer emails."
" Only reviewers for accepted talks are listed")
def _video_reviewers(self, options):
talks = Talk.objects.filter(status=ACCEPTED)
csv_file = csv.writer(sys.stdout)
for talk in talks:
reviewer = talk.video_reviewer
if not reviewer:
reviewer = 'NO REVIEWER'
row = [x.encode("utf-8") for x in (
talk.title,
talk.get_authors_display_name(),
reviewer,
)]
csv_file.writerow(row)
def handle(self, *args, **options):
self._video_reviewers(options)
|
Cut the over than 80 columns code
|
module.exports = function (app, passport) {
var authorization = require('../controllers/authorization'),
pages = require('../controllers/pages'),
users = require('../controllers/users'),
auth = require('../lib/authorization');
app.get('/', pages.index);
app.get('/about', pages.about);
app.get('/signup', authorization.signup);
app.post('/signup', authorization.newLocalUser);
app.get('/signin', authorization.signin);
app.post('/signin', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/signin',
failureFlash: true})
);
app.get('/logout', authorization.logout);
app.get('/activate/:string', authorization.activate);
app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/return', passport.authenticate('google', {
successRedirect: '/',
failureRedirect: '/signin'}));
app.get('/users', auth.requiresLogin, users.list);
};
|
module.exports = function (app, passport) {
var authorization = require('../controllers/authorization'),
pages = require('../controllers/pages'),
users = require('../controllers/users'),
auth = require('../lib/authorization');
app.get('/', pages.index);
app.get('/about', pages.about);
app.get('/signup', authorization.signup);
app.post('/signup', authorization.newLocalUser);
app.get('/signin', authorization.signin);
app.post('/signin', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/signin',
failureFlash: true })
);
app.get('/logout', authorization.logout);
app.get('/activate/:string', authorization.activate);
app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/return', passport.authenticate('google', { successRedirect: '/',
failureRedirect: '/signin' }));
app.get('/users', auth.requiresLogin, users.list);
};
|
Extend site model with storage for a defaultRoomID.
This is used in conjunction with autopromote to allow homecloud
to auto-promote all newly created devices.
Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@ninjablocks.com>
|
package model
type Site struct {
ID string `json:"id,omitempty" redis:"id"`
Name *string `json:"name,omitempty" redis:"name"`
Type *string `json:"type,omitempty" redis:"type"`
Latitude *float64 `json:"latitude,omitempty" redis:"latitude"`
Longitude *float64 `json:"longitude,omitempty" redis:"longitude"`
TimeZoneID *string `json:"timeZoneId,omitempty" redis:"timeZoneId"`
TimeZoneName *string `json:"timeZoneName,omitempty" redis:"timeZoneName"`
TimeZoneOffset *int `json:"timeZoneOffset,omitempty" redis:"timeZoneOffset"`
SitePreferences interface{} `json:"site-preferences,omitempty" redis:"site-preferences,json"`
DefaultRoomID *string `json:"defaultRoomId,omitempty" redis:"defaultRoomId,json"`
}
//https://maps.googleapis.com/maps/api/timezone/json?location=-33.86,151.20×tamp=1414645501
/*{
id: "whatever",
name: "Home",
type: "home",
latitude: -33.86,
longitude: 151.20,
timeZoneID: "Australia/Sydney",
timeZoneName: "Australian Eastern Daylight Time",
timeZoneOffset: 36000
}*/
|
package model
type Site struct {
ID string `json:"id,omitempty" redis:"id"`
Name *string `json:"name,omitempty" redis:"name"`
Type *string `json:"type,omitempty" redis:"type"`
Latitude *float64 `json:"latitude,omitempty" redis:"latitude"`
Longitude *float64 `json:"longitude,omitempty" redis:"longitude"`
TimeZoneID *string `json:"timeZoneId,omitempty" redis:"timeZoneId"`
TimeZoneName *string `json:"timeZoneName,omitempty" redis:"timeZoneName"`
TimeZoneOffset *int `json:"timeZoneOffset,omitempty" redis:"timeZoneOffset"`
SitePreferences interface{} `json:"site-preferences,omitempty" redis:"site-preferences,json"`
}
//https://maps.googleapis.com/maps/api/timezone/json?location=-33.86,151.20×tamp=1414645501
/*{
id: "whatever",
name: "Home",
type: "home",
latitude: -33.86,
longitude: 151.20,
timeZoneID: "Australia/Sydney",
timeZoneName: "Australian Eastern Daylight Time",
timeZoneOffset: 36000
}*/
|
Add jobtype as index for schedule
|
package org.commonjava.indy.schedule.datastax;
public class ScheduleDBUtil
{
public static final String TABLE_SCHEDULE = "schedule";
public static String getSchemaCreateTableSchedule( String keyspace )
{
return "CREATE TABLE IF NOT EXISTS " + keyspace + "." + TABLE_SCHEDULE + " ("
+ "jobtype varchar,"
+ "jobname varchar,"
+ "storekey varchar,"
+ "scheduletime timestamp,"
+ "lifescan bigint,"
+ "expiration varchar,"
+ "PRIMARY KEY (storekey, jobname)"
+ ");";
}
public static String getSchemaCreateTypeIndex4Schedule( String keyspace )
{
return "CREATE INDEX IF NOT EXISTS type_idx on " + keyspace + "." + TABLE_SCHEDULE + " (jobtype)";
}
}
|
package org.commonjava.indy.schedule.datastax;
public class ScheduleDBUtil
{
public static String getSchemaCreateTableSchedule( String keyspace )
{
return "CREATE TABLE IF NOT EXISTS " + keyspace + ".schedule ("
+ "jobtype varchar,"
+ "jobname varchar,"
+ "storekey varchar,"
+ "scheduletime timestamp,"
+ "lifescan bigint,"
+ "expiration varchar,"
+ "PRIMARY KEY (storekey, jobname)"
+ ");";
}
}
|
Add all code annotations in single line block comments instead of only @var.
|
<?php
/**
* PHP version 5
*
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @copyright 2014 Contao Community Alliance
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
/**
* Verifies that block comments are used appropriately.
*
* This alters the check from Squiz_Sniffs_Commenting_BlockCommentSniff to ignore inline doc comments as we want to
* allow constructs like: "@var ClassName $variable".
*/
class ContaoCommunityAlliance_Sniffs_Commenting_BlockCommentSniff extends Squiz_Sniffs_Commenting_BlockCommentSniff
{
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// If it is an inline doc comment for type hinting etc., return.
if (substr($tokens[$stackPtr]['content'], 0, 5) === '/** @') {
return;
}
parent::process($phpcsFile, $stackPtr);
}
}
|
<?php
/**
* PHP version 5
*
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @copyright 2014 Contao Community Alliance
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
/**
* Verifies that block comments are used appropriately.
*
* This alters the check from Squiz_Sniffs_Commenting_BlockCommentSniff to ignore inline doc comments as we want to
* allow constructs like: "@var ClassName $variable".
*/
class ContaoCommunityAlliance_Sniffs_Commenting_BlockCommentSniff extends Squiz_Sniffs_Commenting_BlockCommentSniff
{
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The current file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// If it is an inline doc comment for type hinting, return.
if (substr($tokens[$stackPtr]['content'], 0, 8) === '/** @var') {
return;
}
parent::process($phpcsFile, $stackPtr);
}
}
|
Add strings for upcoming features to common learn strings
|
import { createTranslator } from 'kolibri.utils.i18n';
export const learnStrings = createTranslator('CommonLearnStrings', {
// Labels
learnLabel: {
message: 'Learn',
context:
"Each time a learner signs in to Kolibri, the first thing they see is the 'Learn' page with the list of all the classes they are enrolled to.",
},
recommendedLabel: {
message: 'Recommended',
context:
"The 'Recommended' section shows learning topics and materials that are either related to what the learner was doing the last time they used Kolibri, or recommended by their coaches.",
},
resumeLabel: {
message: 'Resume',
context: 'Label for links that go to content that has been started and can be resumed',
},
mostPopularLabel: {
message: 'Most popular',
context: 'Label for links that go to the most popular content',
},
popularLabel: {
message: 'Popular',
context: 'Label for links that go to the most popular content',
},
nextStepsLabel: {
message: 'Next steps',
context: 'Label for links that go to post-requisites for content that has been completed',
},
exploreResourcesWatch: {
message: 'Explore resources to watch',
},
exploreResourcesSchool: {
message: 'Explore resources for school',
},
});
export default {
methods: {
learnString(key, args) {
return learnStrings.$tr(key, args);
},
},
};
|
import { createTranslator } from 'kolibri.utils.i18n';
export const learnStrings = createTranslator('CommonLearnStrings', {
// Labels
learnLabel: {
message: 'Learn',
context:
"Each time a learner signs in to Kolibri, the first thing they see is the 'Learn' page with the list of all the classes they are enrolled to.",
},
recommendedLabel: {
message: 'Recommended',
context:
"The 'Recommended' section shows learning topics and materials that are either related to what the learner was doing the last time they used Kolibri, or recommended by their coaches.",
},
resumeLabel: {
message: 'Resume',
context: 'Label for links that go to content that has been started and can be resumed',
},
mostPopularLabel: {
message: 'Most popular',
context: 'Label for links that go to the most popular content',
},
popularLabel: {
message: 'Popular',
context: 'Label for links that go to the most popular content',
},
nextStepsLabel: {
message: 'Next steps',
context: 'Label for links that go to post-requisites for content that has been completed',
},
});
export default {
methods: {
learnString(key, args) {
return learnStrings.$tr(key, args);
},
},
};
|
Remove calls to the console from the background script
|
/*
* Default Values of options
*/
var defaults = {
min: 39000
};
function onError(e){
console.error(e);
}
// to be run when the app is installed.
function checkStorage(res){
var keys = Object.keys(defaults);
for (var i = 0; i < keys.length;i++){
var nthKey = keys[i];
if (!res[nthKey]){
var storage = {};
storage[nthKey] = defaults[nthKey];
browser.storage.local.set(storage);
// console.log(nthKey+ ' set');
}
}
if (!res.defaults){
browser.storage.local.set({defaults: defaults});
// console.log("default values set.");
}
}
var keys = Object.keys(defaults);
keys.push('defaults');
const gettingStoredSettings = browser.storage.local.get(keys);
gettingStoredSettings.then(checkStorage, onError);
|
/*
* Default Values of options
*/
var defaults = {
min: 39000
};
function onError(e){
console.error(e);
}
// to be run when the app is installed.
function checkStorage(res){
var keys = Object.keys(defaults);
for (var i = 0; i < keys.length;i++){
var nthKey = keys[i];
if (!res[nthKey]){
var storage = {};
storage[nthKey] = defaults[nthKey];
browser.storage.local.set(storage);
console.log(nthKey+ ' set');
}
}
if (!res.defaults){
browser.storage.local.set({defaults: defaults});
console.log("default values set.");
}
}
var keys = Object.keys(defaults);
keys.push('defaults');
const gettingStoredSettings = browser.storage.local.get(keys);
gettingStoredSettings.then(checkStorage, onError);
|
Change fillable user_name to name in model
|
<?php
namespace ZaLaravel\LaravelUser\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use ZaLaravel\LaravelUser\Models\Role;
use ZaLaravel\LaravelUser\Models\Interfaces\UserInterface;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, UserInterface
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
protected $fillable = ['name', 'email', 'password', 'blocked'];
protected $guarded = ['_token'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Get the roles a user has
*/
public function roles()
{
return $this->belongsToMany('ZaLaravel\LaravelUser\Models\Role', 'users_roles');
}
/**
* Find out if user has a specific role
*
* $return boolean
*/
public function hasRole($check)
{
return in_array($check, array_fetch($this->roles->toArray(), 'name'));
}
}
|
<?php
namespace ZaLaravel\LaravelUser\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use ZaLaravel\LaravelUser\Models\Role;
use ZaLaravel\LaravelUser\Models\Interfaces\UserInterface;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract, UserInterface
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
protected $fillable = ['user_name', 'email', 'password', 'blocked'];
protected $guarded = ['_token'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Get the roles a user has
*/
public function roles()
{
return $this->belongsToMany('ZaLaravel\LaravelUser\Models\Role', 'users_roles');
}
/**
* Find out if user has a specific role
*
* $return boolean
*/
public function hasRole($check)
{
return in_array($check, array_fetch($this->roles->toArray(), 'name'));
}
}
|
Disable the jbcsrc debug flag, this was accidentally left on in a debugging session.
GITHUB_BREAKING_CHANGES=none
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=255963260
|
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.jbcsrc.restricted;
/** Holds flags controlling compiler behavior. */
public final class Flags {
/**
* Controls extra debug checks in the compiler that are generally redundant with bytecode
* verification. Currently only enabled in tests.
*/
public static final boolean DEBUG = Boolean.getBoolean("soy_jbcsrc_debug_mode");
private Flags() {}
}
|
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.jbcsrc.restricted;
/** Holds flags controlling compiler behavior. */
public final class Flags {
/**
* Controls extra debug checks in the compiler that are generally redundant with bytecode
* verification. Currently only enabled in tests.
*/
public static final boolean DEBUG = true; // Boolean.getBoolean("soy_jbcsrc_debug_mode");
private Flags() {}
}
|
Fix test for Traits listing
|
<?php
namespace fennecweb\ajax\listing;
use \fennecweb\WebService as WebService;
class TraitsTest extends \PHPUnit_Framework_TestCase
{
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Traits');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '')));
$expected = array(
array(
"name" => "PlantHabit",
"trait_type_id" => 1,
"frequency" => 48916
)
);
$this->assertArraySubset($expected, $results);
}
}
|
<?php
namespace fennecweb\ajax\listing;
use \fennecweb\WebService as WebService;
class TraitsTest extends \PHPUnit_Framework_TestCase
{
public function testExecute()
{
//Test for error returned by user is not logged in
list($service) = WebService::factory('listing/Traits');
$results = ($service->execute(array('dbversion' => DEFAULT_DBVERSION, 'search' => '', 'limit' => '')));
$expected = array(
array(
"name" => "PlantHabit",
"trait_type_id" => 1,
"frequency" => 48916
)
);
$this->assertArraySubset($expected, $results);
}
}
|
Change value in "should assert equality with ===" block
|
describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = "2";
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(2);
});
});
|
describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = "1 + 1";
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(2);
});
});
|
Add daily import for Google Analytics boosting
|
<?php
namespace App\Console\Commands;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class ImportScheduleDaily extends BaseCommand
{
protected $signature = 'import:daily';
protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';
public function handle()
{
$this->call('import:collections');
$this->call('import:exhibitions-legacy');
$this->call('import:events-ticketed');
$this->call('import:events-legacy');
$this->call('import:mobile');
$this->call('import:set-ulan-uris');
$this->call('import:products');
$this->call('import:web');
$this->call('import:analytics');
}
}
|
<?php
namespace App\Console\Commands;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class ImportScheduleDaily extends BaseCommand
{
protected $signature = 'import:daily';
protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';
public function handle()
{
$this->call('import:collections');
$this->call('import:exhibitions-legacy');
$this->call('import:events-ticketed');
$this->call('import:events-legacy');
$this->call('import:mobile');
$this->call('import:set-ulan-uris');
$this->call('import:products');
$this->call('import:web');
}
}
|
Move Namespace in first line
|
<?php namespace Xaamin\Curl;
use Illuminate\Foundation\AliasLoader as Loader;
use Illuminate\Support\ServiceProvider;
/**
* CURL Service provider
*
* @package Xaamin\Curl
* @author Benjamín Martínez Mateos <bmxamin@gmail.com>
*/
class CurlServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
public function boot()
{
$loader = Loader::getInstance();
$loader->alias('CURL', 'Xaamin\Curl\Facades\CurlFacade');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('CURL', function($app)
{
return $app->make('Xaamin\Curl\Curl');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['CURL'];
}
}
|
<?php
namespace Xaamin\Curl;
use Illuminate\Foundation\AliasLoader as Loader;
use Illuminate\Support\ServiceProvider;
/**
* CURL Service provider
*
* @package Xaamin\Curl
* @author Benjamín Martínez Mateos <bmxamin@gmail.com>
*/
class CurlServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
public function boot()
{
$loader = Loader::getInstance();
$loader->alias('CURL', 'Xaamin\Curl\Facades\CurlFacade');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('CURL', function($app)
{
return $app->make('Xaamin\Curl\Curl');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['CURL'];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.