text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Set app group and password | package org.example.app;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import java.util.Map;
import java.util.UUID;
public class PersonCache {
private IMap<String, UUID> map;
private HazelcastInstance instance;
public PersonCache () {
ClientConfig cfg = new ClientConfig();
cfg.addAddress("hazelcast:5701");
cfg.getGroupConfig().setName( "app1" ).setPassword( "app1-pass" );
this.instance = HazelcastClient.newHazelcastClient(cfg);
this.map = instance.getMap("person");
this.map.put("Anonymous", new UUID(0, 0));
}
public boolean cachePerson (String name, UUID id) {
System.out.println("Put " + name + ":" + id.toString() + "to cache");
return this.map.putIfAbsent(name, id) == null;
}
public void forgetPerson (String name) {
System.out.println("Removing " + name + " from cache");
this.map.removeAsync(name);
}
}
| package org.example.app;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import java.util.Map;
import java.util.UUID;
public class PersonCache {
private IMap<String, UUID> map;
private HazelcastInstance instance;
public PersonCache () {
ClientConfig cfg = new ClientConfig();
cfg.addAddress("hazelcast:5701");
this.instance = HazelcastClient.newHazelcastClient(cfg);
this.map = instance.getMap("person");
this.map.put("Anonymous", new UUID(0, 0));
}
public boolean cachePerson (String name, UUID id) {
System.out.println("Put " + name + ":" + id.toString() + "to cache");
return this.map.putIfAbsent(name, id) == null;
}
public void forgetPerson (String name) {
System.out.println("Removing " + name + " from cache");
this.map.removeAsync(name);
}
}
|
Fix F841: local variable is assigned to but never used. | #! /usr/bin/env python
"""
"""
from landlab import RasterModelGrid
from landlab.components.flexure import Flexure
def add_load_to_middle_of_grid(grid, load):
shape = grid.shape
load_array = grid.field_values(
"node", "lithosphere__overlying_pressure_increment"
).view()
load_array.shape = shape
load_array[shape[0] / 2, shape[1] / 2] = load
def main():
(n_rows, n_cols) = (100, 100)
spacing = (10e3, 10e3)
grid = RasterModelGrid(n_rows, n_cols, spacing[1])
flex = Flexure(grid, method="flexure")
add_load_to_middle_of_grid(grid, 1e7)
flex.update()
grid.imshow(
"node",
"lithosphere_surface__elevation_increment",
symmetric_cbar=True,
show=True,
)
if __name__ == "__main__":
main()
| #! /usr/bin/env python
"""
"""
from landlab import RasterModelGrid
from landlab.components.flexure import Flexure
def add_load_to_middle_of_grid(grid, load):
shape = grid.shape
load_array = grid.field_values(
"node", "lithosphere__overlying_pressure_increment"
).view()
load_array.shape = shape
load_array[shape[0] / 2, shape[1] / 2] = load
def main():
(n_rows, n_cols) = (100, 100)
(dy, dx) = (10e3, 10e3)
grid = RasterModelGrid(n_rows, n_cols, dx)
flex = Flexure(grid, method="flexure")
add_load_to_middle_of_grid(grid, 1e7)
flex.update()
grid.imshow(
"node",
"lithosphere_surface__elevation_increment",
symmetric_cbar=True,
show=True,
)
if __name__ == "__main__":
main()
|
Use null instead of undefined in loose check for clarity of purpose | /**
* Store
* Used to provide default values for a store configuration
*/
exports.reduce = function (stores, state, transformer, initial) {
return stores.reduce(function(next, item) {
let key = item[0]
let store = item[1]
next[key] = transformer(store, state[key], key)
return next
}, initial || {})
}
exports.getInitialState = function (store) {
return store.getInitialState? store.getInitialState() : undefined
}
exports.serialize = function (store, state) {
return store.serialize? store.serialize(state) : state
}
exports.deserialize = function (store, raw) {
return store.deserialize? store.deserialize(raw) : raw
}
exports.send = function (store, state, { payload, type }) {
let pool = null
if (typeof store === 'function') {
pool = store()
} else if (typeof store.register === 'function') {
pool = store.register()
}
if (pool == null || type in pool === false) {
return state
}
let handler = pool[type]
return typeof handler === 'function' ? handler.call(store, state, payload) : handler
}
| /**
* Store
* Used to provide default values for a store configuration
*/
exports.reduce = function (stores, state, transformer, initial) {
return stores.reduce(function(next, item) {
let key = item[0]
let store = item[1]
next[key] = transformer(store, state[key], key)
return next
}, initial || {})
}
exports.getInitialState = function (store) {
return store.getInitialState? store.getInitialState() : undefined
}
exports.serialize = function (store, state) {
return store.serialize? store.serialize(state) : state
}
exports.deserialize = function (store, raw) {
return store.deserialize? store.deserialize(raw) : raw
}
exports.send = function (store, state, { payload, type }) {
let pool = null
if (typeof store === 'function') {
pool = store()
} else if (typeof store.register === 'function') {
pool = store.register()
}
if (pool == undefined || type in pool === false) {
return state
}
let handler = pool[type]
return typeof handler === 'function' ? handler.call(store, state, payload) : handler
}
|
Fix no-op test for string library. | const string = require('../../src/util/string.js');
describe('string', () => {
it('exports string', () => {
expect(string).toBeDefined();
});
describe('mapAscii', () => {
it('should return same result for no-ops', () => {
const before = string.mapAscii('', '');
const after = string.mapAscii('', '');
expect(before).toEqual(after);
});
it('should return different results given input', () => {
const before = string.mapAscii('b', 'a');
const after = string.mapAscii('a', 'b');
expect(before).not.toEqual(after);
});
});
describe('translate', () => {
const NO_OP = string.mapAscii('', '');
const LEET = string.mapAscii('let', '137');
it('should be a no-op for empty strings', () => {
expect(string.translate('', NO_OP)).toEqual('');
});
it('should be a no-op for empty translations', () => {
expect(string.translate('example', NO_OP)).toEqual('example');
});
it('should translate characters', () => {
expect(string.translate('leet', LEET)).toEqual('1337');
});
});
});
| const string = require('../../src/util/string.js');
describe('string', () => {
it('exports string', () => {
expect(string).toBeDefined();
});
describe('mapAscii', () => {
it('should return same result for no-ops', () => {
const before = string.mapAscii('', '');
const after = string.mapAscii('', '');
expect(before).toEqual(after);
});
it('should return different results given input', () => {
const before = string.mapAscii('b', 'a');
const after = string.mapAscii('a', 'b');
expect(before).not.toEqual(after);
});
});
describe('translate', () => {
const NO_OP = string.mapAscii('', '');
const LEET = string.mapAscii('let', '137');
it('should be a no-op for empty strings', () => {
expect(string.translate('', '', '')).toEqual('');
});
it('should be a no-op for empty translations', () => {
expect(string.translate('example', NO_OP)).toEqual('example');
});
it('should translate characters', () => {
expect(string.translate('leet', LEET)).toEqual('1337');
});
});
});
|
Tweak demo to show multiple faces in one window instead of separate windows | from PIL import Image, ImageDraw
import face_recognition
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("two_people.jpg")
# Find all facial features in all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)
print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))
# Create a PIL imagedraw object so we can draw on the picture
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)
for face_landmarks in face_landmarks_list:
# Print the location of each facial feature in this image
for facial_feature in face_landmarks.keys():
print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))
# Let's trace out each facial feature in the image with a line!
for facial_feature in face_landmarks.keys():
d.line(face_landmarks[facial_feature], width=5)
# Show the picture
pil_image.show()
| from PIL import Image, ImageDraw
import face_recognition
# Load the jpg file into a numpy array
image = face_recognition.load_image_file("biden.jpg")
# Find all facial features in all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)
print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))
for face_landmarks in face_landmarks_list:
# Print the location of each facial feature in this image
for facial_feature in face_landmarks.keys():
print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))
# Let's trace out each facial feature in the image with a line!
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)
for facial_feature in face_landmarks.keys():
d.line(face_landmarks[facial_feature], width=5)
pil_image.show()
|
Allow CORs on all routes | "use strict";
var express = require('express');
var compress = require('compression')();
var errorHandler = require('errorhandler')({
dumpExceptions: true,
showStack: true
});
var api = require('./modules/api.js');
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
var app = express();
// Configuration
app.use(compress);
app.use('/v1', api);
app.use(errorHandler);
// Allow CORs
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// Routes
app.get('/', function (req, res) {
res.send('Regard website api running');
});
// Go
app.listen(process.env.port || 3001);
console.log("Regard website api running"); | "use strict";
var express = require('express');
var compress = require('compression')();
var errorHandler = require('errorhandler')({
dumpExceptions: true,
showStack: true
});
var api = require('./modules/api.js');
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
var app = express();
// Configuration
app.use(compress);
app.use('/v1', api);
app.use(errorHandler);
// Allow CORs
app.all('/', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// Routes
app.get('/', function (req, res) {
res.send('Regard website api running');
});
// Go
app.listen(process.env.port || 3001);
console.log("Regard website api running"); |
Make swift int textfield use the numberpad keyboard. | /**
* @license
* 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.
*/
foam.CLASS({
package: 'foam.swift.ui',
name: 'FOAMUITextFieldInt',
extends: 'foam.swift.ui.FOAMUITextField',
properties: [
{
name: 'view',
swiftFactory: function() {/*
let t = UITextField()
t.keyboardType = .numberPad
return t
*/},
},
{
name: 'emptyValue',
value: "0",
},
],
});
| /**
* @license
* 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.
*/
foam.CLASS({
package: 'foam.swift.ui',
name: 'FOAMUITextFieldInt',
extends: 'foam.swift.ui.FOAMUITextField',
properties: [
{
name: 'view',
swiftFactory: function() {/*
let t = UITextField()
// TODO make numeric.
return t
*/},
},
{
name: 'emptyValue',
value: "0",
},
],
});
|
Test profile's relationship with updates | import json
from nose.tools import eq_, raises
from mock import MagicMock, patch
from buffer.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
def test_profile_updates():
'''
Test updates relationship with a profile
'''
mocked_api = MagicMock()
with patch('buffer.models.profile.Updates') as mocked_updates:
profile = Profile(api=mocked_api, raw_response={'id': 1})
updates = profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
| import json
from nose.tools import eq_, raises
from mock import MagicMock, patch
from buffer.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
|
Migrate to Dropbox API v2 | <?php
namespace Stevenmaguire\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
class DropboxResourceOwner implements ResourceOwnerInterface
{
/**
* Raw response
*
* @var array
*/
protected $response;
/**
* Creates new resource owner.
*
* @param array $response
*/
public function __construct(array $response = array())
{
$this->response = $response;
}
/**
* Get resource owner id
*
* @return string
*/
public function getId()
{
return $this->response['account_id'] ?: null;
}
/**
* Get resource owner name
*
* @return string
*/
public function getName()
{
return $this->response['name']['display_name'] ?: null;
}
/**
* Return all of the owner details available as an array.
*
* @return array
*/
public function toArray()
{
return $this->response;
}
}
| <?php
namespace Stevenmaguire\OAuth2\Client\Provider;
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
class DropboxResourceOwner implements ResourceOwnerInterface
{
/**
* Raw response
*
* @var array
*/
protected $response;
/**
* Creates new resource owner.
*
* @param array $response
*/
public function __construct(array $response = array())
{
$this->response = $response;
}
/**
* Get resource owner id
*
* @return string
*/
public function getId()
{
return $this->response['uid'] ?: null;
}
/**
* Get resource owner name
*
* @return string
*/
public function getName()
{
return $this->response['display_name'] ?: null;
}
/**
* Return all of the owner details available as an array.
*
* @return array
*/
public function toArray()
{
return $this->response;
}
}
|
Fix Memcachestat. Using wrong classname | <?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_Memcache::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?> | <?php
require_once('../_include.php');
try {
$config = SimpleSAML_Configuration::getInstance();
$session = SimpleSAML_Session::getInstance();
/* Make sure that the user has admin access rights. */
if (!isset($session) || !$session->isValid('login-admin') ) {
SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
array('RelayState' => SimpleSAML_Utilities::selfURL())
);
}
$stats = SimpleSAML_MemcacheStore::getStats();
$template = new SimpleSAML_XHTML_Template($config, 'status-table.php');
$template->data['title'] = 'Memcache stats';
$template->data['table'] = $stats;
$template->show();
} catch(Exception $e) {
SimpleSAML_Utilities::fatalError('na', NULL, $e);
}
?> |
Fix namespace page can not search project name
https://github.com/rancher/rancher/issues/21380 | import Component from '@ember/component';
import layout from './template';
import { inject as service } from '@ember/service';
const headers = [
{
name: 'state',
sort: ['sortState', 'displayName'],
searchField: 'displayState',
translationKey: 'generic.state',
width: 120
},
{
name: 'name',
sort: ['displayName'],
searchField: ['displayName', 'name'],
translationKey: 'projectsPage.ns.label',
},
{
classNames: 'text-right pr-20',
name: 'created',
sort: ['createdTs'],
searchField: false,
translationKey: 'projectsPage.created.label',
width: 250,
},
];
export default Component.extend({
scope: service(),
layout,
headers,
tagName: '',
sortBy: 'name',
searchText: '',
subRows: true,
suffix: true,
paging: true,
extraSearchFields: [
'displayUserLabelStrings',
'project.displayName',
],
});
| import Component from '@ember/component';
import layout from './template';
import { inject as service } from '@ember/service';
const headers = [
{
name: 'state',
sort: ['sortState', 'displayName'],
searchField: 'displayState',
translationKey: 'generic.state',
width: 120
},
{
name: 'name',
sort: ['displayName'],
searchField: ['displayName', 'name'],
translationKey: 'projectsPage.ns.label',
},
{
classNames: 'text-right pr-20',
name: 'created',
sort: ['createdTs'],
searchField: false,
translationKey: 'projectsPage.created.label',
width: 250,
},
];
export default Component.extend({
scope: service(),
layout,
headers,
tagName: '',
sortBy: 'name',
searchText: '',
subRows: true,
suffix: true,
paging: true,
extraSearchFields: [
'displayUserLabelStrings',
],
});
|
Change mixin to use new package
This should not break anything, because the mixin essentially remains the
same. | 'use strict';
import {DeclareMixin} from '@vcas/js-mixin';
/**
* dependencies symbol
*
* @type {Symbol}
* @private
*/
const _dependencies = Symbol('dependencies');
/**
* Dependencies Aware Mixin
*
* @return {DependenciesAware}
*/
export default DeclareMixin((superClass) => class DependenciesAware extends superClass {
/**
* Set dependencies
*
* @param {Array.<*>|null} dependencies Various component dependencies
*/
set dependencies(dependencies) {
this[_dependencies] = dependencies;
}
/**
* Get dependencies
*
* @return {Array.<*>|null} Various component dependencies
*/
get dependencies() {
if (!this.hasDependencies()) {
this.dependencies = this.defaultDependencies;
}
return this[_dependencies];
}
/**
* Check if "dependencies" has been set
*
* @return {boolean}
*/
hasDependencies() {
return (this[_dependencies] !== undefined && this[_dependencies] !== null);
}
/**
* Get a default "dependencies"
*
* @return {Array.<*>|null} A default "dependencies" value or null if none is available
*/
get defaultDependencies() {
return [];
}
}); | 'use strict';
import { Mixin } from 'mixwith/src/mixwith';
/**
* Dependencies symbol
*
* @type {Symbol}
* @private
*/
const _dependencies = Symbol('meta-data-dependencies');
/**
* dependencies Aware mixin
*
* @param {Function} superClass
*
* @returns {DependenciesAware}
*/
export default Mixin(function(superClass){
/**
* @class DependenciesAware
*
* @description Class is aware of one or multiple dependencies.
*
* @author Alin Eugen Deac <aedart@gmail.com>
*/
return class DependenciesAware extends superClass {
/**
* Set data about target's dependencies
*
* @param {Array<*>} dependencies
*/
set dependencies(dependencies){
this.data[_dependencies] = dependencies;
return this;
}
/**
* Get data about target's dependencies
*
* @returns {Array<*>}
*/
get dependencies(){
if(!this.data.hasOwnProperty(_dependencies)){
this.dependencies = [];
}
return this.data[_dependencies];
}
};
}); |
[MISC] Simplify the grunt 'packageIsDefault' check | // Project configuration.
var pkg = require("../package");
module.exports = {
"package" : pkg,
"paths" : {
"private": "Resources/Private",
"public": "Resources/Public",
},
"Sass" : {
"sassDir" : "Resources/Private/Sass",
"cssDir" : "Resources/Public/Stylesheets"
},
"JavaScripts" : {
"devDir" : "Resources/Private/Javascripts",
"distDir" : "Resources/Public/Javascripts",
"config" : "Resources/Private/Javascripts/Main.js",
"requireJS" : "Resources/Private/Javascripts/Libaries/RequireJS/require",
"compileDistFile" : "Resources/Public/Javascripts/Main.min.js"
},
"Images" : {
"devDir" : "Resources/Private/Images",
"distDir" : "Resources/Public/Images",
"optimizationLevel" : 5
},
"packageIsDefault" : pkg.name === "t3b_template" // Check if the defaults in 'package.json' are customized.
};
| // Project configuration.
var pkg = require("../package");
module.exports = {
"package" : pkg,
"paths" : {
"private": "Resources/Private",
"public": "Resources/Public",
},
"Sass" : {
"sassDir" : "Resources/Private/Sass",
"cssDir" : "Resources/Public/Stylesheets"
},
"JavaScripts" : {
"devDir" : "Resources/Private/Javascripts",
"distDir" : "Resources/Public/Javascripts",
"config" : "Resources/Private/Javascripts/Main.js",
"requireJS" : "Resources/Private/Javascripts/Libaries/RequireJS/require",
"compileDistFile" : "Resources/Public/Javascripts/Main.min.js"
},
"Images" : {
"devDir" : "Resources/Private/Images",
"distDir" : "Resources/Public/Images",
"optimizationLevel" : 5
},
"packageIsDefault" : (pkg.name === "t3b_template") ? true : false // Check if the defaults in 'package.json' are customized.
};
|
Include all dates in blast list display | from django.contrib import admin
from django.db import models as django_models
from tinymce.widgets import TinyMCE
from .models import (Recipient, RecipientList, DailyEmailBlast,
DailyEmailBlastType)
def send_blasts(model_admin, request, qs):
for blast in qs:
print blast.send()
class RecipientInline(admin.TabularInline):
model = RecipientList.recipients.through
verbose_name = 'recipient'
verbose_name_plural = 'recipients'
class RecipientListAdmin(admin.ModelAdmin):
model = RecipientList
inlines = [RecipientInline]
class RecipientListInline(admin.TabularInline):
model = DailyEmailBlast.recipient_lists.through
verbose_name = 'recipient list'
verbose_name_plural = 'recipient lists'
class DailyEmailBlastAdmin(admin.ModelAdmin):
model = DailyEmailBlast
inlines = [RecipientListInline]
list_display = ('blast_type', 'created_on', 'sent_on',
'send_completed_on',)
formfield_overrides = {
django_models.TextField: {'widget': TinyMCE()},
}
actions = [send_blasts]
admin.site.register(DailyEmailBlastType)
admin.site.register(Recipient)
admin.site.register(RecipientList, RecipientListAdmin)
admin.site.register(DailyEmailBlast, DailyEmailBlastAdmin)
| from django.contrib import admin
from django.db import models as django_models
from tinymce.widgets import TinyMCE
from .models import (Recipient, RecipientList, DailyEmailBlast,
DailyEmailBlastType)
def send_blasts(model_admin, request, qs):
for blast in qs:
print blast.send()
class RecipientInline(admin.TabularInline):
model = RecipientList.recipients.through
verbose_name = 'recipient'
verbose_name_plural = 'recipients'
class RecipientListAdmin(admin.ModelAdmin):
model = RecipientList
inlines = [RecipientInline]
class RecipientListInline(admin.TabularInline):
model = DailyEmailBlast.recipient_lists.through
verbose_name = 'recipient list'
verbose_name_plural = 'recipient lists'
class DailyEmailBlastAdmin(admin.ModelAdmin):
model = DailyEmailBlast
inlines = [RecipientListInline]
formfield_overrides = {
django_models.TextField: {'widget': TinyMCE()},
}
actions = [send_blasts]
admin.site.register(DailyEmailBlastType)
admin.site.register(Recipient)
admin.site.register(RecipientList, RecipientListAdmin)
admin.site.register(DailyEmailBlast, DailyEmailBlastAdmin)
|
Fix a panic if the request passed in is nil | package cleanhttp
import (
"net/http"
"strings"
"unicode"
)
// HandlerInput provides input options to cleanhttp's handlers
type HandlerInput struct {
ErrStatus int
}
// PrintablePathCheckHandler is a middleware that ensures the request path
// contains only printable runes.
func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler {
// Nil-check on input to make it optional
if input == nil {
input = &HandlerInput{
ErrStatus: http.StatusBadRequest,
}
}
// Default to http.StatusBadRequest on error
if input.ErrStatus == 0 {
input.ErrStatus = http.StatusBadRequest
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r != nil {
// Check URL path for non-printable characters
idx := strings.IndexFunc(r.URL.Path, func(c rune) bool {
return !unicode.IsPrint(c)
})
if idx != -1 {
w.WriteHeader(input.ErrStatus)
return
}
if next != nil {
next.ServeHTTP(w, r)
}
}
return
})
}
| package cleanhttp
import (
"net/http"
"strings"
"unicode"
)
// HandlerInput provides input options to cleanhttp's handlers
type HandlerInput struct {
ErrStatus int
}
// PrintablePathCheckHandler is a middleware that ensures the request path
// contains only printable runes.
func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler {
// Nil-check on input to make it optional
if input == nil {
input = &HandlerInput{
ErrStatus: http.StatusBadRequest,
}
}
// Default to http.StatusBadRequest on error
if input.ErrStatus == 0 {
input.ErrStatus = http.StatusBadRequest
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check URL path for non-printable characters
idx := strings.IndexFunc(r.URL.Path, func(c rune) bool {
return !unicode.IsPrint(c)
})
if idx != -1 {
w.WriteHeader(input.ErrStatus)
return
}
next.ServeHTTP(w, r)
return
})
}
|
Add fullname in REST response | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
bundle.data["full_name"] = "%s %s" % (bundle.obj.parent.user.first_name, bundle.obj.parent.user.last_name)
return bundle
| from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileResource
from scout.api import PostalAddressResource
class MakerScienceProfileResource(ModelResource):
parent = fields.OneToOneField(ProfileResource, 'parent')
location = fields.ToOneField(PostalAddressResource, 'location', null=True, blank=True, full=True)
class Meta:
queryset = MakerScienceProfile.objects.all()
allowed_methods = ['get', 'post', 'put', 'patch']
resource_name = 'makerscience/profile'
authentication = AnonymousApiKeyAuthentication()
authorization = DjangoAuthorization()
always_return_data = True
filtering = {
'parent' : ALL_WITH_RELATIONS,
}
def dehydrate(self, bundle):
bundle.data["first_name"] = bundle.obj.parent.user.first_name
bundle.data["last_name"] = bundle.obj.parent.user.last_name
return bundle
|
Fix stubbing to prevent tests from trying to talk to server. [rev: daniel.grayling] | /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
require.config({
baseUrl: 'src/main/webapp/static/js',
paths: {
'js-testing': '../lib/hp-autonomy-js-testing-utils/src/js',
'mock': '../../../../test/js/mock'
},
map: {
'*': {
'find/lib/backbone/backbone-extensions': 'backbone'
},
'find/app/page/service-view': {
'find/app/model/indexes-collection': 'mock/model/indexes-collection'
}
}
});
| /*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
require.config({
baseUrl: 'src/main/webapp/static/js',
paths: {
'js-testing': '../lib/hp-autonomy-js-testing-utils/src/js',
'mock': '../../../../test/js/mock'
},
map: {
'*': {
'find/lib/backbone/backbone-extensions': 'backbone'
},
'find/app/page/indexes/indexes-view': {
'find/app/model/indexes-collection': 'mock/model/indexes-collection'
}
}
});
|
Use querySelectorAll instead of recursing. | var selection = window.getSelection();
var urls;
function get_links(node) {
var i;
var child;
var children;
var urls = [];
if (!node) {
return;
}
children = node.querySelectorAll('a');
if (children === undefined || children.length === 0) {
return;
}
for(i = 0; i < children.length; i++) {
child = children[i];
if (child.href && urls.indexOf(child.href) === -1) {
urls.push(child.href);
}
}
return urls;
}
function create_tabs(urls) {
var i;
var url;
for (i = 0; i < urls.length; i++) {
url = urls[i];
window.open(url);
}
}
urls = get_links(selection.getRangeAt(0).cloneContents());
create_tabs(urls);
| var selection = window.getSelection();
var urls = [];
function get_links(node) {
var i;
var child;
var children;
if (!node) {
return;
}
children = node.childNodes;
if (children === undefined || children.length === 0) {
return;
}
for(i = 0; i < children.length; i++) {
child = children[i];
if (child.href && urls.indexOf(child.href) === -1) {
urls.push(child.href);
}
get_links(child);
}
}
function create_tabs() {
var i;
var url;
for (i = 0; i < urls.length; i++) {
url = urls[i];
window.open(url);
}
}
get_links(selection.getRangeAt(0).cloneContents());
create_tabs(urls);
|
Add labels to menu buttons | # Game Button class for menu
# Marshall Ehlinger
import pygame
class gameButton:
GRAY = [131, 131, 131]
PINK = [255, 55, 135]
WHITE = [255, 255, 255]
BLACK = [0, 0, 0]
def __init__(self, label, buttonWidth, buttonHeight, importedGameFunction):
self.label = label
self.height = buttonHeight
self.width = buttonWidth
self.importedGameFunction = importedGameFunction
self.font = pygame.font.SysFont("monospace", 15)
def renderButton(self, surface, isSelected, origin_x, origin_y):
label = self.font.render(self.label, True, self.BLACK)
if isSelected:
# pygame.draw.rect(surface, self.PINK, [origin_x, origin_y, self.width, self.height])
surface.fill(self.PINK,[origin_x, origin_y, self.width, self.height])
else:
# pygame.draw.rect(surface, self.GRAY, [origin_x, origin_y, self.width, self.height])
surface.fill(self.GRAY,[origin_x, origin_y, self.width, self.height])
surface.blit(label,[origin_x + 5, origin_y + (.3 * self.height)])
def runGame(self):
self.importedGameFunction()
| # Game Button class for menu
# Marshall Ehlinger
import pygame
class gameButton:
GRAY = [131, 131, 131]
PINK = [255, 55, 135]
def __init__(self, label, buttonWidth, buttonHeight, importedGameFunction):
self.label = label
self.height = buttonHeight
self.width = buttonWidth
self.importedGameFunction = importedGameFunction
def renderButton(self, surface, isSelected, origin_x, origin_y):
if isSelected:
# pygame.draw.rect(surface, self.PINK, [origin_x, origin_y, self.width, self.height])
surface.fill(self.PINK,[origin_x, origin_y, self.width, self.height])
else:
# pygame.draw.rect(surface, self.GRAY, [origin_x, origin_y, self.width, self.height])
surface.fill(self.GRAY,[origin_x, origin_y, self.width, self.height])
def runGame(self):
self.importedGameFunction()
|
Remove the "no second factors yet" flash message | <?php
/**
* Copyright 2014 SURFnet bv
*
* 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.
*/
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
class EntryPointController extends Controller
{
public function decideSecondFactorFlowAction()
{
$identity = $this->getIdentity();
/** @var SecondFactorService $service */
$service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
if ($service->doSecondFactorsExistForIdentity($identity->id)) {
return $this->redirect($this->generateUrl('ss_second_factor_list'));
} else {
return $this->redirect(
$this->generateUrl('ss_registration_display_types')
);
}
}
}
| <?php
/**
* Copyright 2014 SURFnet bv
*
* 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.
*/
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
class EntryPointController extends Controller
{
public function decideSecondFactorFlowAction()
{
$identity = $this->getIdentity();
/** @var SecondFactorService $service */
$service = $this->get('surfnet_stepup_self_service_self_service.service.second_factor');
if ($service->doSecondFactorsExistForIdentity($identity->id)) {
return $this->redirect($this->generateUrl('ss_second_factor_list'));
} else {
$this->get('session')->getFlashBag()->add('notice', 'ss.registration.selector.alert.no_second_factors_yet');
return $this->redirect(
$this->generateUrl('ss_registration_display_types')
);
}
}
}
|
Revert "Use performance.now instead of Date.now"
This reverts commit cbcc919782649d8bcfd7e86e86a20a82fc4dd109. | function easing(time) {
return 1 - (--time) * time * time * time;
};
/**
* Given a start/end point of a scroll and time elapsed, calculate the scroll position we should be at
* @param {Number} start - the initial value
* @param {Number} stop - the final desired value
* @param {Number} elapsed - the amount of time elapsed since we started animating
* @param {Number} - duration - the duration of the animation
* @return {Number} - The value we should use on the next tick
*/
function getValue(start, end, elapsed, duration) {
if (elapsed > duration) return end;
return start + (end - start) * easing(elapsed / duration);
};
/**
* Smoothly animate between two values
* @param {Number} fromValue - the initial value
* @param {Function} onUpdate - A function that is called on each tick
* @param {Function} onComplete - A callback that is fired once the scroll animation ends
* @param {Number} duration - the desired duration of the scroll animation
*/
export default function animate({
fromValue,
toValue,
onUpdate,
onComplete,
duration = 600,
}) {
const startTime = Date.now();
const tick = () => {
const elapsed = Date.now() - startTime;
window.requestAnimationFrame(() => onUpdate(
getValue(fromValue, toValue, elapsed, duration),
// Callback
elapsed <= duration
? tick
: onComplete
));
};
tick();
};
| function easing(time) {
return 1 - (--time) * time * time * time;
};
/**
* Given a start/end point of a scroll and time elapsed, calculate the scroll position we should be at
* @param {Number} start - the initial value
* @param {Number} stop - the final desired value
* @param {Number} elapsed - the amount of time elapsed since we started animating
* @param {Number} - duration - the duration of the animation
* @return {Number} - The value we should use on the next tick
*/
function getValue(start, end, elapsed, duration) {
if (elapsed > duration) return end;
return start + (end - start) * easing(elapsed / duration);
};
/**
* Smoothly animate between two values
* @param {Number} fromValue - the initial value
* @param {Function} onUpdate - A function that is called on each tick
* @param {Function} onComplete - A callback that is fired once the scroll animation ends
* @param {Number} duration - the desired duration of the scroll animation
*/
export default function animate({
fromValue,
toValue,
onUpdate,
onComplete,
duration = 600,
}) {
const startTime = performance.now();
const tick = () => {
const elapsed = performance.now() - startTime;
window.requestAnimationFrame(() => onUpdate(
getValue(fromValue, toValue, elapsed, duration),
// Callback
elapsed <= duration
? tick
: onComplete
));
};
tick();
};
|
Fix pep8, E231 missing whitespace after ',' | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
new['flip'] = image.flip
new['flop'] = image.flop
if image.halign != "":
new['halign'] = image.halign
if image.valign != "":
new['valign'] = image.valign
new['fit_in'] = image.fit_in
new['smart'] = image.smart
if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \
image.crop_y2 > 0:
new['crop'] = ((image.crop_x1, image.crop_y1),
(image.crop_x2, image.crop_y2))
kwargs = dict(new, **kwargs)
return url(image_url=image.image.url, **kwargs)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
new['flip'] = image.flip
new['flop'] = image.flop
if image.halign != "":
new['halign'] = image.halign
if image.valign != "":
new['valign'] = image.valign
new['fit_in'] = image.fit_in
new['smart'] = image.smart
if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \
image.crop_y2 > 0:
new['crop'] = ((image.crop_x1,image.crop_y1),
(image.crop_x2,image.crop_y2))
kwargs = dict(new, **kwargs)
return url(image_url=image.image.url, **kwargs)
|
Change API URL to new location | import axios from 'axios';
import { push } from 'react-router-redux';
import { SIGN_UP_SUCCESS, SIGNING_UP, SIGN_UP_FAILURE } from './types';
export const apiURL = 'https://hello-books-v2.herokuapp.com/api/v1';
export const signUpSuccess = user => ({
type: SIGN_UP_SUCCESS,
user,
});
export const signUpFailure = error => ({
type: SIGN_UP_FAILURE,
error,
});
export const signingUp = () => ({
type: SIGNING_UP,
});
export const signUp = user => (dispatch) => {
dispatch(signingUp());
return axios.post(`${apiURL}/users/signup`, user)
.then((response) => {
dispatch(signUpSuccess(response));
localStorage.setItem('userToken', response.data.token);
setTimeout(() => {
dispatch(push('/login'));
}, 2000);
})
.catch((error) => {
if (error.response) {
dispatch(signUpFailure(error.response.data.error));
} else {
dispatch(signUpFailure(error.message));
}
});
};
| import axios from 'axios';
import { push } from 'react-router-redux';
import { SIGN_UP_SUCCESS, SIGNING_UP, SIGN_UP_FAILURE } from './types';
export const apiURL = 'https://hellobooksv2.herokuapp.com/api/v1';
export const signUpSuccess = user => ({
type: SIGN_UP_SUCCESS,
user,
});
export const signUpFailure = error => ({
type: SIGN_UP_FAILURE,
error,
});
export const signingUp = () => ({
type: SIGNING_UP,
});
export const signUp = user => (dispatch) => {
dispatch(signingUp());
return axios.post(`${apiURL}/users/signup`, user)
.then((response) => {
dispatch(signUpSuccess(response));
localStorage.setItem('userToken', response.data.token);
setTimeout(() => {
dispatch(push('/login'));
}, 2000);
})
.catch((error) => {
if (error.response) {
dispatch(signUpFailure(error.response.data.error));
} else {
dispatch(signUpFailure(error.message));
}
});
};
|
Use the Meta class for noindex meta tag | <?php
/**
* @title Main Controller
* @desc Reproduces a false administration interface identical to the real interface.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License <http://www.gnu.org/licenses/gpl.html>
* @package PH7 / App / Module / Fake Admin Panel / Controller
* @version 1.1.0
*/
namespace PH7;
use PH7\Framework\Layout\Html\Meta;
class MainController extends Controller
{
public function login()
{
$this->view->header = Meta::NOINDEX;
$this->view->page_title = t('Sign in to Admin Panel');
$this->view->h1_title = t('Admin Panel - Login');
$this->output();
}
}
| <?php
/**
* @title Main Controller
* @desc Reproduces a false administration interface identical to the real interface.
*
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License <http://www.gnu.org/licenses/gpl.html>
* @package PH7 / App / Module / Fake Admin Panel / Controller
* @version 1.1.0
*/
namespace PH7;
class MainController extends Controller
{
public function login()
{
$this->view->header = '<meta name="robots" content="noindex" />';
$this->view->page_title = t('Sign in to Admin Panel');
$this->view->h1_title = t('Admin Panel - Login');
$this->output();
}
}
|
Remove `HashMap.merge`, which is absent in Java7.
PiperOrigin-RevId: 445068304 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 quantize;
import java.util.HashMap;
import java.util.Map;
/** Creates a dictionary with keys of colors, and values of count of the color */
public final class QuantizerMap implements Quantizer {
Map<Integer, Integer> colorToCount;
@Override
public QuantizerResult quantize(int[] pixels, int colorCount) {
final HashMap<Integer, Integer> pixelByCount = new HashMap<>();
for (int pixel : pixels) {
final Integer currentPixelCount = pixelByCount.get(pixel);
final int newPixelCount = currentPixelCount == null ? 1 : currentPixelCount + 1;
pixelByCount.put(pixel, newPixelCount);
}
colorToCount = pixelByCount;
return new QuantizerResult(pixelByCount);
}
public Map<Integer, Integer> getColorToCount() {
return colorToCount;
}
}
| /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 quantize;
import java.util.HashMap;
import java.util.Map;
/** Creates a dictionary with keys of colors, and values of count of the color */
public final class QuantizerMap implements Quantizer {
Map<Integer, Integer> colorToCount;
@Override
public QuantizerResult quantize(int[] pixels, int colorCount) {
final HashMap<Integer, Integer> pixelByCount = new HashMap<>();
for (int pixel : pixels) {
pixelByCount.merge(pixel, 1, (Integer count, Integer newValue) -> count + newValue);
}
colorToCount = pixelByCount;
return new QuantizerResult(pixelByCount);
}
public Map<Integer, Integer> getColorToCount() {
return colorToCount;
}
}
|
Change author in about file | """Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe-bio'
__summary__ = 'Bioinformatics pipelines for the Resolwe platform'
__url__ = 'https://github.com/genialis/resolwe-bio'
# Semantic versioning is used. For more information see:
# https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred
__version__ = '12.0.0a2'
__author__ = 'Genialis, Inc.'
__email__ = 'dev-team@genialis.com'
__license__ = 'Apache License (2.0)'
__copyright__ = '2015-2018, ' + __author__
__all__ = (
"__title__", "__summary__", "__url__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
)
| """Central place for package metadata."""
# NOTE: We use __title__ instead of simply __name__ since the latter would
# interfere with a global variable __name__ denoting object's name.
__title__ = 'resolwe-bio'
__summary__ = 'Bioinformatics pipelines for the Resolwe platform'
__url__ = 'https://github.com/genialis/resolwe-bio'
# Semantic versioning is used. For more information see:
# https://packaging.python.org/en/latest/distributing/#semantic-versioning-preferred
__version__ = '12.0.0a2'
__author__ = 'Genialis d.o.o.'
__email__ = 'dev-team@genialis.com'
__license__ = 'Apache License (2.0)'
__copyright__ = '2015-2018, ' + __author__
__all__ = (
"__title__", "__summary__", "__url__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
)
|
Fix the AvailableActionsPrinter to support the new multiplayer action spec.
PiperOrigin-RevId: 183247161 | # 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.
"""An env wrapper to print the available actions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pysc2.env import base_env_wrapper
class AvailableActionsPrinter(base_env_wrapper.BaseEnvWrapper):
"""An env wrapper to print the available actions."""
def __init__(self, env):
super(AvailableActionsPrinter, self).__init__(env)
self._seen = set()
self._action_spec = self.action_spec()[0]
def step(self, *args, **kwargs):
all_obs = super(AvailableActionsPrinter, self).step(*args, **kwargs)
for obs in all_obs:
for avail in obs.observation["available_actions"]:
if avail not in self._seen:
self._seen.add(avail)
self._print(self._action_spec.functions[avail].str(True))
return all_obs
def _print(self, s):
print(s)
| # 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.
"""An env wrapper to print the available actions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pysc2.env import base_env_wrapper
class AvailableActionsPrinter(base_env_wrapper.BaseEnvWrapper):
"""An env wrapper to print the available actions."""
def __init__(self, env):
super(AvailableActionsPrinter, self).__init__(env)
self._seen = set()
self._action_spec = self.action_spec()
def step(self, *args, **kwargs):
all_obs = super(AvailableActionsPrinter, self).step(*args, **kwargs)
for obs in all_obs:
for avail in obs.observation["available_actions"]:
if avail not in self._seen:
self._seen.add(avail)
self._print(self._action_spec.functions[avail].str(True))
return all_obs
def _print(self, s):
print(s)
|
Print zero weights if there is no 1.0 weight. |
package com.uwetrottmann.shopr.algorithm.model;
public abstract class GenericAttribute<T> {
private T currentValue;
double[] mValueWeights;
public double[] getValueWeights() {
return mValueWeights;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
T[] values = getValueSymbols();
builder.append("[");
for (int i = 0; i < mValueWeights.length; i++) {
if (mValueWeights[i] == 1) {
return "[" + values[i] + ":" + mValueWeights[i] + "]";
}
builder.append(values[i]).append(":").append(mValueWeights[i]).append(" ");
}
builder.append("]");
return builder.toString();
}
public abstract T[] getValueSymbols();
public T currentValue() {
return currentValue;
}
public GenericAttribute<T> currentValue(T currentValue) {
this.currentValue = currentValue;
return this;
}
}
|
package com.uwetrottmann.shopr.algorithm.model;
public abstract class GenericAttribute<T> {
private T currentValue;
double[] mValueWeights;
public double[] getValueWeights() {
return mValueWeights;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
T[] values = getValueSymbols();
builder.append("[");
for (int i = 0; i < mValueWeights.length; i++) {
if (mValueWeights[i] != 0) {
builder.append(values[i]).append(":").append(mValueWeights[i]).append(" ");
}
}
builder.append("]");
return builder.toString();
}
public abstract T[] getValueSymbols();
public T currentValue() {
return currentValue;
}
public GenericAttribute<T> currentValue(T currentValue) {
this.currentValue = currentValue;
return this;
}
}
|
Update one remaining context import. | package reception
import (
"context"
etcd "github.com/coreos/etcd/client"
)
type (
keysAPI interface {
Get(path string) (*etcd.Response, error)
Set(path, value string, opts *etcd.SetOptions) error
Watcher(path string) etcd.Watcher
}
etcdShim struct {
api etcd.KeysAPI
}
)
func (s *etcdShim) Get(path string) (*etcd.Response, error) {
return s.api.Get(context.Background(), path, &etcd.GetOptions{
Recursive: true,
})
}
func (s *etcdShim) Set(path, value string, opts *etcd.SetOptions) error {
_, err := s.api.Set(context.Background(), path, value, opts)
return err
}
func (s *etcdShim) Watcher(path string) etcd.Watcher {
return s.api.Watcher(path, &etcd.WatcherOptions{Recursive: true})
}
| package reception
import (
etcd "github.com/coreos/etcd/client"
"golang.org/x/net/context"
)
type (
keysAPI interface {
Get(path string) (*etcd.Response, error)
Set(path, value string, opts *etcd.SetOptions) error
Watcher(path string) etcd.Watcher
}
etcdShim struct {
api etcd.KeysAPI
}
)
func (s *etcdShim) Get(path string) (*etcd.Response, error) {
return s.api.Get(context.Background(), path, &etcd.GetOptions{
Recursive: true,
})
}
func (s *etcdShim) Set(path, value string, opts *etcd.SetOptions) error {
_, err := s.api.Set(context.Background(), path, value, opts)
return err
}
func (s *etcdShim) Watcher(path string) etcd.Watcher {
return s.api.Watcher(path, &etcd.WatcherOptions{Recursive: true})
}
|
[DJ1.10] Support for string view arguments to url() will be removed | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import url, include
from django.views.static import serve
urlpatterns = [
url(r'^auth/', include('helios_auth.urls')),
url(r'^helios/', include('helios.urls')),
# SHOULD BE REPLACED BY APACHE STATIC PATH
url(r'booth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosbooth'}),
url(r'verifier/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosverifier'}),
url(r'static/auth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}),
url(r'static/helios/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios/media'}),
url(r'static/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/server_ui/media'}),
url(r'^', include('server_ui.urls')),
]
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import url, include
urlpatterns = [
url(r'^auth/', include('helios_auth.urls')),
url(r'^helios/', include('helios.urls')),
# SHOULD BE REPLACED BY APACHE STATIC PATH
url(r'booth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosbooth'}),
url(r'verifier/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosverifier'}),
url(r'static/auth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}),
url(r'static/helios/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios/media'}),
url(r'static/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/server_ui/media'}),
url(r'^', include('server_ui.urls')),
]
|
Update the Loader handler to use the new MapUse handler. | package handler
import (
"github.com/materials-commons/config/cfg"
)
type loaderHandler struct {
handler cfg.Handler
loader cfg.Loader
}
// Loader returns a handler that reads the keys in from a loader.
func Loader(loader cfg.Loader) cfg.Handler {
return &loaderHandler{
loader: loader,
}
}
// Init loads the keys by calling the loader.
func (h *loaderHandler) Init() error {
var m = make(map[string]interface{})
if err := h.loader.Load(&m); err != nil {
return err
}
h.handler = MapUse(m)
return h.handler.Init()
}
// Get retrieves keys loaded from the loader.
func (h *loaderHandler) Get(key string, args ...interface{}) (interface{}, error) {
return h.handler.Get(key, args...)
}
// Set sets the value of keys. You can create new keys, or modify existing ones.
// Values are not persisted across runs.
func (h *loaderHandler) Set(key string, value interface{}, args ...interface{}) error {
return h.handler.Set(key, value, args...)
}
// Args returns false. This handler doesn't accept additional arguments.
func (h *loaderHandler) Args() bool {
return false
}
| package handler
import (
"github.com/materials-commons/config/cfg"
)
type loaderHandler struct {
handler cfg.Handler
loader cfg.Loader
}
// Loader returns a handler that reads the keys in from a loader.
func Loader(loader cfg.Loader) cfg.Handler {
return &loaderHandler{
handler: Map(),
loader: loader,
}
}
// Init loads the keys by calling the loader.
func (h *loaderHandler) Init() error {
m := h.handler.(*mapHandler)
if err := h.loader.Load(&m.values); err != nil {
return err
}
return nil
}
// Get retrieves keys loaded from the loader.
func (h *loaderHandler) Get(key string, args ...interface{}) (interface{}, error) {
return h.handler.Get(key, args...)
}
// Set sets the value of keys. You can create new keys, or modify existing ones.
// Values are not persisted across runs.
func (h *loaderHandler) Set(key string, value interface{}, args ...interface{}) error {
return h.handler.Set(key, value, args...)
}
// Args returns false. This handler doesn't accept additional arguments.
func (h *loaderHandler) Args() bool {
return false
}
|
Fix function nextOpenTime to handle hours before opening. | DateUtilities = {
addDay : function(date, days) {
date.setHours(date.getHours() + 24*days);
},
roundToFollowingHalfHour : function(date) {
date.setMilliseconds(0);
date.setSeconds(0);
if(date.getMinutes() < 30) {
date.setMinutes(30);
}
if(date.getMinutes() > 30) {
date.setMinutes(30);
date.setHours(date.getHours() + 1);
}
},
// TODO: handle time before opening
nextOpenTime: function(date) {
var changed = false;
if(date.getHours() < 8) {
date.setHours(8);
changed = true;
}
if(date.getHours() >= 20) {
date.setHours(8 + 24);
changed = true;
}
if(date.getDay() == 0) {
date.setHours(date.getHours() + 24);
changed = true;
}
return changed;
}
};
| DateUtilities = {
addDay : function(date, days) {
date.setHours(date.getHours() + 24*days);
},
roundToFollowingHalfHour : function(date) {
date.setMilliseconds(0);
date.setSeconds(0);
if(date.getMinutes() < 30) {
date.setMinutes(30);
}
if(date.getMinutes() > 30) {
date.setMinutes(30);
date.setHours(date.getHours() + 1);
}
},
// TODO: handle time before opening
nextOpenTime: function(date) {
var changed = false;
if(date.getHours() >= 20) {
date.setHours(8 + 24);
changed = true;
}
if(date.getDay() == 0) {
date.setHours(date.getHours() + 24);
changed = true;
}
return changed;
}
};
|
Update backend - Flight search result | var Flight = require('../models/Flight'),
express = require('express'),
flightRouter = express.Router();
flightRouter.get("/",function (req, res, next) {
console.log(req.query.date);
var query = {};
if(req.query.from)
query.from = req.query.from;
if(req.query.to)
query.to = req.query.to;
if(req.query.date)
query.date = Date.parse(req.query.date);
Flight.find(query, function(err, results){
if (err)
return res.status(500).end("Cant find Flight");
res.status(200).json(results);
})
});
flightRouter.post("/",function (req, res, next) {
var flight = new Flight({
id: req.body.id,
from: req.body.from,
to: req.body.to,
date: req.body.date,
time: req.body.time,
type: req.body.type,
pricetype: req.body.pricetype,
chair: req.body.chair,
price: req.body.price,
})
flight.save(function (err){
if(err)
return res.status(500).end("Cant add Flight");
res.end("Success");
})
});
module.exports = flightRouter;
| var Flight = require('../models/Flight'),
express = require('express'),
flightRouter = express.Router();
flightRouter.get("/",function (req, res, next) {
Flight.find({}, function(err, results){
if (err)
return res.status(500).end("Cant find Flight");
res.status(200).json(results);
})
});
flightRouter.post("/",function (req, res, next) {
var flight = new Flight({
id: req.body.id,
from: req.body.from,
to: req.body.to,
date: req.body.date,
time: req.body.time,
type: req.body.type,
pricetype: req.body.pricetype,
chair: req.body.chair,
price: req.body.price,
})
flight.save(function (err){
if(err)
return res.status(500).end("Cant add Flight");
res.end("Success");
})
});
module.exports = flightRouter;
|
Choose the correct build directory
- We get it from the process.config.default_configuration | var util = require('util');
var Socket = require('net').Socket;
/* Make sure we choose the correct build directory */
var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release';
var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node');
var SOCK_STREAM = bindings.SOCK_STREAM;
var AF_UNIX = bindings.AF_UNIX;
var bind = bindings.bind;
var socket = bindings.socket;
function errnoException(errorno, syscall) {
var e = new Error(syscall + ' ' + errorno);
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
exports.createSocket = function(local_path) {
var fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1)
throw errnoException(errno, 'socket');
var s = new Socket(fd);
if (local_path) {
if (bind(fd, local_path) == -1) {
process.nextTick(function() {
s.emit('error', errnoException(errno, 'bind'));
});
}
s.local_path = local_path;
}
return s;
};
| var util = require('util');
var Socket = require('net').Socket;
var bindings = require(__dirname + '/../build/Debug/unix_stream.node');
var SOCK_STREAM = bindings.SOCK_STREAM;
var AF_UNIX = bindings.AF_UNIX;
var bind = bindings.bind;
var socket = bindings.socket;
function errnoException(errorno, syscall) {
var e = new Error(syscall + ' ' + errorno);
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
exports.createSocket = function(local_path) {
var fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1)
throw errnoException(errno, 'socket');
var s = new Socket(fd);
if (local_path) {
if (bind(fd, local_path) == -1) {
process.nextTick(function() {
s.emit('error', errnoException(errno, 'bind'));
});
}
s.local_path = local_path;
}
return s;
};
|
messages: Add better Java test for time conversion | package io.cucumber.messages;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.TemporalUnit;
import static io.cucumber.messages.TimeConversion.durationToJavaDuration;
import static io.cucumber.messages.TimeConversion.javaDurationToDuration;
import static io.cucumber.messages.TimeConversion.javaInstantToTimestamp;
import static io.cucumber.messages.TimeConversion.timestampToJavaInstant;
import static org.junit.Assert.assertEquals;
public class TimeConversionTest {
@Test
public void convertsToAndFromTimestamp() {
Instant javaInstant = Instant.now();
Messages.Timestamp timestamp = javaInstantToTimestamp(javaInstant);
Instant javaInstantAgain = timestampToJavaInstant(timestamp);
assertEquals(javaInstant, javaInstantAgain);
}
@Test
public void convertsToAndFromDuration() {
Duration javaDuration = Duration.ofSeconds(3, 161000);
Messages.Duration duration = javaDurationToDuration(javaDuration);
Duration javaDurationAgain = durationToJavaDuration(duration);
assertEquals(javaDuration, javaDurationAgain);
}
}
| package io.cucumber.messages;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.TemporalUnit;
import static io.cucumber.messages.TimeConversion.durationToJavaDuration;
import static io.cucumber.messages.TimeConversion.javaDurationToDuration;
import static io.cucumber.messages.TimeConversion.javaInstantToTimestamp;
import static io.cucumber.messages.TimeConversion.timestampToJavaInstant;
import static org.junit.Assert.assertEquals;
public class TimeConversionTest {
@Test
public void convertsToAndFromTimestamp() {
Instant javaInstant = Instant.now();
Messages.Timestamp timestamp = javaInstantToTimestamp(javaInstant);
Instant javaInstantAgain = timestampToJavaInstant(timestamp);
assertEquals(javaInstant, javaInstantAgain);
}
@Test
public void convertsToAndFromDuration() {
Duration javaDuration = Duration.ofMillis(1234);
Messages.Duration duration = javaDurationToDuration(javaDuration);
Duration javaDurationAgain = durationToJavaDuration(duration);
assertEquals(javaDuration, javaDurationAgain);
}
}
|
Add pyinstrument as a commandline entry point | from setuptools import setup, find_packages
setup(
name="pyinstrument",
packages=['pyinstrument'],
version="0.12",
description="A call stack profiler for Python. Inspired by Apple's Instruments.app",
author='Joe Rickerby',
author_email='joerick@mac.com',
url='https://github.com/joerick/pyinstrument',
keywords=['profiling', 'profile', 'profiler', 'cpu', 'time'],
include_package_data=True,
entry_points={'console_scripts': ['pyinstrument = pyinstrument.__main__:main']},
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Debuggers',
'Topic :: Software Development :: Testing',
]
)
| from setuptools import setup, find_packages
setup(
name="pyinstrument",
packages=['pyinstrument'],
version="0.12",
description="A call stack profiler for Python. Inspired by Apple's Instruments.app",
author='Joe Rickerby',
author_email='joerick@mac.com',
url='https://github.com/joerick/pyinstrument',
keywords=['profiling', 'profile', 'profiler', 'cpu', 'time'],
include_package_data=True,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Debuggers',
'Topic :: Software Development :: Testing',
]
)
|
Make the bench/param/stat a commandline parameter
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6150 e27351fd-9f3e-4f54-a53b-843176b1656c |
import sys, pickle
from matplotlib import pyplot
import numpy
from compare import select
def main():
fig = pyplot.figure()
ax = fig.add_subplot(111)
data = []
for fname in sys.argv[1:]:
fname, bench, param, stat = fname.split(',')
stats, samples = select(
pickle.load(file(fname)), bench, param, stat)
data.append(samples)
if data:
assert len(samples) == len(data[0])
bars = []
color = iter('rgbcmy').next
w = 1.0 / len(data)
xs = numpy.arange(len(data[0]))
for i, s in enumerate(data):
bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0])
ax.set_xlabel('sample #')
ax.set_ylabel('seconds')
ax.legend(bars, sys.argv[1:])
pyplot.show()
|
import sys, pickle
from matplotlib import pyplot
import numpy
from compare import select
def main():
fig = pyplot.figure()
ax = fig.add_subplot(111)
data = []
for fname in sys.argv[1:]:
stats, samples = select(
pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time')
data.append(samples)
if data:
assert len(samples) == len(data[0])
bars = []
color = iter('rgbcmy').next
w = 1.0 / len(data)
xs = numpy.arange(len(data[0]))
for i, s in enumerate(data):
bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0])
ax.set_xlabel('sample #')
ax.set_ylabel('seconds')
ax.legend(bars, sys.argv[1:])
pyplot.show()
|
Reset browser sync to Google Chrome Canary | var path = require('path');
var browserSync = require('browser-sync');
var gulp = require('gulp');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpackConfig = require(path.resolve('webpack.config.js'));
var bundler = webpack(webpackConfig);
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'build'
},
files: [
'build/**/*.html',
'build/**/*.js'
],
browser: 'google chrome canary',
middleware: [
webpackDevMiddleware(bundler, {
// IMPORTANT: dev middleware can't access config, so we should
// provide publicPath by ourselves
publicPath: webpackConfig.output.publicPath,
// pretty colored output
stats: { colors: true }
// for other settings see
// http://webpack.github.io/docs/webpack-dev-middleware.html
}),
// bundler should be the same as above
webpackHotMiddleware(bundler)
]
});
});
| var path = require('path');
var browserSync = require('browser-sync');
var gulp = require('gulp');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpackConfig = require(path.resolve('webpack.config.js'));
var bundler = webpack(webpackConfig);
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'build'
},
files: [
'build/**/*.html',
'build/**/*.js'
],
// browser: 'google chrome canary',
browser: 'google-chrome',
middleware: [
webpackDevMiddleware(bundler, {
// IMPORTANT: dev middleware can't access config, so we should
// provide publicPath by ourselves
publicPath: webpackConfig.output.publicPath,
// pretty colored output
stats: { colors: true }
// for other settings see
// http://webpack.github.io/docs/webpack-dev-middleware.html
}),
// bundler should be the same as above
webpackHotMiddleware(bundler)
]
});
});
|
Use local verdana file if available. | var fs = require('fs');
var SVGO = require('svgo');
// Initialize what will be used for automatic text measurement.
var Canvas = require('canvas');
var canvasElement = new Canvas(0, 0); // Width and height are irrelevant.
var canvasContext = canvasElement.getContext('2d');
var CanvasFont = Canvas.Font;
try {
var opensans = new CanvasFont('Verdana', './Verdana.ttf');
canvasContext.addFont(opensans);
} catch(e) {}
canvasContext.font = '10px Verdana';
// Template crafting action below.
var dot = require('dot');
var colorscheme = require('./colorscheme.json');
var template = fs.readFileSync('./template.svg');
var imageTemplate = dot.template(''+template);
function optimize(string, callback) {
var svgo = new SVGO();
svgo.optimize(string, callback);
}
function makeImage(data, cb) {
if (data.colorscheme) {
data.colorA = colorscheme[data.colorscheme].colorA;
data.colorB = colorscheme[data.colorscheme].colorB;
}
data.widths = [
(canvasContext.measureText(data.text[0]).width|0) + 10,
(canvasContext.measureText(data.text[1]).width|0) + 10,
];
var result = imageTemplate(data);
// Run the SVG through SVGO.
optimize(result, function(object) { cb(object.data); });
}
module.exports = makeImage;
| var fs = require('fs');
var SVGO = require('svgo');
// Initialize what will be used for automatic text measurement.
var Canvas = require('canvas');
var canvasElement = new Canvas(0, 0); // Width and height are irrelevant.
var canvasContext = canvasElement.getContext('2d');
canvasContext.font = '10px Verdana';
// Template crafting action below.
var dot = require('dot');
var colorscheme = require('./colorscheme.json');
var template = fs.readFileSync('./template.svg');
var imageTemplate = dot.template(''+template);
function optimize(string, callback) {
var svgo = new SVGO();
svgo.optimize(string, callback);
}
function makeImage(data, cb) {
if (data.colorscheme) {
data.colorA = colorscheme[data.colorscheme].colorA;
data.colorB = colorscheme[data.colorscheme].colorB;
}
data.widths = [
(canvasContext.measureText(data.text[0]).width|0) + 10,
(canvasContext.measureText(data.text[1]).width|0) + 10,
];
var result = imageTemplate(data);
// Run the SVG through SVGO.
optimize(result, function(object) { cb(object.data); });
}
module.exports = makeImage;
|
Fix small problem with properties | '''
Created on 02/02/2014
@author: Miguel Otero
'''
class MeasurementUnit(object):
'''
classdocs
'''
RANK = "rank"
INDEX = "index"
UNITS = "units"
SQ_KM = "sq. km"
PERCENTAGE = "%"
#Enum possible convert_to values
def __init__(self, name=None, convert_to=None, factor=1):
'''
Constructor
'''
self.name = name
self._convert_to = convert_to
self.factor = factor
def __get_convert_to(self):
return self._convert_to
def __set_convert_to(self, value):
if value not in [self.RANK, self.INDEX, self.UNITS, self.SQ_KM, self.PERCENTAGE]:
raise ValueError("Invalid provided convert_to value: {0}".format(value))
self._convert_to = value
convert_to = property(fget=__get_convert_to,
fset=__set_convert_to,
doc="The MeasurementUnit is convertible to this value")
| '''
Created on 02/02/2014
@author: Miguel Otero
'''
class MeasurementUnit(object):
'''
classdocs
'''
RANK = "rank"
INDEX = "index"
UNITS = "units"
SQ_KM = "sq. km"
PERCENTAGE = "%"
#Enum possible convert_to values
def __init__(self, name=None, convert_to=None, factor=1):
'''
Constructor
'''
self.name = name
self.convert_to = convert_to
self.factor = factor
def __get_convert_to(self):
return self.convert_to
def __set_convert_to(self, value):
if value not in [self.RANK, self.INDEX, self.UNITS, self.SQ_KM, self.PERCENTAGE]:
raise ValueError("Invalid provided convert_to value: {0}".format(value))
self.convert_to = value
convert_to = property(fget=__get_convert_to,
fset=__set_convert_to,
doc="The MeasurementUnit is convertible to this value")
|
Clear selected countries correctly when switching sectors | angular.module('yds').controller('Dashboard2Controller', ['$scope', 'DashboardService',
function($scope, DashboardService) {
var scope = $scope;
// If the panels should be allowed to open
scope.allowOpenPanel = false;
// Default selected sector
scope.selectedSector = "aidactivity";
// Set initial panel titles
scope.panelSectorTitle = "Choose your sector";
scope.panelCountrySelectionTitle = "Choose countries";
scope.panelTimePeriodTitle = "Choose time period of activities";
scope.panelCategoryTitle = "Choose filter category";
/**
* Select a sector
* @param newSector Sector to select
*/
scope.setSelectedSector = function(newSector) {
// Get country types for previously selected sector
var map = DashboardService.getApiOptionsMapping(scope.selectedSector);
// For country type of previous sector, clear its selected countries
_.each(map, function(countryType) {
DashboardService.clearCountries(countryType);
});
// Select new sector
scope.selectedSector = newSector;
}
}
]); | angular.module('yds').controller('Dashboard2Controller', ['$scope', 'DashboardService',
function($scope, DashboardService) {
var scope = $scope;
// If the panels should be allowed to open
scope.allowOpenPanel = false;
// Default selected sector
scope.selectedSector = "aidactivity";
// Set initial panel titles
scope.panelSectorTitle = "Choose your sector";
scope.panelCountrySelectionTitle = "Choose countries";
scope.panelTimePeriodTitle = "Choose time period of activities";
scope.panelCategoryTitle = "Choose filter category";
/**
* Select a sector
* @param newSector Sector to select
*/
scope.setSelectedSector = function(newSector) {
// Clear selected countries
DashboardService.clearCountries(scope.selectedSector);
DashboardService.clearCountries(newSector);
// Select new sector
scope.selectedSector = newSector;
}
}
]); |
Revert type hints on abstract container for now.
This is our only abstract class in the compat suite and we expect
people to implement this. Adding a type hint breaks existing
implementations. So it's not really good to do this in a patch
release. | <?php
namespace SAML2\Compat;
abstract class AbstractContainer
{
/**
* Get a PSR-3 compatible logger.
* @return \Psr\Log\LoggerInterface
*/
abstract public function getLogger();
/**
* Generate a random identifier for identifying SAML2 documents.
*/
abstract public function generateId();
/**
* Log an incoming message to the debug log.
*
* Type can be either:
* - **in** XML received from third party
* - **out** XML that will be sent to third party
* - **encrypt** XML that is about to be encrypted
* - **decrypt** XML that was just decrypted
*
* @param string $message
* @param string $type
* @return void
*/
abstract public function debugMessage($message, $type);
/**
* Trigger the user to perform a GET to the given URL with the given data.
*
* @param string $url
* @param array $data
* @return void
*/
abstract public function redirect($url, $data = []);
/**
* Trigger the user to perform a POST to the given URL with the given data.
*
* @param string $url
* @param array $data
* @return void
*/
abstract public function postRedirect($url, $data = []);
}
| <?php
namespace SAML2\Compat;
abstract class AbstractContainer
{
/**
* Get a PSR-3 compatible logger.
* @return \Psr\Log\LoggerInterface
*/
abstract public function getLogger();
/**
* Generate a random identifier for identifying SAML2 documents.
*/
abstract public function generateId();
/**
* Log an incoming message to the debug log.
*
* Type can be either:
* - **in** XML received from third party
* - **out** XML that will be sent to third party
* - **encrypt** XML that is about to be encrypted
* - **decrypt** XML that was just decrypted
*
* @param string $message
* @param string $type
* @return void
*/
abstract public function debugMessage($message, $type);
/**
* Trigger the user to perform a GET to the given URL with the given data.
*
* @param string $url
* @param array $data
* @return void
*/
abstract public function redirect($url, array $data = []);
/**
* Trigger the user to perform a POST to the given URL with the given data.
*
* @param string $url
* @param array $data
* @return void
*/
abstract public function postRedirect($url, array $data = []);
}
|
Add name to dashboard Route. | <?php
namespace DTR\DTRBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class EventController extends Controller
{
/**
* @param $hash
* @return mixed
*
* @Route("/event/{hash}", name="dashboard")
*/
public function dashboardAction($hash)
{
$user = $this->getUser();
if(!$user) {
return $this->redirectToRoute('fos_user_security_login');
}
$doctrine = $this->getDoctrine();
$event = $doctrine->getRepository('DTRBundle:Event')->findOneByHash($hash);
$member = $doctrine->getRepository('DTRBundle:Member')->findByEventUser($event, $user);
if($member == null) {
return new Response('Not a member yet. Need a join button');
}
if($member->isHost()) {
return new Response('Is a host. Need a moderator view.');
}
return new Response('Is a simple member. Need a simple view.');
}
} | <?php
namespace DTR\DTRBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class EventController extends Controller
{
/**
* @param $hash
* @return mixed
*
* @Route("/event/{hash}")
*/
public function dashboardAction($hash)
{
$user = $this->getUser();
if(!$user) {
return $this->redirectToRoute('fos_user_security_login');
}
$doctrine = $this->getDoctrine();
$event = $doctrine->getRepository('DTRBundle:Event')->findOneByHash($hash);
$member = $doctrine->getRepository('DTRBundle:Member')->findByEventUser($event, $user);
if($member == null) {
return new Response('Not a member yet. Need a join button');
}
if($member->isHost()) {
return new Response('Is a host. Need a moderator view.');
}
return new Response('Is a simple member. Need a simple view.');
}
} |
Use consistent load for integ test stability | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine.save(user)
same_user = User(email=user.email, username=user.username)
engine.load(same_user)
assert user.profile == same_user.profile
same_user.profile = "second"
engine.save(same_user)
engine.load(user, consistent=True)
assert user.profile == same_user.profile
engine.delete(user)
with pytest.raises(MissingObjects) as excinfo:
engine.load(same_user, consistent=True)
assert [same_user] == excinfo.value.objects
def test_projection_overlap(engine):
class Model(BaseModel):
hash = Column(Integer, hash_key=True)
range = Column(Integer, range_key=True)
other = Column(Integer)
by_other = GlobalSecondaryIndex(projection=["other", "range"], hash_key="other")
# by_other's projected attributes overlap with the model and its own keys
engine.bind(Model)
| """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine.save(user)
same_user = User(email=user.email, username=user.username)
engine.load(same_user)
assert user.profile == same_user.profile
same_user.profile = "second"
engine.save(same_user)
engine.load(user)
assert user.profile == same_user.profile
engine.delete(user)
with pytest.raises(MissingObjects) as excinfo:
engine.load(same_user)
assert [same_user] == excinfo.value.objects
def test_projection_overlap(engine):
class Model(BaseModel):
hash = Column(Integer, hash_key=True)
range = Column(Integer, range_key=True)
other = Column(Integer)
by_other = GlobalSecondaryIndex(projection=["other", "range"], hash_key="other")
# by_other's projected attributes overlap with the model and its own keys
engine.bind(Model)
|
Reword Test Names for Clarity
I didn't like how the test names were sounding. Hopefully this is
better. | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_triggering_of_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_passes_record_id_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
| """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_valid_data_calls_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_valid_data_writes_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
|
Use advertised API version for CFN. | exports.init = function(genericAWSClient) {
// Creates a CloudFormation API client
var createCFNClient = function (accessKeyId, secretAccessKey, options) {
options = options || {};
var client = cfnClient({
host: options.host || "cloudformation.us-east-1.amazonaws.com",
path: options.path || "/",
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
secure: options.secure,
version: options.version
});
return client;
}
// Amazon CloudFormation API handler which is wrapped around the genericAWSClient
var cfnClient = function(obj) {
var aws = genericAWSClient({
host: obj.host, path: obj.path, accessKeyId: obj.accessKeyId,
secretAccessKey: obj.secretAccessKey, secure: obj.secure
});
obj.call = function(action, query, callback) {
query["Action"] = action
query["Version"] = obj.version || '2010-05-15'
query["SignatureMethod"] = "HmacSHA256"
query["SignatureVersion"] = "2"
return aws.call(action, query, callback);
}
return obj;
}
return createCFNClient;
}
| exports.init = function(genericAWSClient) {
// Creates a CloudFormation API client
var createCFNClient = function (accessKeyId, secretAccessKey, options) {
options = options || {};
var client = cfnClient({
host: options.host || "cloudformation.us-east-1.amazonaws.com",
path: options.path || "/",
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
secure: options.secure,
version: options.version
});
return client;
}
// Amazon CloudFormation API handler which is wrapped around the genericAWSClient
var cfnClient = function(obj) {
var aws = genericAWSClient({
host: obj.host, path: obj.path, accessKeyId: obj.accessKeyId,
secretAccessKey: obj.secretAccessKey, secure: obj.secure
});
obj.call = function(action, query, callback) {
query["Action"] = action
query["Version"] = obj.version || '2010-08-01'
query["SignatureMethod"] = "HmacSHA256"
query["SignatureVersion"] = "2"
return aws.call(action, query, callback);
}
return obj;
}
return createCFNClient;
}
|
Fix bug in migration file | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
class CreateJwtClaimsTable extends Migration
{
/**
* @var string $tableName - Table name.
*/
protected $tableName;
/**
* Initialise the migration.
*/
public function __construct()
{
$this->tableName = Config::get('jwt.claim_table_name');
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('subject')->index();
$table->string('audience')->index();
$table->string('jwt_id')->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop($this->tableName);
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
class CreateJwtClaimsTable extends Migration
{
/**
* @var string $tableName - Table name.
*/
protected $tableName;
/**
* Initialise the migration.
*/
public function __construct()
{
$this->tableName = Config::get('jwt.claim_table_name');
}
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('subject')->unsigned();
$table->string('audience')->unsigned();
$table->string('jwt_id')->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop($this->tableName);
}
}
|
Update url includes for django 2.0 | import django.views.static
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='base.html')),
url(r'^admin/', admin.site.urls),
{%- if cookiecutter.use_djangocms == 'y' %}
url(r'^', include('cms.urls')),
{%- endif %}
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^media/(?P<path>.*)$', django.views.static.serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'^__debug__/', include(debug_toolbar.urls)),
] + staticfiles_urlpatterns() + urlpatterns
| import django.views.static
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='base.html')),
url(r'^admin/', include(admin.site.urls)),
{%- if cookiecutter.use_djangocms == 'y' %}
url(r'^', include('cms.urls')),
{%- endif %}
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^media/(?P<path>.*)$', django.views.static.serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'^__debug__/', include(debug_toolbar.urls)),
] + staticfiles_urlpatterns() + urlpatterns
|
Change the import statement so that the test is skipped when
os.startfile is not present. | # Ridiculously simple test of the os.startfile function for Windows.
#
# empty.vbs is an empty file (except for a comment), which does
# nothing when run with cscript or wscript.
#
# A possible improvement would be to have empty.vbs do something that
# we can detect here, to make sure that not only the os.startfile()
# call succeeded, but also the the script actually has run.
import unittest
from test import test_support
# use this form so that the test is skipped when startfile is not available:
from os import startfile
class TestCase(unittest.TestCase):
def test_nonexisting(self):
self.assertRaises(OSError, startfile, "nonexisting.vbs")
def test_nonexisting_u(self):
self.assertRaises(OSError, startfile, u"nonexisting.vbs")
def test_empty(self):
empty = os.path.join(os.path.dirname(__file__), "empty.vbs")
startfile(empty)
startfile(empty, "open")
def test_empty_u(self):
empty = os.path.join(os.path.dirname(__file__), "empty.vbs")
startfile(unicode(empty, "mbcs"))
startfile(unicode(empty, "mbcs"), "open")
def test_main():
test_support.run_unittest(TestCase)
if __name__=="__main__":
test_main()
| # Ridiculously simple test of the os.startfile function for Windows.
#
# empty.vbs is an empty file (except for a comment), which does
# nothing when run with cscript or wscript.
#
# A possible improvement would be to have empty.vbs do something that
# we can detect here, to make sure that not only the os.startfile()
# call succeeded, but also the the script actually has run.
import unittest
from test import test_support
import os
class TestCase(unittest.TestCase):
def test_nonexisting(self):
self.assertRaises(OSError, os.startfile, "nonexisting.vbs")
def test_nonexisting_u(self):
self.assertRaises(OSError, os.startfile, u"nonexisting.vbs")
def test_empty(self):
empty = os.path.join(os.path.dirname(__file__), "empty.vbs")
os.startfile(empty)
os.startfile(empty, "open")
def test_empty_u(self):
empty = os.path.join(os.path.dirname(__file__), "empty.vbs")
os.startfile(unicode(empty, "mbcs"))
os.startfile(unicode(empty, "mbcs"), "open")
def test_main():
test_support.run_unittest(TestCase)
if __name__=="__main__":
test_main()
|
Copy cert auth from master | #!/usr/bin/env python
import os.path
import subprocess
import argparse
import shutil
cl_parser = argparse.ArgumentParser()
args = cl_parser.parse_args()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
if not os.path.exists('assets/certificates'):
os.makedirs('assets/certificates')
os.chdir('assets/certificates')
shutil.copy2(
'../../../master/assets/certificates/ca.pem', 'ca.pem'
)
shutil.copy2(
'../../../master/assets/certificates/ca-key.pem',
'ca-key.pem'
)
with file('worker.json', 'wt') as f:
f.write("""{
"CN": "node.staging.realtimemusic.com",
"hosts": [
"127.0.0.1",
"staging-node"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "DE",
"L": "Germany",
"ST": ""
}
]
}
""")
subprocess.check_call(
'cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json '
'-profile=client-server worker.json | '
'cfssljson -bare worker-client', shell=True)
| #!/usr/bin/env python
import os.path
import subprocess
import argparse
import shutil
cl_parser = argparse.ArgumentParser()
args = cl_parser.parse_args()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
if not os.path.exists('assets/certificates'):
os.makedirs('assets/certificates')
os.chdir('assets/certificates')
print(os.listdir('.'))
with file('worker.json', 'wt') as f:
f.write("""{
"CN": "node.staging.realtimemusic.com",
"hosts": [
"127.0.0.1",
"staging-node"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "DE",
"L": "Germany",
"ST": ""
}
]
}
""")
subprocess.check_call(
'cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json '
'-profile=client-server worker.json | '
'cfssljson -bare worker-client', shell=True)
|
Change style of Payload suclasses to better encapsulate internal structure | '''
Copyright (c) 2015 Jesse Peterson
Licensed under the MIT license. See the included LICENSE.txt file for details.
'''
from . import Payload
import plistlib # needed for Data() wrapper
class PEMCertificatePayload(Payload):
'''PEM-encoded certificate without private key. May contain root
certificates.
Payload type of "com.apple.security.pem". Further encodes cert_data as
plistlib.Data instance (Base64 data).'''
payload_type = 'com.apple.security.pem'
def __init__(self, identifier, cert_data, uuid=None, **kwargs):
kwargs['PayloadContent'] = plistlib.Data(cert_data)
Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
class PKCS12CertificatePayload(Payload):
'''Password-protected identity certificate. Only one certificate may be
included.
Payload type of "com.apple.security.pkcs12". Include a PKCS#12 (.p12)
identity as cert_data. Further encodes cert_data as plistlib.Data instance
(Base64 data). Include a password argument for the PKCS#12 identity.'''
payload_type = 'com.apple.security.pkcs12'
def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs):
kwargs['PayloadContent'] = plistlib.Data(cert_data)
if password:
kwargs['Password'] = password
Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
| '''
Copyright (c) 2015 Jesse Peterson
Licensed under the MIT license. See the included LICENSE.txt file for details.
'''
from . import Payload
import plistlib # needed for Data() wrapper
class PEMCertificatePayload(Payload):
'''PEM-encoded certificate without private key. May contain root
certificates.
Payload type of "com.apple.security.pem". Further encodes cert_data as
plistlib.Data instance (Base64 data).'''
payload_type = 'com.apple.security.pem'
def __init__(self, identifier, cert_data, uuid=None, **kwargs):
Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
self.payload['PayloadContent'] = plistlib.Data(cert_data)
class PKCS12CertificatePayload(Payload):
'''Password-protected identity certificate. Only one certificate may be
included.
Payload type of "com.apple.security.pkcs12". Include a PKCS#12 (.p12)
identity as cert_data. Further encodes cert_data as plistlib.Data instance
(Base64 data). Include a password argument for the PKCS#12 identity.'''
payload_type = 'com.apple.security.pkcs12'
def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs):
Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
self.payload['PayloadContent'] = plistlib.Data(cert_data)
if password:
self.payload['Password'] = password
|
Remove strange outbox requirement for SSLIFY_DISABLE
I don't understand why that was a condition of the SSLIFY_DISABLE flag, so I removed it. | from django.conf import settings
from django.http import HttpResponsePermanentRedirect
class SSLifyMiddleware(object):
"""Force all requests to use HTTPs. If we get an HTTP request, we'll just
force a redirect to HTTPs.
.. note::
This will only take effect if ``settings.DEBUG`` is False.
.. note::
You can also disable this middleware when testing by setting
``settings.SSLIFY_DISABLE`` to True
"""
def process_request(self, request):
# disabled for test mode?
if getattr(settings, 'SSLIFY_DISABLE', False):
return None
# proceed as normal
if not any((settings.DEBUG, request.is_secure())):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace('http://', 'https://')
return HttpResponsePermanentRedirect(secure_url)
| from django.conf import settings
from django.core import mail
from django.http import HttpResponsePermanentRedirect
class SSLifyMiddleware(object):
"""Force all requests to use HTTPs. If we get an HTTP request, we'll just
force a redirect to HTTPs.
.. note::
This will only take effect if ``settings.DEBUG`` is False.
.. note::
You can also disable this middleware when testing by setting
``settings.SSLIFY_DISABLE`` to True
"""
def process_request(self, request):
# disabled for test mode?
if getattr(settings, 'SSLIFY_DISABLE', False) and \
hasattr(mail, 'outbox'):
return None
# proceed as normal
if not any((settings.DEBUG, request.is_secure())):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace('http://', 'https://')
return HttpResponsePermanentRedirect(secure_url)
|
Use a saner test filename, to work on Windows. | #! /usr/bin/env python
"""Test script for the dumbdbm module
Original by Roger E. Masse
"""
# XXX This test is a disgrace. It doesn't test that it works.
import dumbdbm as dbm
from dumbdbm import error
from test_support import verbose, TESTFN as filename
d = dbm.open(filename, 'c')
d['a'] = 'b'
d['12345678910'] = '019237410982340912840198242'
d.keys()
if d.has_key('a'):
if verbose:
print 'Test dbm keys: ', d.keys()
d.close()
d = dbm.open(filename, 'r')
d.close()
d = dbm.open(filename, 'w')
d.close()
d = dbm.open(filename, 'n')
d.close()
import os
def rm(fn):
try:
os.unlink(fn)
except os.error:
pass
rm(filename + '.dir')
rm(filename + '.dat')
rm(filename + '.bak')
| #! /usr/bin/env python
"""Test script for the dumbdbm module
Original by Roger E. Masse
"""
# XXX This test is a disgrace. It doesn't test that it works.
import dumbdbm as dbm
from dumbdbm import error
from test_support import verbose
filename = '/tmp/delete_me'
d = dbm.open(filename, 'c')
d['a'] = 'b'
d['12345678910'] = '019237410982340912840198242'
d.keys()
if d.has_key('a'):
if verbose:
print 'Test dbm keys: ', d.keys()
d.close()
d = dbm.open(filename, 'r')
d.close()
d = dbm.open(filename, 'w')
d.close()
d = dbm.open(filename, 'n')
d.close()
import os
def rm(fn):
try:
os.unlink(fn)
except os.error:
pass
rm(filename + '.dir')
rm(filename + '.dat')
rm(filename + '.bak')
|
Change email subject. Not much of an ALERT if it happens every day. | #!/usr/bin/env python3
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'MyCymbal Digest'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
| #!/usr/bin/env python3
import datetime
import os
import sys
import smtplib
from email.mime.text import MIMEText
def timeString():
return str(datetime.datetime.now())
if not os.path.exists('email-list'):
print(timeString(), ':\tERROR: email-list not found.', sep='')
quit(1)
if not os.path.exists('credentials'):
print(timeString(), ':\tERROR: credentials not found.', sep='')
quit(1)
with open('credentials', 'r') as _file:
_lines = [str(e).strip('\n') for e in _file]
server = _lines[0]
port = _lines[1]
username = _lines[2]
password = _lines[3]
with open('new-products.html', 'r') as _file:
_message = _file.read()
with open('email-list', 'r') as _file:
recipients = [e.strip('\n') for e in _file]
session=smtplib.SMTP(server, port)
session.ehlo()
session.starttls()
session.login(username, password)
for message_to in recipients:
msg = MIMEText(_message, 'html')
msg['To'] = message_to
msg['From'] = username
msg['Subject'] = 'ALERT: New Cymbals detected on mycymbal.com'
msg = msg.as_string()
session.sendmail(username, message_to, msg)
print(timeString(), ':\tEmailed ', message_to, sep='')
session.quit()
|
Add test to make sure `run_applescript` throws on bad script | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript
from itunes.exceptions import AppleScriptError
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
def test_run_applescript(self):
self.assertRaises(AppleScriptError, run_applescript, "THIS IS INVALID" \
" APPLESCRIPT")
| """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_parse_value(self):
self.assertEquals(parse_value("10"), 10)
self.assertEquals(parse_value("1.0"), 1.0)
self.assertTrue(parse_value("true"))
self.assertFalse(parse_value("false"))
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
self.assertEquals(parse_value('date: "Saturday, March 13, 2010 at ' \
'5:02:22 PM"'), datetime.fromtimestamp(1268517742))
|
Update description to match readme | import os
from setuptools import setup
NAME = 'archivable'
PACKAGES = ['archivable']
DESCRIPTION = 'A class-decorator for archivable django-models'
URL = "https://github.com/potatolondon/archivable"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Potato London Ltd.'
EXTRAS = {
"test": ["mock", "coverage==3.7.1"],
}
setup(
name=NAME,
version='0.1.0',
packages=PACKAGES,
# metadata for upload to PyPI
author=AUTHOR,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=["django", "archivable", "uniqueness"],
url=URL,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
include_package_data=True,
extras_require=EXTRAS,
tests_require=EXTRAS['test'],
)
| import os
from setuptools import setup
NAME = 'archivable'
PACKAGES = ['archivable']
DESCRIPTION = 'Archivable class-decorator for django models which supports uniqueness'
URL = "https://github.com/potatolondon/archivable"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Potato London Ltd.'
EXTRAS = {
"test": ["mock", "coverage==3.7.1"],
}
setup(
name=NAME,
version='0.1.0',
packages=PACKAGES,
# metadata for upload to PyPI
author=AUTHOR,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=["django", "archivable", "uniqueness"],
url=URL,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
include_package_data=True,
extras_require=EXTRAS,
tests_require=EXTRAS['test'],
)
|
Handle lists of possibilities in tests | import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if type(expected) == type([]):
if actual not in expected:
sys.stderr.write("%s didn't expand as expected, got %s instead\n" % (template, actual))
assert 0
else:
if actual != expected:
sys.stderr.write("%s expected to expand to %s, got %s instead\n" % (template, expected, actual))
assert 0
print
| import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = testsuite['testcases']
level = testsuite.get('level', 4)
if level > desired_level:
continue
print name
for testcase in testcases:
template = testcase[0]
expected = testcase[1]
actual = uritemplate.expand(template, vars)
sys.stdout.write(".")
if expected != actual:
print "Template %s expected to expand to %s, got %s instead" % (template, expected, actual)
assert 0
print
|
Fix expandPath() utility when no * is used | 'use strict';
const { flatten } = require('./flatten');
// Take a dot-notation path that can contain `*` and expand it to all
// possible paths within `obj`
// For example, `{a: [{attrB: 'b', attrC: 'c', attrD: 'd'}]}` + `a.*.*` would
// result in `a.0.attrB`, `a.0.attrC` and `a.0.attrD`
const expandPath = function (obj, key) {
const keys = key.split('.');
const keysA = getPaths(obj, keys);
const keysB = Array.isArray(keysA) ? keysA : [keysA];
return keysB;
};
const getPaths = function (obj, path, parentPath = []) {
// Final values
if (path.length === 0) {
return parentPath.join('.');
}
// If the parent path has some non-existing values
if (!isStructuredType(obj)) { return []; }
const [childKey, ...pathA] = path;
if (childKey !== '*') {
return getPaths(obj[childKey], pathA, [...parentPath, childKey]);
}
const paths = Object.entries(obj).map(([childKeyA, child]) =>
getPaths(child, pathA, [...parentPath, childKeyA]));
const pathsA = flatten(paths);
return pathsA;
};
const isStructuredType = function (obj) {
return obj && typeof obj === 'object';
};
module.exports = {
expandPath,
};
| 'use strict';
const { flatten } = require('./flatten');
// Take a dot-notation path that can contain `*` and expand it to all
// possible paths within `obj`
// For example, `{a: [{attrB: 'b', attrC: 'c', attrD: 'd'}]}` + `a.*.*` would
// result in `a.0.attrB`, `a.0.attrC` and `a.0.attrD`
const expandPath = function (obj, key) {
const keys = key.split('.');
const keysA = getPaths(obj, keys);
return keysA;
};
const getPaths = function (obj, path, parentPath = []) {
// Final values
if (path.length === 0) {
return parentPath.join('.');
}
// If the parent path has some non-existing values
if (!isStructuredType(obj)) { return []; }
const [childKey, ...pathA] = path;
if (childKey !== '*') {
return getPaths(obj[childKey], pathA, [...parentPath, childKey]);
}
const paths = Object.entries(obj).map(([childKeyA, child]) =>
getPaths(child, pathA, [...parentPath, childKeyA]));
const pathsA = flatten(paths);
return pathsA;
};
const isStructuredType = function (obj) {
return obj && typeof obj === 'object';
};
module.exports = {
expandPath,
};
|
Remove grunt concat, not used by default, causes errors | module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
less: {
development: {
options: {
compress: false,
yuicompress: false,
optimization: 2
},
files: {
// target.css file: source.less file
'assets/css/css-bootstrap.css': 'assets/css/css-bootstrap.less'
}
}
},
watch: {
options : {
livereload: true,
},
styles: {
// Which files to watch (all .less files recursively in the less directory)
files: ['assets/css/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default',
[
'less',
'watch'
]
);
}; | module.exports = function(grunt) {
// 1. All configuration goes here
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
less: {
development: {
options: {
compress: false,
yuicompress: false,
optimization: 2
},
files: {
// target.css file: source.less file
'assets/css/css-bootstrap.css': 'assets/css/css-bootstrap.less'
}
}
},
watch: {
options : {
livereload: true,
},
styles: {
// Which files to watch (all .less files recursively in the less directory)
files: ['assets/css/**/*.less'],
tasks: ['less'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-watch');
// 4. Where we tell Grunt what to do when we type "grunt" into the terminal.
grunt.registerTask('default',
[
'less',
'watch'
]
);
}; |
Fix model factory faker for user | <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(Suitcoda\Model\User::class, function ($faker) {
return [
'username' => $faker->word,
'email' => $faker->email,
'password' => bcrypt($faker->word),
'name' => $faker->name,
'slug' => $faker->slug,
'is_admin' => $faker->boolean,
'is_active' => true,
'last_login_at' => \Carbon\Carbon::now()
];
});
| <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
$factory->define(Suitcoda\Model\User::class, function ($faker) {
return [
'username' => $faker->userName,
'email' => $faker->email,
'password' => bcrypt($faker->word),
'name' => $faker->name,
'slug' => $faker->slug,
'is_admin' => $faker->boolean,
'is_active' => true,
'last_login_at' => \Carbon\Carbon::now()
];
});
|
Disable query string auth for django compressor. | from firecares.settings.base import *
INSTALLED_APPS = (
'django_statsd',
) + INSTALLED_APPS
STATSD_HOST = 'stats.garnertb.com'
STATSD_PREFIX = 'firecares'
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
MIDDLEWARE_CLASSES = (
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
'django_statsd.middleware.TastyPieRequestTimingMiddleware'
) + MIDDLEWARE_CLASSES
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
AWS_STORAGE_BUCKET_NAME = 'firecares-static'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = "https://s3.amazonaws.com/firecares-static/"
COMPRESS_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATICFILES_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATIC_URL = COMPRESS_URL
DEBUG = False
AWS_QUERYSTRING_AUTH = False
try:
from local_settings import * # noqa
except ImportError:
pass | from firecares.settings.base import *
INSTALLED_APPS = (
'django_statsd',
) + INSTALLED_APPS
STATSD_HOST = 'stats.garnertb.com'
STATSD_PREFIX = 'firecares'
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
MIDDLEWARE_CLASSES = (
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
'django_statsd.middleware.TastyPieRequestTimingMiddleware'
) + MIDDLEWARE_CLASSES
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
AWS_STORAGE_BUCKET_NAME = 'firecares-static'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = "https://s3.amazonaws.com/firecares-static/"
COMPRESS_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATICFILES_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATIC_URL = COMPRESS_URL
DEBUG = False
try:
from local_settings import * # noqa
except ImportError:
pass |
Set lat and lng values |
$(document).ready(function() {
$("#id_place")
.geocomplete({
map: "#map_location",
mapOptions: {
zoom: 10
},
markerOptions: {
draggable: true
}
})
.bind("geocode:result", function(event, result) {
var coordinates = result.geometry.location.lat() + ',' + result.geometry.location.lng();
$('#id_location').val(coordinates);
})
.bind("geocode:error", function(event, status){
console.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
console.log("Multiple: " + results.length + " results found");
});
});
|
$(document).ready(function() {
$("#id_place")
.geocomplete({
map: "#map_location",
mapOptions: {
zoom: 10
},
markerOptions: {
draggable: true
}
//details: "#id_location"
})
.bind("geocode:result", function(event, result){
console.log("Result: " + result.formatted_address + result.lat + ',' + result.lng);
})
.bind("geocode:error", function(event, status){
console.log("ERROR: " + status);
})
.bind("geocode:multiple", function(event, results){
console.log("Multiple: " + results.length + " results found");
});
});
|
Add acknowledgement about command processing | import commands from './commands';
import { client as slackClient } from './slack';
const TEAM_DOMAIN = process.env.SLACK_TEAM_DOMAIN;
const TOKEN = process.env.SLACK_COMMAND_TOKEN;
const CHANNEL = process.env.SLACK_COMMAND_CHANNEL;
function validate(hookData) {
if (TEAM_DOMAIN !== hookData.team_domain) {
return Promise.reject(new Error('Invalid team domain.'));
}
if (TOKEN !== hookData.token) {
return Promise.reject(new Error('Invalid token.'));
}
if (CHANNEL !== hookData.channel_id) {
return Promise.reject(new Error('Invalid channel'));
}
return Promise.resolve(true);
}
function hookRequest(req, res) {
const hookData = req.body;
const commandFn = commands[hookData.command];
res.set('Content-Type', 'text/plain');
if (!commandFn) {
return res.send(400, 'No command given');
}
validate(hookData)
.then(() => res.send(200, 'Ok, processing.'))
.catch((err) => res.send(500, err.message))
.then(() => commandFn(hookData))
.then((response) =>
slackClient().send({ channel: hookData.channel_name, text: response })
)
.catch((err) => console.error('Error processing webhook:', err));
}
export default hookRequest;
| import commands from './commands';
import { client as slackClient } from './slack';
const TEAM_DOMAIN = process.env.SLACK_TEAM_DOMAIN;
const TOKEN = process.env.SLACK_COMMAND_TOKEN;
const CHANNEL = process.env.SLACK_COMMAND_CHANNEL;
function validate(hookData) {
if (TEAM_DOMAIN !== hookData.team_domain) {
return Promise.reject(new Error('Invalid team domain.'));
}
if (TOKEN !== hookData.token) {
return Promise.reject(new Error('Invalid token.'));
}
if (CHANNEL !== hookData.channel_id) {
return Promise.reject(new Error('Invalid channel'));
}
return Promise.resolve(true);
}
function hookRequest(req, res) {
const hookData = req.body;
const commandFn = commands[hookData.command];
res.set('Content-Type', 'text/plain');
if (!commandFn) {
return res.send(400, 'No command given');
}
validate(hookData)
.then(() => res.send(200, ''))
.catch((err) => res.send(500, err.message))
.then(() => commandFn(hookData))
.then((response) =>
slackClient().send({ channel: hookData.channel_name, text: response })
)
.catch((err) => console.error('Error processing webhook:', err));
}
export default hookRequest;
|
DOC: Clean up hinton example text. | """
==============
Hinton diagram
==============
Hinton diagrams are useful for visualizing the values of a 2D array: Positive
and negative values are represented by white and black squares, respectively,
and the size of each square represents the magnitude of each value.
``special.hinton`` is based off of the `Hinton demo`_ in the matplotlib gallery. This implementation, however, uses a ``RegularPolyCollection`` to draw
squares, which is much more efficient than drawing individual rectangles.
Obscure example use: For my Ph.D., I wrote a numerical solver using
finite-differences. For speed, the Jacobian matrices were calculated
analytically, which was incredibly-prone to bugs. To debug my code,
I calculated the numerical Jacobian (calculated using
``scipy.optimize.slsqp.approx_jacobian``) and plotted the Hinton diagram for
the difference of the numerical and analytical results. That allowed me to
narrow down where the bugs were (boundary conditions!) instead of blindly
checking every equation. You could, of course, use ``pcolor`` or ``imshow`` in
a similar situation.
.. _Hinton demo: http://matplotlib.sourceforge.net/examples/api/hinton_demo.html
"""
import numpy as np
import matplotlib.pyplot as plt
from mpltools import special
A = np.random.uniform(-1, 1, size=(20, 20))
special.hinton(A)
plt.show()
| """
==============
Hinton diagram
==============
Hinton diagrams are useful for visualizing the values of a 2D array. Positive
and negative values represented by white and black squares, respectively, and
the size of each square represents the magnitude of each value.
The `special.hinton` function is based off of the Hinton demo in the matplotlib
gallery [1]_. This implementation, however, uses a `RegularPolyCollection` to
draw squares, which is much more efficient than drawing individual rectangles.
Obscure example use: For my Ph.D., I wrote a numerical solver using
finite-differences and writing down Jacobian matrices analytically, was
incredibly-prone to bugs. To debug my code, I calculated the numerical Jacobian
(calculated using `scipy.optimize.slsqp.approx_jacobian`) and plotted the
Hinton diagram for for the difference of the numerical and analytical results.
You could, of course, use `pcolor` or `imshow` in a similar situation.
"""
import numpy as np
import matplotlib.pyplot as plt
from mpltools import special
A = np.random.uniform(-1, 1, size=(20, 20))
special.hinton(A)
plt.show()
|
Add master to admins when added to group | 'use strict';
// Bot
const bot = require('../../bot');
const { replyOptions } = require('../../bot/options');
const { admin } = require('../../stores/user');
const { addGroup, managesGroup } = require('../../stores/group');
const { masterID } = require('../../config.json');
const addedToGroupHandler = async (ctx, next) => {
const msg = ctx.message;
const wasAdded = msg.new_chat_members.some(user =>
user.username === ctx.me);
if (wasAdded && ctx.from.id === masterID) {
admin(ctx.from);
if (!await managesGroup(ctx.chat)) {
const link = await bot.telegram.exportChatInviteLink(ctx.chat.id);
ctx.chat.link = link ? link : '';
await addGroup(ctx.chat);
}
ctx.reply('🛠 <b>Ok, I\'ll help you manage this group from now.</b>',
replyOptions);
}
return next();
};
module.exports = addedToGroupHandler;
| 'use strict';
// Bot
const bot = require('../../bot');
const { replyOptions } = require('../../bot/options');
const { addGroup, managesGroup } = require('../../stores/group');
const { masterID } = require('../../config.json');
const addedToGroupHandler = async (ctx, next) => {
const msg = ctx.message;
const wasAdded = msg.new_chat_members.some(user =>
user.username === ctx.me);
if (wasAdded && ctx.from.id === masterID) {
if (!await managesGroup(ctx.chat)) {
const link = await bot.telegram.exportChatInviteLink(ctx.chat.id);
ctx.chat.link = link ? link : '';
await addGroup(ctx.chat);
}
ctx.reply('🛠 <b>Ok, I\'ll help you manage this group from now.</b>',
replyOptions);
}
return next();
};
module.exports = addedToGroupHandler;
|
Change removeConfirmationDialog from support lib to HEW (Dialog) | package net.somethingdreadful.MAL.dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import net.somethingdreadful.MAL.DetailView;
import net.somethingdreadful.MAL.R;
import org.holoeverywhere.app.AlertDialog;
import org.holoeverywhere.app.DialogFragment;
public class RemoveConfirmationDialogFragment extends DialogFragment {
@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_title_remove);
builder.setMessage(R.string.dialog_message_remove);
builder.setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismiss();
}
});
builder.setPositiveButton(R.string.dialog_label_remove, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
((DetailView) getActivity()).onRemoveConfirmed();
dismiss();
}
});
return builder.create();
}
} | package net.somethingdreadful.MAL.dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import net.somethingdreadful.MAL.DetailView;
import net.somethingdreadful.MAL.R;
import org.holoeverywhere.app.AlertDialog;
public class RemoveConfirmationDialogFragment extends DialogFragment {
@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.dialog_title_remove);
builder.setMessage(R.string.dialog_message_remove);
builder.setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismiss();
}
});
builder.setPositiveButton(R.string.dialog_label_remove, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
((DetailView) getActivity()).onRemoveConfirmed();
dismiss();
}
});
return builder.create();
}
} |
Remove --harmony_maths (I think all methods already work by default) | 'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
'--harmony_symbols', // `Symbol('s')` throws
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
| 'use strict';
var findup = require('findup-sync');
var spawnSync = require('child_process').spawnSync;
var gruntPath = findup('node_modules/grunt-cli/bin/grunt', {cwd: __dirname});
process.title = 'grunth';
var harmonyFlags = [
'--harmony_scoping',
// '--harmony_modules', // We have `require` and ES6 modules are still in flux
'--harmony_symbols', // `Symbol('s')` throws
// '--harmony_proxies', // `new Proxy({}, {})` throws
'--harmony_generators',
'--harmony_numeric_literals',
'--harmony_strings',
'--harmony_arrays',
'--harmony_maths',
];
module.exports = function cli(params) {
spawnSync('node',
harmonyFlags.concat([gruntPath]).concat(params),
{
cwd: process.cwd(),
stdio: 'inherit',
}
);
};
|
Fix logout logger no username | <?php
/**
* Created by PhpStorm.
* User: rahman
* Date: 11/5/14
* Time: 8:47 AM
*/
Event::listen('auth.login', function($user)
{
Event::fire('logger', array(array('login',array('username'=>$user->username),3)));
});
Event::listen('auth.logout', function($user)
{
$username = $user ? $user->username : '-';
Event::fire('logger', array(array('logout',array('username'=>$user->username),3)));
});
Event::listen('logger', function($log)
{
$log = array(
'event_name'=> $log[0],
'custom_parameter'=> json_encode($log[1]),
'verbose_level' => $log[2],
'ip_address' => Request::getClientIp(),
'request_uri' => Request::url(),
);
$logger = Logger::create($log);
$freshTimestamp = new \Carbon\Carbon();
$log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL;
File::append(Config::get('settings.log_file'),$log_string);
}); | <?php
/**
* Created by PhpStorm.
* User: rahman
* Date: 11/5/14
* Time: 8:47 AM
*/
Event::listen('auth.login', function($user)
{
Event::fire('logger', array(array('login',array('username'=>$user->username),3)));
});
Event::listen('auth.logout', function($user)
{
Event::fire('logger', array(array('logout',array('username'=>$user->username),3)));
});
Event::listen('logger', function($log)
{
$log = array(
'event_name'=> $log[0],
'custom_parameter'=> json_encode($log[1]),
'verbose_level' => $log[2],
'ip_address' => Request::getClientIp(),
'request_uri' => Request::url(),
);
$logger = Logger::create($log);
$freshTimestamp = new \Carbon\Carbon();
$log_string = $freshTimestamp.' '.$log['ip_address'].' VL'.$log['verbose_level'].' '.$logger->id.' '.$log['event_name'].' ['.$log['custom_parameter'].'] ['.$log['request_uri'].']'.PHP_EOL;
File::append(Config::get('settings.log_file'),$log_string);
}); |
Add new files in gulp | const polyfill = require('babel-polyfill');
const gulp = require('gulp');
const rename = require('gulp-rename');
const babel = require('gulp-babel');
const concat = require('gulp-concat-sourcemap');
const sourcemaps = require('gulp-sourcemaps');
const jsmin = require('gulp-jsmin');
const addsrc = require('gulp-add-src');
const notify = require("gulp-notify");
gulp.task('default', [
'build-js',
]);
gulp.task('watch', () => {
gulp.watch('./src/*.js', ['build-js']);
});
gulp.task('build-js', () => {
gulp.src('./src/js/event-emitter.js')
.pipe(addsrc.append('./src/event-emitter.js'))
.pipe(addsrc.append('./src/aliases.js'))
.pipe(addsrc.append('./src/psxhr.js'))
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(jsmin())
.pipe(concat('PSXhr.min.js'))
.pipe(sourcemaps.write('/maps'))
.pipe(gulp.dest('./public/'));
});
| const polyfill = require('babel-polyfill');
const gulp = require('gulp');
const rename = require('gulp-rename');
const babel = require('gulp-babel');
const concat = require('gulp-concat-sourcemap');
const sourcemaps = require('gulp-sourcemaps');
const jsmin = require('gulp-jsmin');
const addsrc = require('gulp-add-src');
const notify = require("gulp-notify");
gulp.task('default', [
'build-js',
]);
gulp.task('watch', () => {
gulp.watch('./src/*.js', ['build-js']);
});
gulp.task('build-js', () => {
gulp.src('./src/js/event-emitter.js')
.pipe(addsrc.append('./src/aliases.js'))
.pipe(addsrc.append('./src/psxhr.js'))
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(jsmin())
.pipe(concat('PSXhr.min.js'))
.pipe(sourcemaps.write('/maps'))
.pipe(gulp.dest('./public/'));
});
|
Use front-matter to parse YAML front matter from posts | #!/usr/bin/env/node
var cheerio = require('cheerio'),
fm = require('front-matter'),
fs = require('fs'),
md = require('marked'),
mkdirp = require('mkdirp'),
path = require('path');
function slurp(fpath) {
return fs.readFileSync(fpath, {encoding: 'utf8'});
}
function spit(fpath, contents) {
fs.writeFileSync(fpath, contents);
}
function readPost(fpath) {
var content = fm(slurp('posts/' + fpath));
return {
name: path.basename(fpath, '.md'),
attrs: content.attributes,
markdown: content.body,
html: md(content.body)
};
}
function renderPost($, post) {
$('body').html(post.html);
return $.html();
}
function main() {
console.log('Rendering static site...\n');
var template = cheerio.load(slurp('template.html'));
var posts = fs.readdirSync('posts').map(readPost);
for (var i in posts) {
var post = posts[i];
var inPath = 'posts/' + post.name + '.md';
var outPath = 'site/' + post.name + '/index.html';
console.log(' ' + inPath + ' → ' + outPath);
mkdirp.sync(path.dirname(outPath));
spit(outPath, renderPost(template, post));
}
console.log('\nRendering complete.');
}
main();
| #!/usr/bin/env/node
var cheerio = require('cheerio'),
fs = require('fs'),
md = require('marked'),
mkdirp = require('mkdirp'),
path = require('path');
function slurp(fpath) {
return fs.readFileSync(fpath, {encoding: 'utf8'});
}
function spit(fpath, contents) {
fs.writeFileSync(fpath, contents);
}
function readPost(fpath) {
var markdown = slurp('posts/' + fpath);
return {
name: path.basename(fpath, ".md"),
markdown: markdown,
html: md(markdown)
};
}
function renderPost($, post) {
$('body').html(post.html);
return $.html();
}
function main() {
console.log('Rendering static site...\n');
var template = cheerio.load(slurp('template.html'));
var posts = fs.readdirSync('posts').map(readPost);
for (var i in posts) {
var post = posts[i];
var inPath = 'posts/' + post.name + '.md';
var outPath = 'site/' + post.name + '/index.html';
console.log(' ' + inPath + ' → ' + outPath);
mkdirp.sync(path.dirname(outPath));
spit(outPath, renderPost(template, post));
}
console.log('\nRendering complete.');
}
main();
|
Fix ConnectedSWFObject: restrict attributes set by constructor
- credentials: SETTINGS | kwargs
- region: SETTINGS | kwargs | boto.swf.layer1.Layer1.DefaultRegionName
- connection: kwargs | # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attributes:
- `region`: name of the AWS region
- `connection`: to the SWF endpoint (`boto.swf.layer1.Layer1` object):
"""
__slots__ = [
'region',
'connection'
]
def __init__(self, *args, **kwargs):
settings_ = {key: SETTINGS.get(key, kwargs.get(key)) for key in
('aws_access_key_id',
'aws_secret_access_key')}
self.region = (SETTINGS.get('region') or
kwargs.get('region') or
boto.swf.layer1.Layer1.DefaultRegionName)
self.connection = (kwargs.pop('connection', None) or
boto.swf.connect_to_region(self.region, **settings_))
if self.connection is None:
raise ValueError('invalid region: {}'.format(self.region))
| # -*- coding:utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
import boto.swf
from . import settings
SETTINGS = settings.get()
class ConnectedSWFObject(object):
"""Authenticated object interface
Provides the instance attributes:
- `region`: name of the AWS region
- `connection`: to the SWF endpoint (`boto.swf.layer1.Layer1` object):
"""
__slots__ = [
'region',
'connection'
]
def __init__(self, *args, **kwargs):
settings_ = {k: v for k, v in SETTINGS.iteritems()}
settings_.update(kwargs)
self.region = (settings_.pop('region', None) or
boto.swf.layer1.Layer1.DefaultRegionName)
self.connection = boto.swf.connect_to_region(self.region, **settings_)
if self.connection is None:
raise ValueError('invalid region: {}'.format(self.region))
|
Use ViewHolder pattern in sample adapter | package com.yuyakaido.android.cardstackview.sample;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CardAdapter extends ArrayAdapter<String> {
public CardAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View contentView, ViewGroup parent) {
ViewHolder holder;
if (contentView == null) {
contentView = View.inflate(getContext(), R.layout.item_card_stack, null);
holder = new ViewHolder(contentView);
contentView.setTag(holder);
} else {
holder = (ViewHolder) contentView.getTag();
}
holder.textView.setText(getItem(position));
return contentView;
}
private static class ViewHolder {
public TextView textView;
public ViewHolder(View view) {
this.textView = (TextView) view.findViewById(R.id.item_card_stack_text);
}
}
}
| package com.yuyakaido.android.cardstackview.sample;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CardAdapter extends ArrayAdapter<String> {
public CardAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View contentView, ViewGroup parent) {
if (contentView == null) {
contentView = View.inflate(getContext(), R.layout.item_card_stack, null);
}
TextView v = (TextView) (contentView.findViewById(R.id.item_card_stack_text));
v.setText(getItem(position));
return contentView;
}
}
|
Fix incorrect variable on edit page. | @extends('app')
@section('content')
<div class="wrapper">
<div class="row">
<h1 class="highlighted">Edit Winner Category: {{ $winnerCategory->name }}</h1>
<p>Changing the name of a winner category will not change its URL.</p>
</div>
@include('partials.errors')
{!! Form::model($winnerCategory, ['method' => 'PUT', 'route'=> ['winner-categories.update', $winnerCategory->slug]]) !!}
@include('winner-categories.form')
{!! Form::submit('Update Winner Category') !!}
{!! Form::close() !!}
</div>
<div class="wrapper">
<p>If this winner category is no longer wanted, you may delete it. All candidates within this category must be deleted or moved into another category first.</p>
<div class="form-actions">
<a href="{{ route('winner-categories.destroy', [$winnerCategory->slug]) }}" data-method="DELETE" data-confirm="Are you sure you want to delete this category?" class="button -danger">Delete Category</a>
</div>
</div>
@stop
| @extends('app')
@section('content')
<div class="wrapper">
<div class="row">
<h1 class="highlighted">Edit Category: {{{ $category->name }}}</h1>
<p>Changing the name of category will not change its URL.</p>
</div>
@include('partials.errors')
{!! Form::model($category, ['method' => 'PUT', 'route'=> ['categories.update', $category->slug]]) !!}
@include('categories.form')
{!! Form::submit('Update Category') !!}
{!! Form::close() !!}
</div>
<div class="wrapper">
<p>If this category is no longer wanted, you may delete it. All candidates within this category must be deleted or moved into another category first.</p>
<div class="form-actions">
<a href="{{ route('winner-categories.destroy', [$category->slug]) }}" data-method="DELETE" data-confirm="Are you sure you want to delete this category?" class="button -danger">Delete Category</a>
</div>
</div>
@stop
|
Fix tag and article connections | import graphene
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from app import models
class TagType(DjangoObjectType):
class Meta:
model = models.Tag
interfaces = (graphene.relay.Node,)
articles = DjangoFilterConnectionField(lambda: ArticleType)
@classmethod
def get_node(cls, id, context, info):
return models.Tag.objects.get(pk=id)
class ArticleType(DjangoObjectType):
class Meta:
model = models.Article
interfaces = (graphene.relay.Node,)
tags = DjangoFilterConnectionField(lambda: TagType)
@classmethod
def get_node(cls, id, context, info):
return models.Article.objects.get(pk=id)
| import graphene
from graphene_django import DjangoObjectType
from app import models
class TagType(DjangoObjectType):
class Meta:
model = models.Tag
interfaces = (graphene.relay.Node,)
@classmethod
def get_node(cls, id, context, info):
return models.Tag.objects.get(pk=id)
class TagConnection(graphene.relay.Connection):
class Meta:
node = TagType
class ArticleType(DjangoObjectType):
class Meta:
model = models.Article
interfaces = (graphene.relay.Node,)
tags = graphene.relay.ConnectionField(TagConnection)
@classmethod
def get_node(cls, id, context, info):
return models.Article.objects.get(pk=id)
@graphene.resolve_only_args
def resolve_tags(self):
return self.tags.all() |
Split out the app detail lookup into function | """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def get_app_details(app_key):
url_full = 'https://play.google.com/store/apps/details?id=' + app_key
url = 'https://play.google.com/store/apps/details'
url_params = {'id': app_key }
result = requests.get(url, params=url_params)
if result.status_code != requests.codes.ok:
raise AppNotFoundException(params[0])
else:
soup = BeautifulSoup(result.text, 'html.parser')
return {'title': soup.title.text.replace(' - Android-apps op Google Play', ''), 'url': url_full}
def render(site_path, params):
"""
Look up the Android app details from its Play Store listing
Format of params: <app_key>:optional description
app_key looks like com.linkbubble.license.playstore
"""
app_key = params[0]
details = get_app_details(app_key)
# TODO: render a card(?) with the site's androidapp.html template
return '<a href="' + details['url'] + '">' + details['title'] + '</a>'
| """
paragoo plugin for retrieving card on an Android app
"""
import os
import requests
from bs4 import BeautifulSoup
class AppNotFoundException(Exception):
pass
def render(site_path, params):
"""
Look up the Android app details from its Play Store listing
Format of params: <app_key>
app_key looks like com.linkbubble.license.playstore
"""
app_key = params[0]
url_full = 'https://play.google.com/store/apps/details?id=' + app_key
url = 'https://play.google.com/store/apps/details'
url_params = {'id': app_key }
result = requests.get(url, params=url_params)
if result.status_code != requests.codes.ok:
raise AppNotFoundException(params[0])
else:
soup = BeautifulSoup(result.text, 'html.parser')
# TODO: render a card(?) with the site's androidapp.html template
return '<a href="' + url_full + '">' + soup.title.text.replace(' - Android-apps op Google Play', '') + '</a>'
|
Use Fuyu's VeryCool™ UTBR impl | import discord
def user_to_bot_ratio(guild: discord.Guild):
bots, users = 0, 0
for member in guild.bots:
if member.bot:
bots += 1
else:
users += 1
return bots / users
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
| import discord
def user_to_bot_ratio(guild: discord.Guild):
""" Calculates the user to bot ratio for a guild. """
bots = len(list(filter(lambda u: u.bot, guild.members)))
users = len(list(filter(lambda u: not u.bot, guild.members)))
ratio = bots / users
return ratio
async def is_blacklisted(bot, guild_id: int) -> bool:
""" Returns a bool indicating whether a guild has been blacklisted. """
async with bot.pgpool.acquire() as conn:
blacklisted_record = await conn.fetchrow('SELECT * FROM blacklisted_guilds WHERE guild_id = $1', guild_id)
return blacklisted_record is not None
async def is_bot_collection(bot, guild: discord.Guild):
""" Returns a bool indicating whether a guild is a collection. """
if await is_blacklisted(bot, guild.id):
return True
# keywords in the guild name
if any([keyword in guild.name.lower() for keyword in ('bot collection', 'bot hell')]):
return True
# special guilds that shouldn't be classified as a bot collection
if guild.id in (110373943822540800, 228317351672545290):
return False
# ratio too big!
if user_to_bot_ratio(guild) >= 8:
return True
return False
|
Update decorators to new signature | package decorator
import (
"context"
"time"
sparta "github.com/mweagle/Sparta"
gocf "github.com/mweagle/go-cloudformation"
"github.com/sirupsen/logrus"
)
// LambdaVersioningDecorator returns a TemplateDecorator
// that is responsible for including a versioning resource
// with the given lambda function
func LambdaVersioningDecorator() sparta.TemplateDecoratorHookFunc {
return func(ctx context.Context,
serviceName string,
lambdaResourceName string,
lambdaResource gocf.LambdaFunction,
resourceMetadata map[string]interface{},
lambdaFunctionCode *gocf.LambdaFunctionCode,
buildID string,
template *gocf.Template,
logger *logrus.Logger) (context.Context, error) {
lambdaResName := sparta.CloudFormationResourceName("LambdaVersion",
buildID,
time.Now().UTC().String())
versionResource := &gocf.LambdaVersion{
FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(),
}
lambdaVersionRes := template.AddResource(lambdaResName, versionResource)
lambdaVersionRes.DeletionPolicy = "Retain"
// That's it...
return ctx, nil
}
}
| package decorator
import (
"time"
sparta "github.com/mweagle/Sparta"
gocf "github.com/mweagle/go-cloudformation"
"github.com/sirupsen/logrus"
)
// LambdaVersioningDecorator returns a TemplateDecorator
// that is responsible for including a versioning resource
// with the given lambda function
func LambdaVersioningDecorator() sparta.TemplateDecoratorHookFunc {
return func(serviceName string,
lambdaResourceName string,
lambdaResource gocf.LambdaFunction,
resourceMetadata map[string]interface{},
S3Bucket string,
S3Key string,
buildID string,
template *gocf.Template,
context map[string]interface{},
logger *logrus.Logger) error {
lambdaResName := sparta.CloudFormationResourceName("LambdaVersion",
buildID,
time.Now().UTC().String())
versionResource := &gocf.LambdaVersion{
FunctionName: gocf.GetAtt(lambdaResourceName, "Arn").String(),
}
lambdaVersionRes := template.AddResource(lambdaResName, versionResource)
lambdaVersionRes.DeletionPolicy = "Retain"
// That's it...
return nil
}
}
|
Fix event teams parser for new format | import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on\/team\/(\d*)\?ProgramCode=FRC">(\d*)')
teams = list()
for first_tpid, team_number in teamRe.findall(html):
team = dict()
team["first_tpid"] = int(first_tpid)
team["team_number"] = int(team_number)
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
| import re
from BeautifulSoup import BeautifulSoup
from datafeeds.parser_base import ParserBase
class UsfirstEventTeamsParser(ParserBase):
@classmethod
def parse(self, html):
"""
Find what Teams are attending an Event, and return their team_numbers.
"""
teamRe = re.compile(r'whats-going-on/team/FRC/[A-Za-z0-9=&;\-:]*?">\d+')
teamNumberRe = re.compile(r'\d+$')
tpidRe = re.compile(r'\d+')
teams = list()
for teamResult in teamRe.findall(html):
team = dict()
team["team_number"] = int(teamNumberRe.findall(teamResult)[0])
team["first_tpid"] = int(tpidRe.findall(teamResult)[0])
teams.append(team)
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
more_pages = soup.find('a', {'title': 'Go to next page'}) is not None
return teams, more_pages
|
Allow string arguments (as slugs) when saving/updating EnumFields
This fixes issues where:
MyModel.objects.update(my_enum_field='slug')
would result in SQL like:
UPDATE app_mymodel SET my_enum_field = 'slug'
.. instead of what that's slug's integer value is.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com> | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return 'IntegerField'
def to_python(self, value):
return self.enumeration.to_item(value)
def get_db_prep_save(self, value, connection=None):
return self.to_python(value).value
def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=False):
def prepare(value):
v = self.to_python(value)
return self.get_db_prep_save(v, connection=connection)
if lookup_type == 'exact':
return [prepare(value)]
elif lookup_type == 'in':
return [prepare(v) for v in value]
elif lookup_type == 'isnull':
return []
raise TypeError("Lookup type %r not supported." % lookup_type)
| from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return 'IntegerField'
def to_python(self, value):
return self.enumeration.to_item(value)
def get_db_prep_save(self, value, connection=None):
if hasattr(value, 'value'):
return value.value
return value
def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=False):
def prepare(value):
v = self.to_python(value)
return self.get_db_prep_save(v, connection=connection)
if lookup_type == 'exact':
return [prepare(value)]
elif lookup_type == 'in':
return [prepare(v) for v in value]
elif lookup_type == 'isnull':
return []
raise TypeError("Lookup type %r not supported." % lookup_type)
|
Make the lib pretty complete
Should be able to replicate set up and tear down now | from os.path import abspath, dirname, join
import sh
import psycopg2
import requests
import time
PROJECT_FOLDER=dirname(dirname(abspath(__file__)))
DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker')
def docker_compose(version, *args):
sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version), *args)
def wait_for(condition):
for i in xrange(120):
if condition():
return True
time.sleep(1)
def test_pg():
try:
return sql('select 1 + 1;')[0][0] == 2
except Exception:
return False
def test_es():
try:
return requests.get('http://localhost:9200').json()['tagline'] == 'You Know, for Search'
except Exception:
return False
def sql(statement):
with psycopg2.connect(host='localhost', port=5432, user='postgres', dbname='postgres') as conn:
with conn.cursor() as cursor:
cursor.execute(statement)
return cursor.fetchall()
| from os.path import abspath, dirname, join
import sh
import psycopg2
import requests
PROJECT_FOLDER=dirname(dirname(abspath(__file__)))
DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker')
def docker_compose(version, *args):
sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version), *args)
def test_pg():
def callback(cursor):
cursor.execute('select 1 + 1;')
return cursor.fetchone()[0] == 2
def error():
return False
return sql(callback, error)
def test_es():
try:
return requests.get('http://localhost:9200').json()['tagline'] == 'You Know, for Search'
except Exception:
return False
def sql(callback, error):
try:
with psycopg2.connect(host='localhost', port=5432, user='postgres', dbname='postgres') as conn:
with conn.cursor() as cursor:
return callback(cursor)
except Exception:
return error()
|
Make it easier to debug with logging. | # Django settings for c10kdemo project.
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = True
INSTALLED_APPS = (
'c10ktools',
'gameoflife',
'django.contrib.staticfiles',
)
LOGGING = {
'disable_existing_loggers': False,
'version': 1,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.request': {
'handlers': ['console'],
},
},
}
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'c10kdemo.urls'
SECRET_KEY = os.environ.get('SECRET_KEY', 'whatever')
STATIC_URL = '/static/'
TIME_ZONE = 'Europe/Paris'
WSGI_APPLICATION = 'c10kdemo.wsgi.application'
del os
| # Django settings for c10kdemo project.
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
DEBUG = True
INSTALLED_APPS = (
'c10ktools',
'gameoflife',
'django.contrib.staticfiles',
)
LOGGING = {
'version': 1,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.request': {
'handlers': ['console'],
},
},
}
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'c10kdemo.urls'
SECRET_KEY = os.environ.get('SECRET_KEY', 'whatever')
STATIC_URL = '/static/'
TIME_ZONE = 'Europe/Paris'
WSGI_APPLICATION = 'c10kdemo.wsgi.application'
del os
|
Test for error if not a postcode. | """
Integration-style tests for binalerts. These tests think of things from the web
frontend point of view. They are designed to make sure the application behaves
as required to the user.
"""
# Various tips on testing forms:
# http://stackoverflow.com/questions/2257958/django-unit-testing-for-form-edit
from django.test import TestCase
from django.test import Client
class FrontPageTest(TestCase):
def setUp(self):
self.c = Client()
def test_asks_for_postcode(self):
response = self.c.get('/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.template.name, 'binalerts/frontpage.html')
self.assertContains(response, 'Please enter your postcode')
self.assertContains(response, '<input type="text" name="postcode" id="id_postcode" />')
self.assertContains(response, '<input type="submit" value="Go" />')
def test_error_if_not_postcode(self):
response = self.c.post('/', { 'postcode': 'notapostcode' })
self.assertEqual(response.template.name, 'binalerts/frontpage.html')
self.assertContains(response, 'Sorry')
# Example doctest in case we need it later
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
| """
Integration-style tests for binalerts. These tests think of things from the web
frontend point of view. They are designed to make sure the application behaves
as required to the user.
"""
# Various tips on testing forms:
# http://stackoverflow.com/questions/2257958/django-unit-testing-for-form-edit
from django.test import TestCase
from django.test import Client
class FrontPageTest(TestCase):
def setUp(self):
self.c = Client()
def test_frontpage_asks_for_postcode(self):
response = self.c.get('/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Please enter your postcode')
self.assertContains(response, '<input type="text" name="postcode" id="id_postcode" />')
self.assertContains(response, '<input type="submit" value="Go" />')
self.assertEqual(response.template.name, 'binalerts/frontpage.html')
# Example doctest in case we need it later
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
|
Make a comment (about code suggestions clearer).
I want nice ways to avoid @SuppressWarnings, that is without
too much code repetitions (such as repeatedly casting the same
object to multiple types) | package strength;
import java.util.Comparator;
import com.google.common.collect.Ordering;
import strength.ranking.PokerHandRanking;
/**
* A {@link Comparator} implementation for poker hand rankings.
* This is actually a subclass of Guava's {@link Ordering} class, which
* descends from Java's Comparator class.
*/
public class PokerHandComparator extends Ordering<PokerHandRanking> {
@SuppressWarnings("deprecation")
@Override
public int compare(final PokerHandRanking h1, final PokerHandRanking h2) {
/* First, check if the hands are in the same category. If not, the result
* of the comparison is the result of comparing the Hand-Categories, according
* to the order degined in the PokerHandKindenumeration type. */
{
final int handKindComparisonResult = Comparator.comparing((PokerHandRanking r) -> r.handKind).compare(h1, h2);
if (handKindComparisonResult != 0)
return handKindComparisonResult;
}
/* If the two hands being compared were of the same category, then
* a specific comparison method for that category is called.
* For instance, PairRanking#compareTo(), or FlushRanking#compareTo(),
* according to the common class of the two hand objects.
*
* This is where a Java warning concerning generic types is suppressed.
* Sugestions on how to nicely avoid suppressing warnings here are welcome :-) */
assert h1.handKind == h2.handKind;
return h1.compareTo(h2);
}
}
| package strength;
import java.util.Comparator;
import com.google.common.collect.Ordering;
import strength.ranking.PokerHandRanking;
/**
* A {@link Comparator} implementation for poker hand rankings.
* This is actually a subclass of Guava's {@link Ordering} class, which
* descends from Java's Comparator class.
*/
public class PokerHandComparator extends Ordering<PokerHandRanking> {
@SuppressWarnings("deprecation")
@Override
public int compare(final PokerHandRanking h1, final PokerHandRanking h2) {
/* First, check if the hands are in the same category. If not, the result
* of the comparison is the result of comparing the Hand-Categories, according
* to the order degined in the PokerHandKindenumeration type. */
{
final int handKindComparisonResult = Comparator.comparing((PokerHandRanking r) -> r.handKind).compare(h1, h2);
if (handKindComparisonResult != 0)
return handKindComparisonResult;
}
/* If the two hands being compared were of the same category, then
* a specific comparison method for that category is called.
* For instance, PairRanking#compareTo(), or FlushRanking#compareTo(),
* according to the common class of the two hand objects.
*
* This is where a Java warning concerning generic types is suppressed.
* Sugestions on how to avoid suppressing warnings here are welcome :-) */
assert h1.handKind == h2.handKind;
return h1.compareTo(h2);
}
}
|
Use webhook URL that should be available from anywhere
(with working Internet connection) | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key'
}
describe('notify', () => {
it('fails when no webhook URL is provided via environment variable', () => {
expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument')
})
it('fails when supplied webhook is not a valid URL', () => {
expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"')
})
it('submits POST with payload to existing URL', () => {
expect(() => webhook.notify(challenge, 'https://webhook.site/f69013b6-c475-46ed-973f-aa07e5e573a3')).to.not.throw()
})
})
})
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key'
}
describe('notify', () => {
it('fails when no webhook URL is provided via environment variable', () => {
expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument')
})
it('fails when supplied webhook is not a valid URL', () => {
expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"')
})
it('submits POST with payload to existing URL', () => {
expect(() => webhook.notify(challenge, 'http://localhost')).to.not.throw()
})
})
})
|
Use short axis names to prevent windows path overflow | #!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import os
import subprocess
import sys
def run():
toolchain = os.getenv('TLC')
if not toolchain:
sys.exit('Environment variable TLC is empty (TooLChain)')
config = os.getenv('CFG')
if not config:
sys.exit('Environment variable CFG is empty (ConFiG)')
build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py')
print('Run script: {}'.format(build))
print('Toolchain: {}'.format(toolchain))
print('Config: {}'.format(config))
args = [
sys.executable,
build,
'--toolchain',
toolchain,
'--config',
config,
'--verbose',
'--test'
]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError as error:
print(error)
print(error.output)
sys.exit(1)
| #!/usr/bin/env python3
# Copyright (c) 2014, Ruslan Baratov
# All rights reserved.
import os
import subprocess
import sys
def run():
toolchain = os.getenv('TOOLCHAIN')
if not toolchain:
sys.exit('Environment variable TOOLCHAIN is empty')
build_type = os.getenv('BUILD_TYPE')
if not build_type:
sys.exit('Environment variable BUILD_TYPE is empty')
build = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build.py')
print('Run script: {}'.format(build))
print('Toolchain: {}'.format(toolchain))
print('Config: {}'.format(build_type))
args = [
sys.executable,
build,
'--toolchain',
toolchain,
'--config',
build_type,
'--verbose',
'--test'
]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError as error:
print(error)
print(error.output)
sys.exit(1)
|
Include *.js and *.jinja files in sdist packages | """
----------------
Flask-Mustache
----------------
`Mustache`__ integration for Flask.
__ http://mustache.github.com/
Flask-Mustache adds template helpers and context processors to assist
Flask developers with integrating the Mustache library into their
development process.
"""
from setuptools import setup
setup(
name='Flask-MustacheJS',
version='0.4.3',
url='https://github.com/bradleywright/flask-mustache',
license='BSD',
author='Bradley Wright',
author_email='brad@intranation.com',
description='Mustache integration in Flask, with Jinja and client-side libraries.',
long_description=__doc__,
packages=['flask_mustache'],
zip_safe=False,
include_package_data=True,
# include static assets
package_data = {
'': ['*.jinja', '*.js']
},
platforms='any',
install_requires=[
'Flask',
'pystache'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| """
----------------
Flask-Mustache
----------------
`Mustache`__ integration for Flask.
__ http://mustache.github.com/
Flask-Mustache adds template helpers and context processors to assist
Flask developers with integrating the Mustache library into their
development process.
"""
from setuptools import setup
setup(
name='Flask-MustacheJS',
version='0.4.2',
url='https://github.com/bradleywright/flask-mustache',
license='BSD',
author='Bradley Wright',
author_email='brad@intranation.com',
description='Mustache integration in Flask, with Jinja and client-side libraries.',
long_description=__doc__,
packages=['flask_mustache'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask',
'pystache'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Add M&E Expert to polls entries permissions | from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists()\
and not User.objects.filter(
pk=request.user.pk, groups__name='M&E Expert').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
| from django.conf.urls import url
from molo.polls.admin import QuestionsModelAdmin
from molo.polls.admin_views import QuestionResultsAdminView
from wagtail.wagtailcore import hooks
from wagtail.contrib.modeladmin.options import modeladmin_register
from django.contrib.auth.models import User
@hooks.register('register_admin_urls')
def register_question_results_admin_view_url():
return [
url(r'polls/question/(?P<parent>\d+)/results/$',
QuestionResultsAdminView.as_view(),
name='question-results-admin'),
]
modeladmin_register(QuestionsModelAdmin)
@hooks.register('construct_main_menu')
def show_polls_entries_for_users_have_access(request, menu_items):
if not request.user.is_superuser and not User.objects.filter(
pk=request.user.pk, groups__name='Moderators').exists():
menu_items[:] = [
item for item in menu_items if item.name != 'polls']
|
Switch luci-py tests to use gcloud SDK.
R=maruel@chromium.org, iannucci@chromium.org
BUG=835919
Change-Id: Iaf7f361343dfebfc7fd603b8b996ad9fa5412f52
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1684451
Reviewed-by: Andrii Shyshkalov <a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org>
Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org> | # Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# TODO(vadimsh): Remove this once LUCI_PY_USE_GCLOUD is set by default.
os.environ['LUCI_PY_USE_GCLOUD'] = '1'
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
| # Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine/Django test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
Make sure to ship translations with sdists. | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'django-orderable',
version = '1.0.1',
description = 'Model ordering for the Django administration site.',
author = 'Ted Kaemming',
author_email = 'ted@kaemming.com',
url = 'http://www.github.com/tkaemming/django-orderable/',
packages = find_packages('src'),
package_dir = {'': 'src'},
package_data = {
'orderable': [
'templates/orderable/change_list.html',
'templates/orderable/edit_inline/stacked.html',
'templates/orderable/edit_inline/tabular.html',
'templates/orderable/orderable.js',
'locale/*/LC_MESSAGES/django.*',
]
},
install_requires = ['setuptools'],
zip_safe = False
) | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'django-orderable',
version = '1.0.1',
description = 'Model ordering for the Django administration site.',
author = 'Ted Kaemming',
author_email = 'ted@kaemming.com',
url = 'http://www.github.com/tkaemming/django-orderable/',
packages = find_packages('src'),
package_dir = {'': 'src'},
package_data = {
'orderable': [
'templates/orderable/change_list.html',
'templates/orderable/edit_inline/stacked.html',
'templates/orderable/edit_inline/tabular.html',
'templates/orderable/orderable.js',
]
},
install_requires = ['setuptools'],
zip_safe = False
) |
Remove arrow func compatible with old version node | const rollup = require('rollup').rollup;
const babel = require('rollup-plugin-babel');
rollup({
entry: './src/index.js',
external: [
'babel-runtime/core-js/json/stringify',
'babel-runtime/core-js/object/assign',
'babel-runtime/helpers/asyncToGenerator',
'babel-runtime/regenerator',
'fs',
'util',
'path',
'node-sass',
'rollup-pluginutils'
],
plugins: [
babel({
runtimeHelpers: true
})
]
}).then(function (bundle) {
bundle.write({
dest: 'dist/rollup-plugin-sass.cjs.js',
format: 'cjs'
});
bundle.write({
dest: 'dist/rollup-plugin-sass.es6.js',
format: 'es6'
});
}).catch(console.error);
| const rollup = require('rollup').rollup;
const babel = require('rollup-plugin-babel');
rollup({
entry: './src/index.js',
external: [
'babel-runtime/core-js/json/stringify',
'babel-runtime/core-js/object/assign',
'babel-runtime/helpers/asyncToGenerator',
'babel-runtime/regenerator',
'fs',
'util',
'path',
'node-sass',
'rollup-pluginutils'
],
plugins: [
babel({
runtimeHelpers: true
})
]
}).then((bundle) => {
bundle.write({
dest: 'dist/rollup-plugin-sass.cjs.js',
format: 'cjs'
});
bundle.write({
dest: 'dist/rollup-plugin-sass.es6.js',
format: 'es6'
});
}).catch(console.error); |
Fix checking a name against an object | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
return [ ("remoteregister", 1, self.sendRemoteConnectNotice),
("servernoticetype", 1, self.checkSnoType),
("startburstcommand", 1, self.markStartBurst),
("endburstcommand", 1, self.markEndBurst) ]
def sendRemoteConnectNotice(self, user, *params):
server = self.ircd.servers[user.uuid[:3]]
if server == self.burstingServer:
return
server = server.name
message = "Client connected on {}: {} ({}) [{}]".format(server, user.hostmaskWithRealHost(), user.ip, user.gecos)
snodata = {
"mask": "connect",
"message": message
}
self.ircd.runActionProcessing("sendservernotice", snodata)
def checkSnoType(self, user, typename):
return typename == "remoteconnect"
def markStartBurst(self, server, command):
self.burstingServer = server
def markEndBurst(self, server, command):
self.burstingServer = None
snoRemoteConnect = SnoRemoteConnect() | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
return [ ("remoteregister", 1, self.sendRemoteConnectNotice),
("servernoticetype", 1, self.checkSnoType),
("startburstcommand", 1, self.markStartBurst),
("endburstcommand", 1, self.markEndBurst) ]
def sendRemoteConnectNotice(self, user, *params):
server = self.ircd.servers[user.uuid[:3]].name
if server == self.burstingServer:
return
message = "Client connected on {}: {} ({}) [{}]".format(server, user.hostmaskWithRealHost(), user.ip, user.gecos)
snodata = {
"mask": "connect",
"message": message
}
self.ircd.runActionProcessing("sendservernotice", snodata)
def checkSnoType(self, user, typename):
return typename == "remoteconnect"
def markStartBurst(self, server, command):
self.burstingServer = server
def markEndBurst(self, server, command):
self.burstingServer = None
snoRemoteConnect = SnoRemoteConnect() |
Use token reference from env | import Telegraf from 'telegraf';
import config from 'config';
import feedReader from './feed';
/* commands */
import commands from './commands';
/* helpers */
import { sendIntervalMessages } from './helpers/messageHelper';
// TODO move this to a DB
const chatids = process.env.CHAT_IDS || JSON.parse(config.get('CHAT_IDS'));
/** telegram app **/
const token = process.env.token || config.get('token');
const URL = process.env.URL || config.get('URL');
const PORT = process.env.PORT || config.get('PORT');
const isDevelopment = process.env.NODE_ENV === 'development';
const app = new Telegraf(token);
/* add commands from command array */
commands.forEach(command => app.command(command.key, ctx => command.func(ctx)));
// start telegram listeners
if (isDevelopment) {
// remove webhook in case any is attached from previous sessions
app.telegram.setWebhook();
app.startPolling();
} else {
app.telegram.setWebhook(`${URL}/bot${token}`);
app.startWebhook(`/bot${token}`, null, PORT);
}
// start reading rss articles
feedReader.read((articles) => {
if (!articles) return;
chatids.forEach(id => sendIntervalMessages(app.telegram, id, articles));
});
| import Telegraf from 'telegraf';
import config from 'config';
import feedReader from './feed';
/* commands */
import commands from './commands';
/* helpers */
import { sendIntervalMessages } from './helpers/messageHelper';
// TODO move this to a DB
const chatids = process.env.CHAT_IDS || JSON.parse(config.get('CHAT_IDS'));
const app = new Telegraf(config.get('token'));
/* add commands from command array */
commands.forEach(command => app.command(command.key, ctx => command.func(ctx)));
/** telegram app **/
const token = process.env.token || config.get('token');
const URL = process.env.URL || config.get('URL');
const PORT = process.env.PORT || config.get('PORT');
const isDevelopment = process.env.NODE_ENV === 'development';
// start telegram listeners
if (isDevelopment) {
// remove webhook in case any is attached from previous sessions
app.telegram.setWebhook();
app.startPolling();
} else {
app.telegram.setWebhook(`${URL}/bot${token}`);
app.startWebhook(`/bot${token}`, null, PORT);
}
// start reading rss articles
feedReader.read((articles) => {
if (!articles) return;
chatids.forEach(id => sendIntervalMessages(app.telegram, id, articles));
});
|
Use selectors to get the loggedIn state | import React, {Component} from 'react';
import {connect} from 'react-redux';
import AppBarLayout from 'components/AppBar';
import Logo from './Logo';
import LoginActions from './LoginActions';
import LoggedInActions from './LoggedInActions';
import {authSelectors} from 'modules/auth'
class AppBar extends Component {
render() {
let {loggedIn} = this.props;
const logo = <Logo />
const actions = loggedIn ? <LoggedInActions /> : <LoginActions />
return (
<AppBarLayout
logo={logo}
actions={actions}
/>
)
}
}
const mapStateToProps = state => ({
loggedIn: authSelectors.loggedIn(state)
})
export default connect(mapStateToProps)(AppBar);
| import React, {Component} from 'react';
import {connect} from 'react-redux';
import AppBarLayout from 'components/AppBar';
import Logo from './Logo';
import LoginActions from './LoginActions';
import LoggedInActions from './LoggedInActions';
class AppBar extends Component {
render() {
let {loggedIn} = this.props;
const logo = <Logo />
const actions = loggedIn ? <LoggedInActions /> : <LoginActions />
return (
<AppBarLayout
logo={logo}
actions={actions}
/>
)
}
}
const mapStateToProps = state => ({
loggedIn: state.auth.loggedIn
})
export default connect(mapStateToProps)(AppBar);
|
Update spectrogram plot file size | from scikits.audiolab import Sndfile
import matplotlib.pyplot as plt
import os
dt = 0.05
Fs = int(1.0/dt)
print 'started...'
current_dir = os.path.dirname(__file__)
print current_dir
for (dirpath, dirnames, filenames) in os.walk(current_dir):
for filename in filenames:
path = os.path.join(current_dir + "/" + filename)
print (path)
fname, extension = os.path.splitext(path)
print (extension)
if extension == '.flac':
soundfile = Sndfile(path, "r")
signal = soundfile.read_frames(soundfile.nframes)
plt.specgram(signal, NFFT=512, Fs=Fs)
outputfile = path.replace(extension, '.png')
print (outputfile)
fig = plt.gcf()
defaultSize = [6.4, 4.8]
# modify height_ratio to change the height of the generated graph file
width_ratio = 1.58
height_ratio = 3.26
fig.set_size_inches( (defaultSize[0]*width_ratio, defaultSize[1]/height_ratio) )
print fig.get_size_inches()
fig.savefig(outputfile, bbox_inches='tight', pad_inches=0) | from scikits.audiolab import Sndfile
import matplotlib.pyplot as plt
import os
dt = 0.05
Fs = int(1.0/dt)
current_dir = os.path.dirname(__file__)
for (dirpath, dirnames, filenames) in os.walk(current_dir):
for filename in filenames:
path = os.path.join(current_dir + "/" + filename)
print (path)
fname, extension = os.path.splitext(path)
print (extension)
if extension == '.flac':
soundfile = Sndfile(path, "r")
signal = soundfile.read_frames(soundfile.nframes)
plt.specgram(signal, NFFT=512, Fs=Fs)
outputfile = path.replace(extension, '.png')
print (outputfile)
plt.savefig(outputfile) |
Remove input POST encoding loop
It caused a warning that read directly into JSON.parse(data) and
appeared to be unnecessary. | <?php
$url = 'http://bidfta.bidqt.com/BidFTA/services/invoices/queryExecutor/queries/FTALocations?size=100';
//CURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Origin: http://bidfta.bidqt.com','Referer: http://bidfta.bidqt.com','X-Requested-With: XMLHttpRequest'));
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $head;
?>
| <?php
$url = 'http://bidfta.bidqt.com/BidFTA/services/invoices/queryExecutor/queries/FTALocations?size=50';
//Encode POST values
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//CURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Origin: http://bidfta.bidqt.com','Referer: http://bidfta.bidqt.com','X-Requested-With: XMLHttpRequest'));
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $head;
?>
|
Test not just that there's no error, but also that there's a result | var RowConstants = require('./constants/row_constants.js'),
QueryConstants = require('./constants/query_constants.js'),
client = require('./client.js'),
Dispatcher = require('./dispatcher.js');
var actions = {
listQueries(callback) {
client.list((err, res) => {
if (!err) {
Dispatcher.handleViewAction({
actionType: QueryConstants.QUERY_LISTED,
value: res
});
if (callback) callback();
}
});
},
deleteQuery(id) {
client.deleteQuery(id, (err, res) => {
if (!err) {
actions.listQueries();
}
});
},
saveQuery(name, query) {
client.saveQuery(name, query, (err, res) => {
console.log(arguments);
});
},
runQuery(query) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_START
});
client.runQuery(query, (err, res) => {
if (!err && res) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_DONE,
value: res
});
}
});
}
};
module.exports = actions;
| var RowConstants = require('./constants/row_constants.js'),
QueryConstants = require('./constants/query_constants.js'),
client = require('./client.js'),
Dispatcher = require('./dispatcher.js');
var actions = {
listQueries(callback) {
client.list((err, res) => {
if (!err) {
Dispatcher.handleViewAction({
actionType: QueryConstants.QUERY_LISTED,
value: res
});
if (callback) callback();
}
});
},
deleteQuery(id) {
client.deleteQuery(id, (err, res) => {
if (!err) {
actions.listQueries();
}
});
},
saveQuery(name, query) {
client.saveQuery(name, query, (err, res) => {
console.log(arguments);
});
},
runQuery(query) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_START
});
client.runQuery(query, (err, res) => {
if (!err) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_DONE,
value: res
});
}
});
}
};
module.exports = actions;
|
Correct a bug in creating directories as needed for output. | #! /usr/bin/env python
import os
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn = [1] # needed because nose does not send() to test generator
# make sure the output target directory exists
if not os.path.exists(os.path.dirname(sim_output)):
os.makedirs(os.path.dirname(sim_output))
cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
check_cmd(cmd, cwd, holdsrtn)
rtn = holdsrtn[0]
if rtn != 0:
return # don"t execute further commands
| #! /usr/bin/env python
import os
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn = [1] # needed because nose does not send() to test generator
# make sure the output target directory exists
if not os.path.exists(sim_output):
os.makedirs(sim_output)
cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
check_cmd(cmd, cwd, holdsrtn)
rtn = holdsrtn[0]
if rtn != 0:
return # don"t execute further commands
|
Correct property and parameter name | <?php
namespace OpenConext\EngineBlock\Driver\File;
use OpenConext\EngineBlock\Assert\Assertion;
use OpenConext\EngineBlock\Driver\StorageDriver;
final class FileStorageDriver implements StorageDriver
{
/**
* @var FileHandler
*/
private $fileHandler;
/**
* @var string
*/
private $filePath;
/**
* @param FileHandler $fileHandler
* @param string $filePath
*/
public function __construct(FileHandler $fileHandler, $filePath)
{
Assertion::nonEmptyString($filePath, 'filePath');
$this->fileHandler = $fileHandler;
$this->filePath = $filePath;
}
public function save($data)
{
Assertion::string($data, 'Data to save must be a string, "%s" given');
$this->fileHandler->writeTo($data, $this->filePath);
}
public function load()
{
return $this->fileHandler->readFrom($this->filePath);
}
}
| <?php
namespace OpenConext\EngineBlock\Driver\File;
use OpenConext\EngineBlock\Assert\Assertion;
use OpenConext\EngineBlock\Driver\StorageDriver;
final class FileStorageDriver implements StorageDriver
{
/**
* @var FileHandler
*/
private $fileAccessor;
/**
* @var string
*/
private $filePath;
/**
* @param FileHandler $fileAccessor
* @param string $filePath
*/
public function __construct(FileHandler $fileAccessor, $filePath)
{
Assertion::nonEmptyString($filePath, 'filePath');
$this->fileAccessor = $fileAccessor;
$this->filePath = $filePath;
}
public function save($data)
{
Assertion::string($data, 'Data to save must be a string, "%s" given');
$this->fileAccessor->writeTo($data, $this->filePath);
}
public function load()
{
return $this->fileAccessor->readFrom($this->filePath);
}
}
|
fix: Make sentry debug controllable with env variable
DEBUG_SENTRY=true will enable it. | const { ApolloServer } = require('apollo-server-micro')
const { schema } = require('./schema')
const { createErrorFormatter, sentryIgnoreErrors } = require('./errors')
module.exports = function createHandler(options) {
let Sentry
if (options.sentryDsn) {
Sentry = require('@sentry/node')
Sentry.init({
dsn: options.sentryDsn,
release: options.release,
environment: process.env.NODE_ENV,
ignoreErrors: sentryIgnoreErrors,
onFatalError(error) {
console.error(error, error.response)
},
debug: process.env.DEBUG_SENTRY == 'true',
})
}
const formatError = createErrorFormatter(Sentry)
const apolloServer = new ApolloServer({ schema, formatError })
return apolloServer.createHandler({ path: '/' })
}
| const { ApolloServer } = require('apollo-server-micro')
const { schema } = require('./schema')
const { createErrorFormatter, sentryIgnoreErrors } = require('./errors')
module.exports = function createHandler(options) {
let Sentry
if (options.sentryDsn) {
Sentry = require('@sentry/node')
Sentry.init({
dsn: options.sentryDsn,
release: options.release,
environment: process.env.NODE_ENV,
ignoreErrors: sentryIgnoreErrors,
onFatalError(error) {
console.error(error, error.response)
},
debug: true,
})
}
const formatError = createErrorFormatter(Sentry)
const apolloServer = new ApolloServer({ schema, formatError })
return apolloServer.createHandler({ path: '/' })
}
|
[DDW-165] Add UTC offset to Daedalus logs, Remove logging output from the web console | import path from 'path';
import { ipcMain } from 'electron';
import Log from 'electron-log';
import { daedalusLogger } from './remoteLog';
import ensureDirectoryExists from './ensureDirectoryExists';
import { pubLogsFolderPath, APP_NAME } from '../config';
export const setupLogging = () => {
const logFilePath = path.join(pubLogsFolderPath, APP_NAME + '.log');
ensureDirectoryExists(pubLogsFolderPath);
Log.transports.console.level = 'warn';
Log.transports.rendererConsole.level = 'warn';
Log.transports.file.level = 'debug';
Log.transports.file.maxSize = 20 * 1024 * 1024;
Log.transports.file.file = logFilePath;
Log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms} {z}] [{level}] {text}';
try {
let sendLogsToRemoteServer;
ipcMain.on('send-logs-choice', (event, sendLogs) => {
sendLogsToRemoteServer = sendLogs;
});
ipcMain.on('log-to-remote', (event, logEntry) => {
if (sendLogsToRemoteServer) daedalusLogger.info(logEntry);
});
} catch (error) {
Log.error('Error setting up log logging to remote server', error);
}
};
| import path from 'path';
import { ipcMain } from 'electron';
import Log from 'electron-log';
import { daedalusLogger } from './remoteLog';
import ensureDirectoryExists from './ensureDirectoryExists';
import { pubLogsFolderPath, APP_NAME } from '../config';
export const setupLogging = () => {
const logFilePath = path.join(pubLogsFolderPath, APP_NAME + '.log');
ensureDirectoryExists(pubLogsFolderPath);
Log.transports.console.level = 'warn';
Log.transports.file.level = 'debug';
Log.transports.file.maxSize = 20 * 1024 * 1024;
Log.transports.file.file = logFilePath;
try {
let sendLogsToRemoteServer;
ipcMain.on('send-logs-choice', (event, sendLogs) => {
sendLogsToRemoteServer = sendLogs;
});
ipcMain.on('log-to-remote', (event, logEntry) => {
if (sendLogsToRemoteServer) daedalusLogger.info(logEntry);
});
} catch (error) {
Log.error('Error setting up log logging to remote server', error);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.